[
  {
    "path": ".gitignore",
    "content": "/bam\n/.bam\n/config.lua\n/objs\n__pycache__/\n*.pyc\n*.pyo\nscripts/work/\nsrc/game/generated/\nother/icons/*.res\n/SDL.dll\n/freetype.dll\n/autoexec.cfg\n\n/crapnet*\n/dilate*\n/fake_server*\n/map_resave*\n/map_version*\n/mastersrv*\n/packetgen*\n/teeworlds*\n/teeworlds_srv*\n/serverlaunch*\n/tileset_border*\n/versionsrv*\n"
  },
  {
    "path": ".gitmodules",
    "content": "[submodule \"data/languages\"]\n\tpath = data/languages\n\turl = git://github.com/teeworlds/teeworlds-translation.git\n[submodule \"data/maps\"]\n\tpath = data/maps\n\turl = git://github.com/teeworlds/teeworlds-maps.git\n"
  },
  {
    "path": "bam.lua",
    "content": "CheckVersion(\"0.4\")\n\nImport(\"configure.lua\")\nImport(\"other/sdl/sdl.lua\")\nImport(\"other/freetype/freetype.lua\")\n\n--- Setup Config -------\nconfig = NewConfig()\nconfig:Add(OptCCompiler(\"compiler\"))\nconfig:Add(OptTestCompileC(\"stackprotector\", \"int main(){return 0;}\", \"-fstack-protector -fstack-protector-all\"))\nconfig:Add(OptTestCompileC(\"minmacosxsdk\", \"int main(){return 0;}\", \"-mmacosx-version-min=10.5 -isysroot /Developer/SDKs/MacOSX10.5.sdk\"))\nconfig:Add(OptTestCompileC(\"macosxppc\", \"int main(){return 0;}\", \"-arch ppc\"))\nconfig:Add(OptLibrary(\"zlib\", \"zlib.h\", false))\nconfig:Add(SDL.OptFind(\"sdl\", true))\nconfig:Add(FreeType.OptFind(\"freetype\", true))\nconfig:Finalize(\"config.lua\")\n\n-- data compiler\nfunction Script(name)\n\tif family == \"windows\" then\n\t\treturn str_replace(name, \"/\", \"\\\\\")\n\tend\n\treturn \"python \" .. name\nend\n\nfunction CHash(output, ...)\n\tlocal inputs = TableFlatten({...})\n\n\toutput = Path(output)\n\n\t-- compile all the files\n\tlocal cmd = Script(\"scripts/cmd5.py\") .. \" \"\n\tfor index, inname in ipairs(inputs) do\n\t\tcmd = cmd .. Path(inname) .. \" \"\n\tend\n\n\tcmd = cmd .. \" > \" .. output\n\n\tAddJob(output, \"cmd5 \" .. output, cmd)\n\tfor index, inname in ipairs(inputs) do\n\t\tAddDependency(output, inname)\n\tend\n\tAddDependency(output, \"scripts/cmd5.py\")\n\treturn output\nend\n\n--[[\nfunction DuplicateDirectoryStructure(orgpath, srcpath, dstpath)\n\tfor _,v in pairs(CollectDirs(srcpath .. \"/\")) do\n\t\tMakeDirectory(dstpath .. \"/\" .. string.sub(v, string.len(orgpath)+2))\n\t\tDuplicateDirectoryStructure(orgpath, v, dstpath)\n\tend\nend\n\nDuplicateDirectoryStructure(\"src\", \"src\", \"objs\")\n]]\n\nfunction ResCompile(scriptfile)\n\tscriptfile = Path(scriptfile)\n\tif config.compiler.driver == \"cl\" then\n\t\toutput = PathBase(scriptfile) .. \".res\"\n\t\tAddJob(output, \"rc \" .. scriptfile, \"rc /fo \" .. output .. \" \" .. scriptfile)\n\telseif config.compiler.driver == \"gcc\" then\n\t\toutput = PathBase(scriptfile) .. \".coff\"\n\t\tAddJob(output, \"windres \" .. scriptfile, \"windres -i \" .. scriptfile .. \" -o \" .. output)\n\tend\n\tAddDependency(output, scriptfile)\n\treturn output\nend\n\nfunction Dat2c(datafile, sourcefile, arrayname)\n\tdatafile = Path(datafile)\n\tsourcefile = Path(sourcefile)\n\n\tAddJob(\n\t\tsourcefile,\n\t\t\"dat2c \" .. PathFilename(sourcefile) .. \" = \" .. PathFilename(datafile),\n\t\tScript(\"scripts/dat2c.py\").. \"\\\" \" .. sourcefile .. \" \" .. datafile .. \" \" .. arrayname\n\t)\n\tAddDependency(sourcefile, datafile)\n\treturn sourcefile\nend\n\nfunction ContentCompile(action, output)\n\toutput = Path(output)\n\tAddJob(\n\t\toutput,\n\t\taction .. \" > \" .. output,\n\t\t--Script(\"datasrc/compile.py\") .. \"\\\" \".. Path(output) .. \" \" .. action\n\t\tScript(\"datasrc/compile.py\") .. \" \" .. action .. \" > \" .. Path(output)\n\t)\n\tAddDependency(output, Path(\"datasrc/content.py\")) -- do this more proper\n\tAddDependency(output, Path(\"datasrc/network.py\"))\n\tAddDependency(output, Path(\"datasrc/compile.py\"))\n\tAddDependency(output, Path(\"datasrc/datatypes.py\"))\n\treturn output\nend\n\n-- Content Compile\nnetwork_source = ContentCompile(\"network_source\", \"src/game/generated/protocol.cpp\")\nnetwork_header = ContentCompile(\"network_header\", \"src/game/generated/protocol.h\")\nclient_content_source = ContentCompile(\"client_content_source\", \"src/game/generated/client_data.cpp\")\nclient_content_header = ContentCompile(\"client_content_header\", \"src/game/generated/client_data.h\")\nserver_content_source = ContentCompile(\"server_content_source\", \"src/game/generated/server_data.cpp\")\nserver_content_header = ContentCompile(\"server_content_header\", \"src/game/generated/server_data.h\")\n\nAddDependency(network_source, network_header)\nAddDependency(client_content_source, client_content_header)\nAddDependency(server_content_source, server_content_header)\n\nnethash = CHash(\"src/game/generated/nethash.cpp\", \"src/engine/shared/protocol.h\", \"src/game/generated/protocol.h\", \"src/game/tuning.h\", \"src/game/gamecore.cpp\", network_header)\n\nclient_link_other = {}\nclient_depends = {}\nserver_link_other = {}\n\nif family == \"windows\" then\n\tif platform == \"win32\" then\n\t\ttable.insert(client_depends, CopyToDirectory(\".\", \"other\\\\freetype\\\\lib32\\\\freetype.dll\"))\n\t\ttable.insert(client_depends, CopyToDirectory(\".\", \"other\\\\sdl\\\\lib32\\\\SDL.dll\"))\n\telse\n\t\ttable.insert(client_depends, CopyToDirectory(\".\", \"other\\\\freetype\\\\lib64\\\\freetype.dll\"))\n\t\ttable.insert(client_depends, CopyToDirectory(\".\", \"other\\\\sdl\\\\lib64\\\\SDL.dll\"))\n\tend\n\n\tif config.compiler.driver == \"cl\" then\n\t\tclient_link_other = {ResCompile(\"other/icons/teeworlds_cl.rc\")}\n\t\tserver_link_other = {ResCompile(\"other/icons/teeworlds_srv_cl.rc\")}\n\telseif config.compiler.driver == \"gcc\" then\n\t\tclient_link_other = {ResCompile(\"other/icons/teeworlds_gcc.rc\")}\n\t\tserver_link_other = {ResCompile(\"other/icons/teeworlds_srv_gcc.rc\")}\n\tend\nend\n\nfunction Intermediate_Output(settings, input)\n\treturn \"objs/\" .. string.sub(PathBase(input), string.len(\"src/\")+1) .. settings.config_ext\nend\n\nfunction build(settings)\n\t-- apply compiler settings\n\tconfig.compiler:Apply(settings)\n\t\n\t--settings.objdir = Path(\"objs\")\n\tsettings.cc.Output = Intermediate_Output\n\n\tif config.compiler.driver == \"cl\" then\n\t\tsettings.cc.flags:Add(\"/wd4244\")\n\telse\n\t\tsettings.cc.flags:Add(\"-Wall\", \"-fno-exceptions\")\n\t\tif family == \"windows\" then\n\t\t\t-- disable visibility attribute support for gcc on windows\n\t\t\tsettings.cc.defines:Add(\"NO_VIZ\")\n\t\telseif platform == \"macosx\" then\n\t\t\tsettings.cc.flags:Add(\"-mmacosx-version-min=10.5\")\n\t\t\tsettings.link.flags:Add(\"-mmacosx-version-min=10.5\")\n\t\t\tif config.minmacosxsdk.value == 1 then\n\t\t\t\tsettings.cc.flags:Add(\"-isysroot /Developer/SDKs/MacOSX10.5.sdk\")\n\t\t\t\tsettings.link.flags:Add(\"-isysroot /Developer/SDKs/MacOSX10.5.sdk\")\n\t\t\tend\n\t\telseif config.stackprotector.value == 1 then\n\t\t\tsettings.cc.flags:Add(\"-fstack-protector\", \"-fstack-protector-all\")\n\t\t\tsettings.link.flags:Add(\"-fstack-protector\", \"-fstack-protector-all\")\n\t\tend\n\tend\n\n\t-- set some platform specific settings\n\tsettings.cc.includes:Add(\"src\")\n\n\tif family == \"unix\" then\n\t\tif platform == \"macosx\" then\n\t\t\tsettings.link.frameworks:Add(\"Carbon\")\n\t\t\tsettings.link.frameworks:Add(\"AppKit\")\n\t\telse\n\t\t\tsettings.link.libs:Add(\"pthread\")\n\t\tend\n\t\t\n\t\tif platform == \"solaris\" then\n\t\t    settings.link.flags:Add(\"-lsocket\")\n\t\t    settings.link.flags:Add(\"-lnsl\")\n\t\tend\n\telseif family == \"windows\" then\n\t\tsettings.link.libs:Add(\"gdi32\")\n\t\tsettings.link.libs:Add(\"user32\")\n\t\tsettings.link.libs:Add(\"ws2_32\")\n\t\tsettings.link.libs:Add(\"ole32\")\n\t\tsettings.link.libs:Add(\"shell32\")\n\tend\n\n\t-- compile zlib if needed\n\tif config.zlib.value == 1 then\n\t\tsettings.link.libs:Add(\"z\")\n\t\tif config.zlib.include_path then\n\t\t\tsettings.cc.includes:Add(config.zlib.include_path)\n\t\tend\n\t\tzlib = {}\n\telse\n\t\tzlib = Compile(settings, Collect(\"src/engine/external/zlib/*.c\"))\n\t\tsettings.cc.includes:Add(\"src/engine/external/zlib\")\n\tend\n\n\t-- build the small libraries\n\twavpack = Compile(settings, Collect(\"src/engine/external/wavpack/*.c\"))\n\tpnglite = Compile(settings, Collect(\"src/engine/external/pnglite/*.c\"))\n\tjsonparser = Compile(settings, Collect(\"src/engine/external/json-parser/*.c\"))\n\n\t-- build game components\n\tengine_settings = settings:Copy()\n\tserver_settings = engine_settings:Copy()\n\tclient_settings = engine_settings:Copy()\n\tlauncher_settings = engine_settings:Copy()\n\n\tif family == \"unix\" then\n\t\tif platform == \"macosx\" then\n\t\t\tclient_settings.link.frameworks:Add(\"OpenGL\")\n\t\t\tclient_settings.link.frameworks:Add(\"AGL\")\n\t\t\tclient_settings.link.frameworks:Add(\"Carbon\")\n\t\t\tclient_settings.link.frameworks:Add(\"Cocoa\")\n\t\t\tlauncher_settings.link.frameworks:Add(\"Cocoa\")\n\t\telse\n\t\t\tclient_settings.link.libs:Add(\"X11\")\n\t\t\tclient_settings.link.libs:Add(\"GL\")\n\t\t\tclient_settings.link.libs:Add(\"GLU\")\n\t\tend\n\n\telseif family == \"windows\" then\n\t\tclient_settings.link.libs:Add(\"opengl32\")\n\t\tclient_settings.link.libs:Add(\"glu32\")\n\t\tclient_settings.link.libs:Add(\"winmm\")\n\tend\n\n\t-- apply sdl settings\n\tconfig.sdl:Apply(client_settings)\n\t-- apply freetype settings\n\tconfig.freetype:Apply(client_settings)\n\n\tengine = Compile(engine_settings, Collect(\"src/engine/shared/*.cpp\", \"src/base/*.c\"))\n\tclient = Compile(client_settings, Collect(\"src/engine/client/*.cpp\"))\n\tserver = Compile(server_settings, Collect(\"src/engine/server/*.cpp\"))\n\n\tversionserver = Compile(settings, Collect(\"src/versionsrv/*.cpp\"))\n\tmasterserver = Compile(settings, Collect(\"src/mastersrv/*.cpp\"))\n\tgame_shared = Compile(settings, Collect(\"src/game/*.cpp\"), nethash, network_source)\n\tgame_client = Compile(settings, CollectRecursive(\"src/game/client/*.cpp\"), client_content_source)\n\tgame_server = Compile(settings, CollectRecursive(\"src/game/server/*.cpp\"), server_content_source)\n\tgame_editor = Compile(settings, Collect(\"src/game/editor/*.cpp\"))\n\n\t-- build tools (TODO: fix this so we don't get double _d_d stuff)\n\ttools_src = Collect(\"src/tools/*.cpp\", \"src/tools/*.c\")\n\n\tclient_osxlaunch = {}\n\tserver_osxlaunch = {}\n\tif platform == \"macosx\" then\n\t\tclient_osxlaunch = Compile(client_settings, \"src/osxlaunch/client.m\")\n\t\tserver_osxlaunch = Compile(launcher_settings, \"src/osxlaunch/server.m\")\n\tend\n\n\ttools = {}\n\tfor i,v in ipairs(tools_src) do\n\t\ttoolname = PathFilename(PathBase(v))\n\t\ttools[i] = Link(settings, toolname, Compile(settings, v), engine, zlib, pnglite)\n\tend\n\n\t-- build client, server, version server and master server\n\tclient_exe = Link(client_settings, \"teeworlds\", game_shared, game_client,\n\t\tengine, client, game_editor, zlib, pnglite, wavpack, jsonparser,\n\t\tclient_link_other, client_osxlaunch)\n\n\tserver_exe = Link(server_settings, \"teeworlds_srv\", engine, server,\n\t\tgame_shared, game_server, zlib, server_link_other)\n\n\tserverlaunch = {}\n\tif platform == \"macosx\" then\n\t\tserverlaunch = Link(launcher_settings, \"serverlaunch\", server_osxlaunch)\n\tend\n\n\tversionserver_exe = Link(server_settings, \"versionsrv\", versionserver,\n\t\tengine, zlib)\n\n\tmasterserver_exe = Link(server_settings, \"mastersrv\", masterserver,\n\t\tengine, zlib)\n\n\t-- make targets\n\tc = PseudoTarget(\"client\"..\"_\"..settings.config_name, client_exe, client_depends)\n\ts = PseudoTarget(\"server\"..\"_\"..settings.config_name, server_exe, serverlaunch)\n\tg = PseudoTarget(\"game\"..\"_\"..settings.config_name, client_exe, server_exe)\n\n\tv = PseudoTarget(\"versionserver\"..\"_\"..settings.config_name, versionserver_exe)\n\tm = PseudoTarget(\"masterserver\"..\"_\"..settings.config_name, masterserver_exe)\n\tt = PseudoTarget(\"tools\"..\"_\"..settings.config_name, tools)\n\n\tall = PseudoTarget(settings.config_name, c, s, v, m, t)\n\treturn all\nend\n\n\ndebug_settings = NewSettings()\ndebug_settings.config_name = \"debug\"\ndebug_settings.config_ext = \"_d\"\ndebug_settings.debug = 1\ndebug_settings.optimize = 0\ndebug_settings.cc.defines:Add(\"CONF_DEBUG\")\n\nrelease_settings = NewSettings()\nrelease_settings.config_name = \"release\"\nrelease_settings.config_ext = \"\"\nrelease_settings.debug = 0\nrelease_settings.optimize = 1\nrelease_settings.cc.defines:Add(\"CONF_RELEASE\")\n\nif platform == \"macosx\" then\n\tdebug_settings_ppc = debug_settings:Copy()\n\tdebug_settings_ppc.config_name = \"debug_ppc\"\n\tdebug_settings_ppc.config_ext = \"_ppc_d\"\n\tdebug_settings_ppc.cc.flags:Add(\"-arch ppc\")\n\tdebug_settings_ppc.link.flags:Add(\"-arch ppc\")\n\tdebug_settings_ppc.cc.defines:Add(\"CONF_DEBUG\")\n\n\trelease_settings_ppc = release_settings:Copy()\n\trelease_settings_ppc.config_name = \"release_ppc\"\n\trelease_settings_ppc.config_ext = \"_ppc\"\n\trelease_settings_ppc.cc.flags:Add(\"-arch ppc\")\n\trelease_settings_ppc.link.flags:Add(\"-arch ppc\")\n\trelease_settings_ppc.cc.defines:Add(\"CONF_RELEASE\")\n\n\tppc_d = build(debug_settings_ppc)\n\tppc_r = build(release_settings_ppc)\n\n\tif arch == \"ia32\" or arch == \"amd64\" then\n\t\tdebug_settings_x86 = debug_settings:Copy()\n\t\tdebug_settings_x86.config_name = \"debug_x86\"\n\t\tdebug_settings_x86.config_ext = \"_x86_d\"\n\t\tdebug_settings_x86.cc.flags:Add(\"-arch i386\")\n\t\tdebug_settings_x86.link.flags:Add(\"-arch i386\")\n\t\tdebug_settings_x86.cc.defines:Add(\"CONF_DEBUG\")\n\n\t\trelease_settings_x86 = release_settings:Copy()\n\t\trelease_settings_x86.config_name = \"release_x86\"\n\t\trelease_settings_x86.config_ext = \"_x86\"\n\t\trelease_settings_x86.cc.flags:Add(\"-arch i386\")\n\t\trelease_settings_x86.link.flags:Add(\"-arch i386\")\n\t\trelease_settings_x86.cc.defines:Add(\"CONF_RELEASE\")\n\t\n\t\tx86_d = build(debug_settings_x86)\n\t\tx86_r = build(release_settings_x86)\n\tend\n\n\tif arch == \"amd64\" then\n\t\tdebug_settings_x86_64 = debug_settings:Copy()\n\t\tdebug_settings_x86_64.config_name = \"debug_x86_64\"\n\t\tdebug_settings_x86_64.config_ext = \"_x86_64_d\"\n\t\tdebug_settings_x86_64.cc.flags:Add(\"-arch x86_64\")\n\t\tdebug_settings_x86_64.link.flags:Add(\"-arch x86_64\")\n\t\tdebug_settings_x86_64.cc.defines:Add(\"CONF_DEBUG\")\n\n\t\trelease_settings_x86_64 = release_settings:Copy()\n\t\trelease_settings_x86_64.config_name = \"release_x86_64\"\n\t\trelease_settings_x86_64.config_ext = \"_x86_64\"\n\t\trelease_settings_x86_64.cc.flags:Add(\"-arch x86_64\")\n\t\trelease_settings_x86_64.link.flags:Add(\"-arch x86_64\")\n\t\trelease_settings_x86_64.cc.defines:Add(\"CONF_RELEASE\")\n\n\t\tx86_64_d = build(debug_settings_x86_64)\n\t\tx86_64_r = build(release_settings_x86_64)\n\tend\n\n\tDefaultTarget(\"game_debug_x86\")\n\t\n\tif config.macosxppc.value == 1 then\n\t\tif arch == \"ia32\" then\n\t\t\tPseudoTarget(\"release\", ppc_r, x86_r)\n\t\t\tPseudoTarget(\"debug\", ppc_d, x86_d)\n\t\t\tPseudoTarget(\"server_release\", \"server_release_ppc\", \"server_release_x86\")\n\t\t\tPseudoTarget(\"server_debug\", \"server_debug_ppc\", \"server_debug_x86\")\n\t\t\tPseudoTarget(\"client_release\", \"client_release_ppc\", \"client_release_x86\")\n\t\t\tPseudoTarget(\"client_debug\", \"client_debug_ppc\", \"client_debug_x86\")\n\t\telseif arch == \"amd64\" then\n\t\t\tPseudoTarget(\"release\", ppc_r, x86_r, x86_64_r)\n\t\t\tPseudoTarget(\"debug\", ppc_d, x86_d, x86_64_d)\n\t\t\tPseudoTarget(\"server_release\", \"server_release_ppc\", \"server_release_x86\", \"server_release_x86_64\")\n\t\t\tPseudoTarget(\"server_debug\", \"server_debug_ppc\", \"server_debug_x86\", \"server_debug_x86_64\")\n\t\t\tPseudoTarget(\"client_release\", \"client_release_ppc\", \"client_release_x86\", \"client_release_x86_64\")\n\t\t\tPseudoTarget(\"client_debug\", \"client_debug_ppc\", \"client_debug_x86\", \"client_debug_x86_64\")\n\t\telse\n\t\t\tPseudoTarget(\"release\", ppc_r)\n\t\t\tPseudoTarget(\"debug\", ppc_d)\n\t\t\tPseudoTarget(\"server_release\", \"server_release_ppc\")\n\t\t\tPseudoTarget(\"server_debug\", \"server_debug_ppc\")\n\t\t\tPseudoTarget(\"client_release\", \"client_release_ppc\")\n\t\t\tPseudoTarget(\"client_debug\", \"client_debug_ppc\")\n\t\tend\n\telse\n\t\tif arch == \"ia32\" then\n\t\t\tPseudoTarget(\"release\", x86_r)\n\t\t\tPseudoTarget(\"debug\", x86_d)\n\t\t\tPseudoTarget(\"server_release\", \"server_release_x86\")\n\t\t\tPseudoTarget(\"server_debug\", \"server_debug_x86\")\n\t\t\tPseudoTarget(\"client_release\", \"client_release_x86\")\n\t\t\tPseudoTarget(\"client_debug\", \"client_debug_x86\")\n\t\telseif arch == \"amd64\" then\n\t\t\tPseudoTarget(\"release\", x86_r, x86_64_r)\n\t\t\tPseudoTarget(\"debug\", x86_d, x86_64_d)\n\t\t\tPseudoTarget(\"server_release\", \"server_release_x86\", \"server_release_x86_64\")\n\t\t\tPseudoTarget(\"server_debug\", \"server_debug_x86\", \"server_debug_x86_64\")\n\t\t\tPseudoTarget(\"client_release\", \"client_release_x86\", \"client_release_x86_64\")\n\t\t\tPseudoTarget(\"client_debug\", \"client_debug_x86\", \"client_debug_x86_64\")\n\t\tend\n\tend\nelse\n\tbuild(debug_settings)\n\tbuild(release_settings)\n\tDefaultTarget(\"game_debug\")\nend\n"
  },
  {
    "path": "configure.lua",
    "content": "\n--[[@GROUP Configuration@END]]--\n\n--[[@FUNCTION\n\tTODO\n@END]]--\nfunction NewConfig(on_configured_callback)\n\tlocal config = {}\n\n\tconfig.OnConfigured = function(self)\n\t\treturn true\n\tend\n\n\tif on_configured_callback then config.OnConfigured = on_configured_callback end\n\n\tconfig.options = {}\n\tconfig.settings = NewSettings()\n\n\tconfig.NewSettings = function(self)\n\t\tlocal s = NewSettings()\n\t\tfor _,v in pairs(self.options) do\n\t\t\tv:Apply(s)\n\t\tend\n\t\treturn s\n\tend\n\n\tconfig.Add = function(self, o)\n\t\ttable.insert(self.options, o)\n\t\tself[o.name] = o\n\tend\n\n\tconfig.Print = function(self)\n\t\tfor k,v in pairs(self.options) do\n\t\t\tprint(v:FormatDisplay())\n\t\tend\n\tend\n\n\tconfig.Save = function(self, filename)\n\t\tprint(\"saved configuration to '\"..filename..\"'\")\n\t\tlocal file = io.open(filename, \"w\")\n\n\t\t-- Define a little helper function to save options\n\t\tlocal saver = {}\n\t\tsaver.file = file\n\n\t\tsaver.line = function(self, str)\n\t\t\tself.file:write(str .. \"\\n\")\n\t\tend\n\n\t\tsaver.option = function(self, option, name)\n\t\t\tlocal valuestr = \"no\"\n\t\t\tif type(option[name]) == type(0) then\n\t\t\t\tvaluestr = option[name]\n\t\t\telseif type(option[name]) == type(true) then\n\t\t\t\tvaluestr = \"false\"\n\t\t\t\tif option[name] then\n\t\t\t\t\tvaluestr = \"true\"\n\t\t\t\tend\n\t\t\telseif type(option[name]) == type(\"\") then\n\t\t\t\tvaluestr = \"'\"..option[name]..\"'\"\n\t\t\telse\n\t\t\t\terror(\"option \"..name..\" have a value of type \".. type(option[name])..\" that can't be saved\")\n\t\t\tend\n\t\t\tself.file:write(option.name..\".\"..name..\" = \".. valuestr..\"\\n\")\n\t\tend\n\n\t\t-- Save all the options\n\t\tfor k,v in pairs(self.options) do\n\t\t\tv:Save(saver)\n\t\tend\n\t\tfile:close()\n\tend\n\n\tconfig.Load = function(self, filename)\n\t\tlocal options_func = loadfile(filename)\n\t\tlocal options_table = {}\n\n\t\tif not options_func then\n\t\t\tprint(\"auto configuration\")\n\t\t\tself:Config(filename)\n\t\t\toptions_func = loadfile(filename)\n\t\tend\n\n\t\tif options_func then\n\t\t\t-- Setup the options tables\n\t\t\tfor k,v in pairs(self.options) do\n\t\t\t\toptions_table[v.name] = {}\n\t\t\tend\n\t\t\tsetfenv(options_func, options_table)\n\n\t\t\t-- this is to make sure that we get nice error messages when\n\t\t\t-- someone sets an option that isn't valid.\n\t\t\tlocal mt = {}\n\t\t\tmt.__index = function(t, key)\n\t\t\t\tlocal v = rawget(t, key)\n\t\t\t\tif v ~= nil then return v end\n\t\t\t\terror(\"there is no configuration option named '\" .. key .. \"'\")\n\t\t\tend\n\n\t\t\tsetmetatable(options_table, mt)\n\n\t\t\t-- Process the options\n\t\t\toptions_func()\n\n\t\t\t-- Copy the options\n\t\t\tfor k,v in pairs(self.options) do\n\t\t\t\tif options_table[v.name] then\n\t\t\t\t\tfor k2,v2 in pairs(options_table[v.name]) do\n\t\t\t\t\t\tv[k2] = v2\n\t\t\t\t\tend\n\t\t\t\t\tv.auto_detected = false\n\t\t\t\tend\n\t\t\tend\n\t\telse\n\t\t\tprint(\"error: no '\"..filename..\"' found\")\n\t\t\tprint(\"\")\n\t\t\tprint(\"run 'bam config' to generate\")\n\t\t\tprint(\"run 'bam config help' for configuration options\")\n\t\t\tprint(\"\")\n\t\t\tos.exit(1)\n\t\tend\n\tend\n\n\tconfig.Config = function(self, filename)\n\t\tprint(\"\")\n\t\tprint(\"configuration:\")\n\t\tif _bam_targets[1] == \"print\" then\n\t\t\tself:Load(filename)\n\t\t\tself:Print()\n\t\t\tprint(\"\")\n\t\t\tprint(\"notes:\")\n\t\t\tself:OnConfigured()\n\t\t\tprint(\"\")\n\t\telse\n\t\t\tself:Autodetect()\n\t\t\tprint(\"\")\n\t\t\tprint(\"notes:\")\n\t\t\tif self:OnConfigured() then\n\t\t\t\tself:Save(filename)\n\t\t\tend\n\t\t\tprint(\"\")\n\t\tend\n\n\tend\n\n\tconfig.Autodetect = function(self)\n\t\tfor k,v in pairs(self.options) do\n\t\t\tv:Check(self.settings)\n\t\t\tprint(v:FormatDisplay())\n\t\t\tself[v.name] = v\n\t\tend\n\tend\n\n\tconfig.PrintHelp = function(self)\n\t\tprint(\"options:\")\n\t\tfor k,v in pairs(self.options) do\n\t\t\tif v.PrintHelp then\n\t\t\t\tv:PrintHelp()\n\t\t\tend\n\t\tend\n\tend\n\n\tconfig.Finalize = function(self, filename)\n\t\tif _bam_targets[0] == \"config\" then\n\t\t\tif _bam_targets[1] == \"help\" then\n\t\t\t\tself:PrintHelp()\n\t\t\t\tos.exit(0)\n\t\t\tend\n\n\t\t\tself:Config(filename)\n\n\t\t\tos.exit(0)\n\t\tend\n\n\t\tself:Load(filename)\n\t\tbam_update_globalstamp(filename)\n\tend\n\n\treturn config\nend\n\n\n-- Helper functions --------------------------------------\nfunction DefaultOptionDisplay(option)\n\tif not option.value then return \"no\" end\n\tif option.value == 1 or option.value == true then return \"yes\" end\n\treturn option.value\nend\n\nfunction IsNegativeTerm(s)\n\tif s == \"no\" then return true end\n\tif s == \"false\" then return true end\n\tif s == \"off\" then return true end\n\tif s == \"disable\" then return true end\n\tif s == \"0\" then return true end\n\treturn false\nend\n\nfunction IsPositiveTerm(s)\n\tif s == \"yes\" then return true end\n\tif s == \"true\" then return true end\n\tif s == \"on\" then return true end\n\tif s == \"enable\" then return true end\n\tif s == \"1\" then return true end\n\treturn false\nend\n\nfunction MakeOption(name, value, check, save, display, printhelp)\n\tlocal o = {}\n\to.name = name\n\to.value = value\n\to.Check = check\n\to.Save = save\n\to.auto_detected = true\n\to.FormatDisplay = function(self)\n\t\tlocal a = \"SET\"\n\t\tif self.auto_detected then a = \"AUTO\" end\n\t\treturn string.format(\"%-5s %-20s %s\", a, self.name, self:Display())\n\tend\n\n\to.Display = display\n\to.PrintHelp = printhelp\n\tif o.Display == nil then o.Display = DefaultOptionDisplay end\n\treturn o\nend\n\n\n-- Test Compile C --------------------------------------\nfunction OptTestCompileC(name, source, compileoptions, desc)\n\tlocal check = function(option, settings)\n\t\toption.value = false\n\t\tif ScriptArgs[option.name] then\n\t\t\tif IsNegativeTerm(ScriptArgs[option.name]) then\n\t\t\t\toption.value = false\n\t\t\telseif IsPositiveTerm(ScriptArgs[option.name]) then\n\t\t\t\toption.value = true\n\t\t\telse\n\t\t\t\terror(ScriptArgs[option.name]..\" is not a valid value for option \"..option.name)\n\t\t\tend\n\t\t\toption.auto_detected = false\n\t\telse\n\t\t\tif CTestCompile(settings, option.source, option.compileoptions) then\n\t\t\t\toption.value = true\n\t\t\tend\n\t\tend\n\tend\n\n\tlocal save = function(option, output)\n\t\toutput:option(option, \"value\")\n\tend\n\n\tlocal printhelp = function(option)\n\t\tprint(\"\\t\"..option.name..\"=on|off\")\n\t\tif option.desc then print(\"\\t\\t\"..option.desc) end\n\tend\n\n\tlocal o = MakeOption(name, false, check, save, nil, printhelp)\n\to.desc = desc\n\to.source = source\n\to.compileoptions = compileoptions\n\treturn o\nend\n\n\n-- OptToggle --------------------------------------\nfunction OptToggle(name, default_value, desc)\n\tlocal check = function(option, settings)\n\t\tif ScriptArgs[option.name] then\n\t\t\tif IsNegativeTerm(ScriptArgs[option.name]) then\n\t\t\t\toption.value = false\n\t\t\telseif IsPositiveTerm(ScriptArgs[option.name]) then\n\t\t\t\toption.value = true\n\t\t\telse\n\t\t\t\terror(ScriptArgs[option.name]..\" is not a valid value for option \"..option.name)\n\t\t\tend\n\t\tend\n\tend\n\n\tlocal save = function(option, output)\n\t\toutput:option(option, \"value\")\n\tend\n\n\tlocal printhelp = function(option)\n\t\tprint(\"\\t\"..option.name..\"=on|off\")\n\t\tif option.desc then print(\"\\t\\t\"..option.desc) end\n\tend\n\n\tlocal o = MakeOption(name, default_value, check, save, nil, printhelp)\n\to.desc = desc\n\treturn o\nend\n\n-- OptInteger --------------------------------------\nfunction OptInteger(name, default_value, desc)\n\tlocal check = function(option, settings)\n\t\tif ScriptArgs[option.name] then\n\t\t\toption.value = tonumber(ScriptArgs[option.name])\n\t\tend\n\tend\n\n\tlocal save = function(option, output)\n\t\toutput:option(option, \"value\")\n\tend\n\n\tlocal printhelp = function(option)\n\t\tprint(\"\\t\"..option.name..\"=N\")\n\t\tif option.desc then print(\"\\t\\t\"..option.desc) end\n\tend\n\n\tlocal o = MakeOption(name, default_value, check, save, nil, printhelp)\n\to.desc = desc\n\treturn o\nend\n\n\n-- OptString --------------------------------------\nfunction OptString(name, default_value, desc)\n\tlocal check = function(option, settings)\n\t\tif ScriptArgs[option.name] then\n\t\t\toption.value = ScriptArgs[option.name]\n\t\tend\n\tend\n\n\tlocal save = function(option, output)\n\t\toutput:option(option, \"value\")\n\tend\n\n\tlocal printhelp = function(option)\n\t\tprint(\"\\t\"..option.name..\"=STRING\")\n\t\tif option.desc then print(\"\\t\\t\"..option.desc) end\n\tend\n\n\tlocal o = MakeOption(name, default_value, check, save, nil, printhelp)\n\to.desc = desc\n\treturn o\nend\n\n-- Find Compiler --------------------------------------\n--[[@FUNCTION\n\tTODO\n@END]]--\nfunction OptCCompiler(name, default_driver, default_c, default_cxx, desc)\n\tlocal check = function(option, settings)\n\t\tif ScriptArgs[option.name] then\n\t\t\t-- set compile driver\n\t\t\toption.driver = ScriptArgs[option.name]\n\n\t\t\t-- set c compiler\n\t\t\tif ScriptArgs[option.name..\".c\"] then\n\t\t\t\toption.c_compiler = ScriptArgs[option.name..\".c\"]\n\t\t\tend\n\n\t\t\t-- set c+= compiler\n\t\t\tif ScriptArgs[option.name..\".cxx\"] then\n\t\t\t\toption.cxx_compiler = ScriptArgs[option.name..\".cxx\"]\n\t\t\tend\n\n\t\t\toption.auto_detected = false\n\t\telseif option.driver then\n\t\t\t-- no need todo anything if we have a driver\n\t\t\t-- TODO: test if we can find the compiler\n\t\telse\n\t\t\tif ExecuteSilent(\"cl\") == 0 then\n\t\t\t\toption.driver = \"cl\"\n\t\t\telseif ExecuteSilent(\"g++ -v\") == 0 then\n\t\t\t\toption.driver = \"gcc\"\n\t\t\telse\n\t\t\t\terror(\"no c/c++ compiler found\")\n\t\t\tend\n\t\tend\n\t\t--setup_compiler(option.value)\n\tend\n\n\tlocal apply = function(option, settings)\n\t\tif option.driver == \"cl\" then\n\t\t\tSetDriversCL(settings)\n\t\telseif option.driver == \"gcc\" then\n\t\t\tSetDriversGCC(settings)\n\t\telseif option.driver == \"clang\" then\n\t\t\tSetDriversClang(settings)\n\t\telse\n\t\t\terror(option.driver..\" is not a known c/c++ compile driver\")\n\t\tend\n\n\t\tif option.c_compiler then settings.cc.c_compiler = option.c_compiler end\n\t\tif option.cxx_compiler then settings.cc.cxx_compiler = option.cxx_compiler end\n\tend\n\n\tlocal save = function(option, output)\n\t\toutput:option(option, \"driver\")\n\t\toutput:option(option, \"c_compiler\")\n\t\toutput:option(option, \"cxx_compiler\")\n\tend\n\n\tlocal printhelp = function(option)\n\t\tlocal a = \"\"\n\t\tif option.desc then a = \"for \"..option.desc end\n\t\tprint(\"\\t\"..option.name..\"=gcc|cl|clang\")\n\t\tprint(\"\\t\\twhat c/c++ compile driver to use\"..a)\n\t\tprint(\"\\t\"..option.name..\".c=FILENAME\")\n\t\tprint(\"\\t\\twhat c compiler executable to use\"..a)\n\t\tprint(\"\\t\"..option.name..\".cxx=FILENAME\")\n\t\tprint(\"\\t\\twhat c++ compiler executable to use\"..a)\n\tend\n\n\tlocal display = function(option)\n\t\tlocal s = option.driver\n\t\tif option.c_compiler then s = s .. \" c=\"..option.c_compiler end\n\t\tif option.cxx_compiler then s = s .. \" cxx=\"..option.cxx_compiler end\n\t\treturn s\n\tend\n\n\tlocal o = MakeOption(name, nil, check, save, display, printhelp)\n\to.desc = desc\n\to.driver = false\n\to.c_compiler = false\n\to.cxx_compiler = false\n\n\tif default_driver then o.driver = default_driver end\n\tif default_c then o.c_compiler = default_c end\n\tif default_cxx then o.cxx_compiler = default_cxx end\n\n\to.Apply = apply\n\treturn o\nend\n\n-- Option Library --------------------------------------\n--[[@FUNCTION\n\tTODO\n@END]]--\nfunction OptLibrary(name, header, desc)\n\tlocal check = function(option, settings)\n\t\toption.value = false\n\t\toption.include_path = false\n\n\t\tlocal function check_compile_include(filename, paths)\n\t\t\tif CTestCompile(settings, \"#include <\" .. filename .. \">\\nint main(){return 0;}\", \"\") then\n\t\t\t\treturn \"\"\n\t\t\tend\n\n\t\t\tfor k,v in pairs(paths) do\n\t\t\t\tif CTestCompile(settings, \"#include <\" .. filename .. \">\\nint main(){return 0;}\", \"-I\"..v) then\n\t\t\t\t\treturn v\n\t\t\t\tend\n\t\t\tend\n\n\t\t\treturn false\n\t\tend\n\n\t\tif ScriptArgs[option.name] then\n\t\t\tif IsNegativeTerm(ScriptArgs[option.name]) then\n\t\t\t\toption.value = false\n\t\t\telseif ScriptArgs[option.name] == \"system\" then\n\t\t\t\toption.value = true\n\t\t\telse\n\t\t\t\toption.value = true\n\t\t\t\toption.include_path = ScriptArgs[option.name]\n\t\t\tend\n\t\t\toption.auto_detected = false\n\t\telse\n\t\t\toption.include_path = check_compile_include(option.header, {})\n\t\t\tif option.include_path == false then\n\t\t\t\tif option.required then\n\t\t\t\t\tprint(name..\" library not found and is required\")\n\t\t\t\t\terror(\"required library not found\")\n\t\t\t\tend\n\t\t\telse\n\t\t\t\toption.value = true\n\t\t\t\toption.include_path = false\n\t\t\tend\n\t\tend\n\tend\n\n\tlocal save = function(option, output)\n\t\toutput:option(option, \"value\")\n\t\toutput:option(option, \"include_path\")\n\tend\n\n\tlocal display = function(option)\n\t\tif option.value then\n\t\t\tif option.include_path then\n\t\t\t\treturn option.include_path\n\t\t\telse\n\t\t\t\treturn \"(in system path)\"\n\t\t\tend\n\t\telse\n\t\t\treturn \"not found\"\n\t\tend\n\tend\n\n\tlocal printhelp = function(option)\n\t\tprint(\"\\t\"..option.name..\"=disable|system|PATH\")\n\t\tif option.desc then print(\"\\t\\t\"..option.desc) end\n\tend\n\n\tlocal o = MakeOption(name, false, check, save, display, printhelp)\n\to.include_path = false\n\to.header = header\n\to.desc = desc\n\treturn o\nend\n\n"
  },
  {
    "path": "data/countryflags/index.json",
    "content": "{\"country codes\": \n\t{\"custom\": [\n\t\t{\n\t\t\t\"id\": \"SS\",\n\t\t\t\"code\": 737\n\t\t},\n\t\t{\n\t\t\t\"id\": \"XEN\",\n\t\t\t\"code\": 901\n\t\t},\n\t\t{\n\t\t\t\"id\": \"XNI\",\n\t\t\t\"code\": 902\n\t\t},\n\t\t{\n\t\t\t\"id\": \"XSC\",\n\t\t\t\"code\": 903\n\t\t},\n\t\t{\n\t\t\t\"id\": \"XWA\",\n\t\t\t\"code\": 904\n\t\t},\n\t\t{\n\t\t\t\"id\": \"default\",\n\t\t\t\"code\": -1\n\t\t}\n\t],\n\t\"ISO 3166-1\": [\n\t\t{\n\t\t\t\"id\": \"AD\",\n\t\t\t\"code\": 20\n\t\t},\n\t\t{\n\t\t\t\"id\": \"AE\",\n\t\t\t\"code\": 784\n\t\t},\n\t\t{\n\t\t\t\"id\": \"AF\",\n\t\t\t\"code\": 4\n\t\t},\n\t\t{\n\t\t\t\"id\": \"AG\",\n\t\t\t\"code\": 28\n\t\t},\n\t\t{\n\t\t\t\"id\": \"AI\",\n\t\t\t\"code\": 660\n\t\t},\n\t\t{\n\t\t\t\"id\": \"AL\",\n\t\t\t\"code\": 8\n\t\t},\n\t\t{\n\t\t\t\"id\": \"AM\",\n\t\t\t\"code\": 51\n\t\t},\n\t\t{\n\t\t\t\"id\": \"AO\",\n\t\t\t\"code\": 24\n\t\t},\n\t\t{\n\t\t\t\"id\": \"AR\",\n\t\t\t\"code\": 32\n\t\t},\n\t\t{\n\t\t\t\"id\": \"AS\",\n\t\t\t\"code\": 16\n\t\t},\n\t\t{\n\t\t\t\"id\": \"AT\",\n\t\t\t\"code\": 40\n\t\t},\n\t\t{\n\t\t\t\"id\": \"AU\",\n\t\t\t\"code\": 36\n\t\t},\n\t\t{\n\t\t\t\"id\": \"AW\",\n\t\t\t\"code\": 533\n\t\t},\n\t\t{\n\t\t\t\"id\": \"AX\",\n\t\t\t\"code\": 248\n\t\t},\n\t\t{\n\t\t\t\"id\": \"AZ\",\n\t\t\t\"code\": 31\n\t\t},\n\t\t{\n\t\t\t\"id\": \"BA\",\n\t\t\t\"code\": 70\n\t\t},\n\t\t{\n\t\t\t\"id\": \"BB\",\n\t\t\t\"code\": 52\n\t\t},\n\t\t{\n\t\t\t\"id\": \"BD\",\n\t\t\t\"code\": 50\n\t\t},\n\t\t{\n\t\t\t\"id\": \"BE\",\n\t\t\t\"code\": 56\n\t\t},\n\t\t{\n\t\t\t\"id\": \"BF\",\n\t\t\t\"code\": 854\n\t\t},\n\t\t{\n\t\t\t\"id\": \"BG\",\n\t\t\t\"code\": 100\n\t\t},\n\t\t{\n\t\t\t\"id\": \"BH\",\n\t\t\t\"code\": 48\n\t\t},\n\t\t{\n\t\t\t\"id\": \"BI\",\n\t\t\t\"code\": 108\n\t\t},\n\t\t{\n\t\t\t\"id\": \"BJ\",\n\t\t\t\"code\": 204\n\t\t},\n\t\t{\n\t\t\t\"id\": \"BL\",\n\t\t\t\"code\": 652\n\t\t},\n\t\t{\n\t\t\t\"id\": \"BM\",\n\t\t\t\"code\": 60\n\t\t},\n\t\t{\n\t\t\t\"id\": \"BN\",\n\t\t\t\"code\": 96\n\t\t},\n\t\t{\n\t\t\t\"id\": \"BO\",\n\t\t\t\"code\": 68\n\t\t},\n\t\t{\n\t\t\t\"id\": \"BR\",\n\t\t\t\"code\": 76\n\t\t},\n\t\t{\n\t\t\t\"id\": \"BS\",\n\t\t\t\"code\": 44\n\t\t},\n\t\t{\n\t\t\t\"id\": \"BT\",\n\t\t\t\"code\": 64\n\t\t},\n\t\t{\n\t\t\t\"id\": \"BW\",\n\t\t\t\"code\": 72\n\t\t},\n\t\t{\n\t\t\t\"id\": \"BY\",\n\t\t\t\"code\": 112\n\t\t},\n\t\t{\n\t\t\t\"id\": \"BZ\",\n\t\t\t\"code\": 84\n\t\t},\n\t\t{\n\t\t\t\"id\": \"CA\",\n\t\t\t\"code\": 124\n\t\t},\n\t\t{\n\t\t\t\"id\": \"CC\",\n\t\t\t\"code\": 166\n\t\t},\n\t\t{\n\t\t\t\"id\": \"CD\",\n\t\t\t\"code\": 180\n\t\t},\n\t\t{\n\t\t\t\"id\": \"CF\",\n\t\t\t\"code\": 140\n\t\t},\n\t\t{\n\t\t\t\"id\": \"CG\",\n\t\t\t\"code\": 178\n\t\t},\n\t\t{\n\t\t\t\"id\": \"CH\",\n\t\t\t\"code\": 756\n\t\t},\n\t\t{\n\t\t\t\"id\": \"CI\",\n\t\t\t\"code\": 384\n\t\t},\n\t\t{\n\t\t\t\"id\": \"CK\",\n\t\t\t\"code\": 184\n\t\t},\n\t\t{\n\t\t\t\"id\": \"CL\",\n\t\t\t\"code\": 152\n\t\t},\n\t\t{\n\t\t\t\"id\": \"CM\",\n\t\t\t\"code\": 120\n\t\t},\n\t\t{\n\t\t\t\"id\": \"CN\",\n\t\t\t\"code\": 156\n\t\t},\n\t\t{\n\t\t\t\"id\": \"CO\",\n\t\t\t\"code\": 170\n\t\t},\n\t\t{\n\t\t\t\"id\": \"CR\",\n\t\t\t\"code\": 188\n\t\t},\n\t\t{\n\t\t\t\"id\": \"CU\",\n\t\t\t\"code\": 192\n\t\t},\n\t\t{\n\t\t\t\"id\": \"CV\",\n\t\t\t\"code\": 132\n\t\t},\n\t\t{\n\t\t\t\"id\": \"CW\",\n\t\t\t\"code\": 531\n\t\t},\n\t\t{\n\t\t\t\"id\": \"CX\",\n\t\t\t\"code\": 162\n\t\t},\n\t\t{\n\t\t\t\"id\": \"CY\",\n\t\t\t\"code\": 196\n\t\t},\n\t\t{\n\t\t\t\"id\": \"CZ\",\n\t\t\t\"code\": 203\n\t\t},\n\t\t{\n\t\t\t\"id\": \"DE\",\n\t\t\t\"code\": 276\n\t\t},\n\t\t{\n\t\t\t\"id\": \"DJ\",\n\t\t\t\"code\": 262\n\t\t},\n\t\t{\n\t\t\t\"id\": \"DK\",\n\t\t\t\"code\": 208\n\t\t},\n\t\t{\n\t\t\t\"id\": \"DM\",\n\t\t\t\"code\": 212\n\t\t},\n\t\t{\n\t\t\t\"id\": \"DO\",\n\t\t\t\"code\": 214\n\t\t},\n\t\t{\n\t\t\t\"id\": \"DZ\",\n\t\t\t\"code\": 12\n\t\t},\n\t\t{\n\t\t\t\"id\": \"EC\",\n\t\t\t\"code\": 218\n\t\t},\n\t\t{\n\t\t\t\"id\": \"EE\",\n\t\t\t\"code\": 233\n\t\t},\n\t\t{\n\t\t\t\"id\": \"EG\",\n\t\t\t\"code\": 818\n\t\t},\n\t\t{\n\t\t\t\"id\": \"EH\",\n\t\t\t\"code\": 732\n\t\t},\n\t\t{\n\t\t\t\"id\": \"ER\",\n\t\t\t\"code\": 232\n\t\t},\n\t\t{\n\t\t\t\"id\": \"ES\",\n\t\t\t\"code\": 724\n\t\t},\n\t\t{\n\t\t\t\"id\": \"ET\",\n\t\t\t\"code\": 231\n\t\t},\n\t\t{\n\t\t\t\"id\": \"FI\",\n\t\t\t\"code\": 246\n\t\t},\n\t\t{\n\t\t\t\"id\": \"FJ\",\n\t\t\t\"code\": 242\n\t\t},\n\t\t{\n\t\t\t\"id\": \"FK\",\n\t\t\t\"code\": 238\n\t\t},\n\t\t{\n\t\t\t\"id\": \"FM\",\n\t\t\t\"code\": 583\n\t\t},\n\t\t{\n\t\t\t\"id\": \"FO\",\n\t\t\t\"code\": 234\n\t\t},\n\t\t{\n\t\t\t\"id\": \"FR\",\n\t\t\t\"code\": 250\n\t\t},\n\t\t{\n\t\t\t\"id\": \"GA\",\n\t\t\t\"code\": 266\n\t\t},\n\t\t{\n\t\t\t\"id\": \"GB\",\n\t\t\t\"code\": 826\n\t\t},\n\t\t{\n\t\t\t\"id\": \"GD\",\n\t\t\t\"code\": 308\n\t\t},\n\t\t{\n\t\t\t\"id\": \"GE\",\n\t\t\t\"code\": 268\n\t\t},\n\t\t{\n\t\t\t\"id\": \"GF\",\n\t\t\t\"code\": 254\n\t\t},\n\t\t{\n\t\t\t\"id\": \"GG\",\n\t\t\t\"code\": 831\n\t\t},\n\t\t{\n\t\t\t\"id\": \"GH\",\n\t\t\t\"code\": 288\n\t\t},\n\t\t{\n\t\t\t\"id\": \"GI\",\n\t\t\t\"code\": 292\n\t\t},\n\t\t{\n\t\t\t\"id\": \"GL\",\n\t\t\t\"code\": 304\n\t\t},\n\t\t{\n\t\t\t\"id\": \"GM\",\n\t\t\t\"code\": 270\n\t\t},\n\t\t{\n\t\t\t\"id\": \"GN\",\n\t\t\t\"code\": 324\n\t\t},\n\t\t{\n\t\t\t\"id\": \"GP\",\n\t\t\t\"code\": 312\n\t\t},\n\t\t{\n\t\t\t\"id\": \"GQ\",\n\t\t\t\"code\": 226\n\t\t},\n\t\t{\n\t\t\t\"id\": \"GR\",\n\t\t\t\"code\": 300\n\t\t},\n\t\t{\n\t\t\t\"id\": \"GS\",\n\t\t\t\"code\": 239\n\t\t},\n\t\t{\n\t\t\t\"id\": \"GT\",\n\t\t\t\"code\": 320\n\t\t},\n\t\t{\n\t\t\t\"id\": \"GU\",\n\t\t\t\"code\": 316\n\t\t},\n\t\t{\n\t\t\t\"id\": \"GW\",\n\t\t\t\"code\": 624\n\t\t},\n\t\t{\n\t\t\t\"id\": \"GY\",\n\t\t\t\"code\": 328\n\t\t},\n\t\t{\n\t\t\t\"id\": \"HK\",\n\t\t\t\"code\": 344\n\t\t},\n\t\t{\n\t\t\t\"id\": \"HN\",\n\t\t\t\"code\": 340\n\t\t},\n\t\t{\n\t\t\t\"id\": \"HR\",\n\t\t\t\"code\": 191\n\t\t},\n\t\t{\n\t\t\t\"id\": \"HT\",\n\t\t\t\"code\": 332\n\t\t},\n\t\t{\n\t\t\t\"id\": \"HU\",\n\t\t\t\"code\": 348\n\t\t},\n\t\t{\n\t\t\t\"id\": \"ID\",\n\t\t\t\"code\": 360\n\t\t},\n\t\t{\n\t\t\t\"id\": \"IE\",\n\t\t\t\"code\": 372\n\t\t},\n\t\t{\n\t\t\t\"id\": \"IL\",\n\t\t\t\"code\": 376\n\t\t},\n\t\t{\n\t\t\t\"id\": \"IM\",\n\t\t\t\"code\": 833\n\t\t},\n\t\t{\n\t\t\t\"id\": \"IN\",\n\t\t\t\"code\": 356\n\t\t},\n\t\t{\n\t\t\t\"id\": \"IO\",\n\t\t\t\"code\": 86\n\t\t},\n\t\t{\n\t\t\t\"id\": \"IQ\",\n\t\t\t\"code\": 368\n\t\t},\n\t\t{\n\t\t\t\"id\": \"IR\",\n\t\t\t\"code\": 364\n\t\t},\n\t\t{\n\t\t\t\"id\": \"IS\",\n\t\t\t\"code\": 352\n\t\t},\n\t\t{\n\t\t\t\"id\": \"IT\",\n\t\t\t\"code\": 380\n\t\t},\n\t\t{\n\t\t\t\"id\": \"JE\",\n\t\t\t\"code\": 832\n\t\t},\n\t\t{\n\t\t\t\"id\": \"JM\",\n\t\t\t\"code\": 388\n\t\t},\n\t\t{\n\t\t\t\"id\": \"JO\",\n\t\t\t\"code\": 400\n\t\t},\n\t\t{\n\t\t\t\"id\": \"JP\",\n\t\t\t\"code\": 392\n\t\t},\n\t\t{\n\t\t\t\"id\": \"KE\",\n\t\t\t\"code\": 404\n\t\t},\n\t\t{\n\t\t\t\"id\": \"KG\",\n\t\t\t\"code\": 417\n\t\t},\n\t\t{\n\t\t\t\"id\": \"KH\",\n\t\t\t\"code\": 116\n\t\t},\n\t\t{\n\t\t\t\"id\": \"KI\",\n\t\t\t\"code\": 296\n\t\t},\n\t\t{\n\t\t\t\"id\": \"KM\",\n\t\t\t\"code\": 174\n\t\t},\n\t\t{\n\t\t\t\"id\": \"KN\",\n\t\t\t\"code\": 659\n\t\t},\n\t\t{\n\t\t\t\"id\": \"KP\",\n\t\t\t\"code\": 408\n\t\t},\n\t\t{\n\t\t\t\"id\": \"KR\",\n\t\t\t\"code\": 410\n\t\t},\n\t\t{\n\t\t\t\"id\": \"KW\",\n\t\t\t\"code\": 414\n\t\t},\n\t\t{\n\t\t\t\"id\": \"KY\",\n\t\t\t\"code\": 136\n\t\t},\n\t\t{\n\t\t\t\"id\": \"KZ\",\n\t\t\t\"code\": 398\n\t\t},\n\t\t{\n\t\t\t\"id\": \"LA\",\n\t\t\t\"code\": 418\n\t\t},\n\t\t{\n\t\t\t\"id\": \"LB\",\n\t\t\t\"code\": 422\n\t\t},\n\t\t{\n\t\t\t\"id\": \"LC\",\n\t\t\t\"code\": 662\n\t\t},\n\t\t{\n\t\t\t\"id\": \"LI\",\n\t\t\t\"code\": 438\n\t\t},\n\t\t{\n\t\t\t\"id\": \"LK\",\n\t\t\t\"code\": 144\n\t\t},\n\t\t{\n\t\t\t\"id\": \"LR\",\n\t\t\t\"code\": 430\n\t\t},\n\t\t{\n\t\t\t\"id\": \"LS\",\n\t\t\t\"code\": 426\n\t\t},\n\t\t{\n\t\t\t\"id\": \"LT\",\n\t\t\t\"code\": 440\n\t\t},\n\t\t{\n\t\t\t\"id\": \"LU\",\n\t\t\t\"code\": 442\n\t\t},\n\t\t{\n\t\t\t\"id\": \"LV\",\n\t\t\t\"code\": 428\n\t\t},\n\t\t{\n\t\t\t\"id\": \"LY\",\n\t\t\t\"code\": 434\n\t\t},\n\t\t{\n\t\t\t\"id\": \"MA\",\n\t\t\t\"code\": 504\n\t\t},\n\t\t{\n\t\t\t\"id\": \"MC\",\n\t\t\t\"code\": 492\n\t\t},\n\t\t{\n\t\t\t\"id\": \"MD\",\n\t\t\t\"code\": 498\n\t\t},\n\t\t{\n\t\t\t\"id\": \"ME\",\n\t\t\t\"code\": 499\n\t\t},\n\t\t{\n\t\t\t\"id\": \"MF\",\n\t\t\t\"code\": 663\n\t\t},\n\t\t{\n\t\t\t\"id\": \"MG\",\n\t\t\t\"code\": 450\n\t\t},\n\t\t{\n\t\t\t\"id\": \"MH\",\n\t\t\t\"code\": 584\n\t\t},\n\t\t{\n\t\t\t\"id\": \"MK\",\n\t\t\t\"code\": 807\n\t\t},\n\t\t{\n\t\t\t\"id\": \"ML\",\n\t\t\t\"code\": 466\n\t\t},\n\t\t{\n\t\t\t\"id\": \"MM\",\n\t\t\t\"code\": 104\n\t\t},\n\t\t{\n\t\t\t\"id\": \"MN\",\n\t\t\t\"code\": 496\n\t\t},\n\t\t{\n\t\t\t\"id\": \"MO\",\n\t\t\t\"code\": 446\n\t\t},\n\t\t{\n\t\t\t\"id\": \"MP\",\n\t\t\t\"code\": 580\n\t\t},\n\t\t{\n\t\t\t\"id\": \"MQ\",\n\t\t\t\"code\": 474\n\t\t},\n\t\t{\n\t\t\t\"id\": \"MR\",\n\t\t\t\"code\": 478\n\t\t},\n\t\t{\n\t\t\t\"id\": \"MS\",\n\t\t\t\"code\": 500\n\t\t},\n\t\t{\n\t\t\t\"id\": \"MT\",\n\t\t\t\"code\": 470\n\t\t},\n\t\t{\n\t\t\t\"id\": \"MU\",\n\t\t\t\"code\": 480\n\t\t},\n\t\t{\n\t\t\t\"id\": \"MV\",\n\t\t\t\"code\": 462\n\t\t},\n\t\t{\n\t\t\t\"id\": \"MW\",\n\t\t\t\"code\": 454\n\t\t},\n\t\t{\n\t\t\t\"id\": \"MX\",\n\t\t\t\"code\": 484\n\t\t},\n\t\t{\n\t\t\t\"id\": \"MY\",\n\t\t\t\"code\": 458\n\t\t},\n\t\t{\n\t\t\t\"id\": \"MZ\",\n\t\t\t\"code\": 508\n\t\t},\n\t\t{\n\t\t\t\"id\": \"NA\",\n\t\t\t\"code\": 516\n\t\t},\n\t\t{\n\t\t\t\"id\": \"NC\",\n\t\t\t\"code\": 540\n\t\t},\n\t\t{\n\t\t\t\"id\": \"NE\",\n\t\t\t\"code\": 562\n\t\t},\n\t\t{\n\t\t\t\"id\": \"NF\",\n\t\t\t\"code\": 574\n\t\t},\n\t\t{\n\t\t\t\"id\": \"NG\",\n\t\t\t\"code\": 566\n\t\t},\n\t\t{\n\t\t\t\"id\": \"NI\",\n\t\t\t\"code\": 558\n\t\t},\n\t\t{\n\t\t\t\"id\": \"NL\",\n\t\t\t\"code\": 528\n\t\t},\n\t\t{\n\t\t\t\"id\": \"NO\",\n\t\t\t\"code\": 578\n\t\t},\n\t\t{\n\t\t\t\"id\": \"NP\",\n\t\t\t\"code\": 524\n\t\t},\n\t\t{\n\t\t\t\"id\": \"NR\",\n\t\t\t\"code\": 520\n\t\t},\n\t\t{\n\t\t\t\"id\": \"NU\",\n\t\t\t\"code\": 570\n\t\t},\n\t\t{\n\t\t\t\"id\": \"NZ\",\n\t\t\t\"code\": 554\n\t\t},\n\t\t{\n\t\t\t\"id\": \"OM\",\n\t\t\t\"code\": 512\n\t\t},\n\t\t{\n\t\t\t\"id\": \"PA\",\n\t\t\t\"code\": 591\n\t\t},\n\t\t{\n\t\t\t\"id\": \"PE\",\n\t\t\t\"code\": 604\n\t\t},\n\t\t{\n\t\t\t\"id\": \"PF\",\n\t\t\t\"code\": 258\n\t\t},\n\t\t{\n\t\t\t\"id\": \"PG\",\n\t\t\t\"code\": 598\n\t\t},\n\t\t{\n\t\t\t\"id\": \"PH\",\n\t\t\t\"code\": 608\n\t\t},\n\t\t{\n\t\t\t\"id\": \"PK\",\n\t\t\t\"code\": 586\n\t\t},\n\t\t{\n\t\t\t\"id\": \"PL\",\n\t\t\t\"code\": 616\n\t\t},\n\t\t{\n\t\t\t\"id\": \"PM\",\n\t\t\t\"code\": 666\n\t\t},\n\t\t{\n\t\t\t\"id\": \"PN\",\n\t\t\t\"code\": 612\n\t\t},\n\t\t{\n\t\t\t\"id\": \"PR\",\n\t\t\t\"code\": 630\n\t\t},\n\t\t{\n\t\t\t\"id\": \"PT\",\n\t\t\t\"code\": 620\n\t\t},\n\t\t{\n\t\t\t\"id\": \"PW\",\n\t\t\t\"code\": 585\n\t\t},\n\t\t{\n\t\t\t\"id\": \"PY\",\n\t\t\t\"code\": 600\n\t\t},\n\t\t{\n\t\t\t\"id\": \"QA\",\n\t\t\t\"code\": 634\n\t\t},\n\t\t{\n\t\t\t\"id\": \"RE\",\n\t\t\t\"code\": 638\n\t\t},\n\t\t{\n\t\t\t\"id\": \"RO\",\n\t\t\t\"code\": 642\n\t\t},\n\t\t{\n\t\t\t\"id\": \"RS\",\n\t\t\t\"code\": 688\n\t\t},\n\t\t{\n\t\t\t\"id\": \"RU\",\n\t\t\t\"code\": 643\n\t\t},\n\t\t{\n\t\t\t\"id\": \"RW\",\n\t\t\t\"code\": 646\n\t\t},\n\t\t{\n\t\t\t\"id\": \"SA\",\n\t\t\t\"code\": 682\n\t\t},\n\t\t{\n\t\t\t\"id\": \"SB\",\n\t\t\t\"code\": 90\n\t\t},\n\t\t{\n\t\t\t\"id\": \"SC\",\n\t\t\t\"code\": 690\n\t\t},\n\t\t{\n\t\t\t\"id\": \"SD\",\n\t\t\t\"code\": 736\n\t\t},\n\t\t{\n\t\t\t\"id\": \"SE\",\n\t\t\t\"code\": 752\n\t\t},\n\t\t{\n\t\t\t\"id\": \"SG\",\n\t\t\t\"code\": 702\n\t\t},\n\t\t{\n\t\t\t\"id\": \"SH\",\n\t\t\t\"code\": 654\n\t\t},\n\t\t{\n\t\t\t\"id\": \"SI\",\n\t\t\t\"code\": 705\n\t\t},\n\t\t{\n\t\t\t\"id\": \"SK\",\n\t\t\t\"code\": 703\n\t\t},\n\t\t{\n\t\t\t\"id\": \"SL\",\n\t\t\t\"code\": 694\n\t\t},\n\t\t{\n\t\t\t\"id\": \"SM\",\n\t\t\t\"code\": 674\n\t\t},\n\t\t{\n\t\t\t\"id\": \"SN\",\n\t\t\t\"code\": 686\n\t\t},\n\t\t{\n\t\t\t\"id\": \"SO\",\n\t\t\t\"code\": 706\n\t\t},\n\t\t{\n\t\t\t\"id\": \"SR\",\n\t\t\t\"code\": 740\n\t\t},\n\t\t{\n\t\t\t\"id\": \"ST\",\n\t\t\t\"code\": 678\n\t\t},\n\t\t{\n\t\t\t\"id\": \"SV\",\n\t\t\t\"code\": 222\n\t\t},\n\t\t{\n\t\t\t\"id\": \"SX\",\n\t\t\t\"code\": 534\n\t\t},\n\t\t{\n\t\t\t\"id\": \"SY\",\n\t\t\t\"code\": 760\n\t\t},\n\t\t{\n\t\t\t\"id\": \"SZ\",\n\t\t\t\"code\": 748\n\t\t},\n\t\t{\n\t\t\t\"id\": \"TC\",\n\t\t\t\"code\": 796\n\t\t},\n\t\t{\n\t\t\t\"id\": \"TD\",\n\t\t\t\"code\": 148\n\t\t},\n\t\t{\n\t\t\t\"id\": \"TF\",\n\t\t\t\"code\": 260\n\t\t},\n\t\t{\n\t\t\t\"id\": \"TG\",\n\t\t\t\"code\": 768\n\t\t},\n\t\t{\n\t\t\t\"id\": \"TH\",\n\t\t\t\"code\": 764\n\t\t},\n\t\t{\n\t\t\t\"id\": \"TJ\",\n\t\t\t\"code\": 762\n\t\t},\n\t\t{\n\t\t\t\"id\": \"TK\",\n\t\t\t\"code\": 772\n\t\t},\n\t\t{\n\t\t\t\"id\": \"TL\",\n\t\t\t\"code\": 626\n\t\t},\n\t\t{\n\t\t\t\"id\": \"TM\",\n\t\t\t\"code\": 795\n\t\t},\n\t\t{\n\t\t\t\"id\": \"TN\",\n\t\t\t\"code\": 788\n\t\t},\n\t\t{\n\t\t\t\"id\": \"TO\",\n\t\t\t\"code\": 776\n\t\t},\n\t\t{\n\t\t\t\"id\": \"TR\",\n\t\t\t\"code\": 792\n\t\t},\n\t\t{\n\t\t\t\"id\": \"TT\",\n\t\t\t\"code\": 780\n\t\t},\n\t\t{\n\t\t\t\"id\": \"TV\",\n\t\t\t\"code\": 798\n\t\t},\n\t\t{\n\t\t\t\"id\": \"TW\",\n\t\t\t\"code\": 158\n\t\t},\n\t\t{\n\t\t\t\"id\": \"TZ\",\n\t\t\t\"code\": 834\n\t\t},\n\t\t{\n\t\t\t\"id\": \"UA\",\n\t\t\t\"code\": 804\n\t\t},\n\t\t{\n\t\t\t\"id\": \"UG\",\n\t\t\t\"code\": 800\n\t\t},\n\t\t{\n\t\t\t\"id\": \"US\",\n\t\t\t\"code\": 840\n\t\t},\n\t\t{\n\t\t\t\"id\": \"UY\",\n\t\t\t\"code\": 858\n\t\t},\n\t\t{\n\t\t\t\"id\": \"UZ\",\n\t\t\t\"code\": 860\n\t\t},\n\t\t{\n\t\t\t\"id\": \"VA\",\n\t\t\t\"code\": 336\n\t\t},\n\t\t{\n\t\t\t\"id\": \"VC\",\n\t\t\t\"code\": 670\n\t\t},\n\t\t{\n\t\t\t\"id\": \"VE\",\n\t\t\t\"code\": 862\n\t\t},\n\t\t{\n\t\t\t\"id\": \"VG\",\n\t\t\t\"code\": 92\n\t\t},\n\t\t{\n\t\t\t\"id\": \"VI\",\n\t\t\t\"code\": 850\n\t\t},\n\t\t{\n\t\t\t\"id\": \"VN\",\n\t\t\t\"code\": 704\n\t\t},\n\t\t{\n\t\t\t\"id\": \"VU\",\n\t\t\t\"code\": 548\n\t\t},\n\t\t{\n\t\t\t\"id\": \"WF\",\n\t\t\t\"code\": 876\n\t\t},\n\t\t{\n\t\t\t\"id\": \"WS\",\n\t\t\t\"code\": 882\n\t\t},\n\t\t{\n\t\t\t\"id\": \"YE\",\n\t\t\t\"code\": 887\n\t\t},\n\t\t{\n\t\t\t\"id\": \"ZA\",\n\t\t\t\"code\": 710\n\t\t},\n\t\t{\n\t\t\t\"id\": \"ZM\",\n\t\t\t\"code\": 894\n\t\t},\n\t\t{\n\t\t\t\"id\": \"ZW\",\n\t\t\t\"code\": 716\n\t\t}\n\t],\n\t\"not used\": [\n\t\t{\n\t\t\t\"id\": \"AQ\",\n\t\t\t\"code\": 10\n\t\t},\n\t\t{\n\t\t\t\"id\": \"BQ\",\n\t\t\t\"code\": 535\n\t\t},\n\t\t{\n\t\t\t\"id\": \"BV\",\n\t\t\t\"code\": 74\n\t\t},\n\t\t{\n\t\t\t\"id\": \"HM\",\n\t\t\t\"code\": 334\n\t\t},\n\t\t{\n\t\t\t\"id\": \"PS\",\n\t\t\t\"code\": 275\n\t\t},\n\t\t{\n\t\t\t\"id\": \"SJ\",\n\t\t\t\"code\": 744\n\t\t},\n\t\t{\n\t\t\t\"id\": \"UM\",\n\t\t\t\"code\": 581\n\t\t},\n\t\t{\n\t\t\t\"id\": \"YT\",\n\t\t\t\"code\": 175\n\t\t}\n\t]},\n}\n"
  },
  {
    "path": "data/editor/automap/grass_doodads.json",
    "content": "{\"doodads\": [\n\t{\"vegetation\":\n\t\t{\n\t\t\t\"rules\": [\n\t\t\t{\n\t\t\t\t\"startid\": 1,\n\t\t\t\t\"endid\": 35,\n\t\t\t\t\"ry\": -3,\n\t\t\t\t\"Location\": \"floor\",\n\t\t\t\t\"random\": 25\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"startid\": 44,\n\t\t\t\t\"endid\": 45,\n\t\t\t\t\"ry\": -1,\n\t\t\t\t\"location\": \"floor\",\n\t\t\t\t\"random\": 25\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"startid\": 56,\n\t\t\t\t\"endid\": 74,\n\t\t\t\t\"ry\": -2,\n\t\t\t\t\"location\": \"floor\",\n\t\t\t\t\"random\": 35\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"startid\": 59,\n\t\t\t\t\"endid\": 77,\n\t\t\t\t\"ry\": -2,\n\t\t\t\t\"location\": \"floor\",\n\t\t\t\t\"random\": 35\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"startid\": 48,\n\t\t\t\t\"endid\": 87,\n\t\t\t\t\"ry\": -3,\n\t\t\t\t\"location\": \"floor\",\n\t\t\t\t\"random\": 50\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"startid\": 96,\n\t\t\t\t\"endid\": 164,\n\t\t\t\t\"ry\": -5,\n\t\t\t\t\"location\": \"floor\",\n\t\t\t\t\"random\": 50\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"startid\": 101,\n\t\t\t\t\"endid\": 168,\n\t\t\t\t\"ry\": -5,\n\t\t\t\t\"location\": \"floor\",\n\t\t\t\t\"random\": 50\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"startid\": 90,\n\t\t\t\t\"endid\": 175,\n\t\t\t\t\"ry\": -6,\n\t\t\t\t\"location\": \"floor\",\n\t\t\t\t\"random\": 50\n\t\t\t}]\n\t\t}\n\t},\n\t{\"grass\":\n\t\t{\n\t\t\t\"rules\": [\n\t\t\t{\n\t\t\t\t\"startid\": 42,\n\t\t\t\t\"endid\": 42,\n\t\t\t\t\"ry\": -1,\n\t\t\t\t\"location\": \"floor\",\n\t\t\t\t\"random\": 1\n\t\t\t}]\n\t\t}\n\t}]\n}\n"
  },
  {
    "path": "data/editor/automap/grass_main.json",
    "content": "{\"tileset\": [\n\t{\"grass\":\n\t\t{\n\t\t\t\"basetile\": 1,\n\n\t\t\t\"rules\": [\n\t\t\t{\n\t\t\t\t\"index\": 2,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": 1, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 0, \"y\": -1, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 1, \"y\": 0, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": -1, \"y\": 0, \"value\": \"full\"}\n\t\t\t\t],\n\t\t\t\t\"random\": 150\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 3,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": 1, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 0, \"y\": -1, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 1, \"y\": 0, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": -1, \"y\": 0, \"value\": \"full\"}\n\t\t\t\t],\n\t\t\t\t\"random\": 150\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 66,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": 1, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 0, \"y\": -1, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 1, \"y\": 0, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": -1, \"y\": 0, \"value\": \"full\"}\n\t\t\t\t],\n\t\t\t\t\"random\": 150\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 67,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": 1, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 0, \"y\": -1, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 1, \"y\": 0, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": -1, \"y\": 0, \"value\": \"full\"}\n\t\t\t\t],\n\t\t\t\t\"random\": 150\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 68,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": 1, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 0, \"y\": -1, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 1, \"y\": 0, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": -1, \"y\": 0, \"value\": \"full\"}\n\t\t\t\t],\n\t\t\t\t\"random\": 150\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 16,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": -1, \"value\": \"empty\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 21,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 1, \"y\": 0, \"value\": \"empty\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 52,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": 1, \"value\": \"empty\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 20,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": -1, \"y\": 0, \"value\": \"empty\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 5,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": -1, \"value\": \"empty\"},\n\t\t\t\t\t{\"x\": 1, \"y\": 0, \"value\": \"empty\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 4,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": -1, \"value\": \"empty\"},\n\t\t\t\t\t{\"x\": -1, \"y\": 0, \"value\": \"empty\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 36,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": 1, \"value\": \"empty\"},\n\t\t\t\t\t{\"x\": -1, \"y\": 0, \"value\": \"empty\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 37,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": 1, \"value\": \"empty\"},\n\t\t\t\t\t{\"x\": 1, \"y\": 0, \"value\": \"empty\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 54,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": -1, \"y\": 1, \"value\": \"empty\"},\n\t\t\t\t\t{\"x\": -1, \"y\": 0, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 0, \"y\": 1, \"value\": \"full\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 53,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 1, \"y\": 1, \"value\": \"empty\"},\n\t\t\t\t\t{\"x\": 1, \"y\": 0, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 0, \"y\": 1, \"value\": \"full\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 49,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 1, \"y\": -1, \"value\": \"empty\"},\n\t\t\t\t\t{\"x\": 1, \"y\": 0, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 0, \"y\": -1, \"value\": \"full\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 48,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": -1, \"y\": -1, \"value\": \"empty\"},\n\t\t\t\t\t{\"x\": -1, \"y\": 0, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 0, \"y\": -1, \"value\": \"full\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 22,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": -1, \"y\": 0, \"value\": \"empty\"},\n\t\t\t\t\t{\"x\": -1, \"y\": 1, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 0, \"y\": 1, \"value\": \"full\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 38,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 1, \"y\": 0, \"value\": \"empty\"},\n\t\t\t\t\t{\"x\": 1, \"y\": 1, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 0, \"y\": 1, \"value\": \"full\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 33,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": -1, \"value\": \"empty\"},\n\t\t\t\t\t{\"x\": 1, \"y\": 0, \"value\": \"empty\"},\n\t\t\t\t\t{\"x\": 1, \"y\": 1, \"value\": \"full\"},\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 32,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": -1, \"value\": \"empty\"},\n\t\t\t\t\t{\"x\": -1, \"y\": 0, \"value\": \"empty\"},\n\t\t\t\t\t{\"x\": -1, \"y\": 1, \"value\": \"full\"}\n\t\t\t\t]\n\t\t\t}]\n\t\t}\n\t},\n\t{\"cave\":\n\t\t{\n\t\t\t\"basetile\": 13,\n\n\t\t\t\"rules\": [\n\t\t\t{\n\t\t\t\t\"index\": 29,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": 1, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 0, \"y\": -1, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 1, \"y\": 0, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": -1, \"y\": 0, \"value\": \"full\"}\n\t\t\t\t],\n\t\t\t\t\"random\": 150\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 42,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": 1, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 0, \"y\": -1, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 1, \"y\": 0, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": -1, \"y\": 0, \"value\": \"full\"}\n\t\t\t\t],\n\t\t\t\t\"random\": 150\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 43,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": 1, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 0, \"y\": -1, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 1, \"y\": 0, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": -1, \"y\": 0, \"value\": \"full\"}\n\t\t\t\t],\n\t\t\t\t\"random\": 150\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 44,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": 1, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 0, \"y\": -1, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 1, \"y\": 0, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": -1, \"y\": 0, \"value\": \"full\"}\n\t\t\t\t],\n\t\t\t\t\"random\": 150\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 45,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": 1, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 0, \"y\": -1, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 1, \"y\": 0, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": -1, \"y\": 0, \"value\": \"full\"}\n\t\t\t\t],\n\t\t\t\t\"random\": 150\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 26,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": -1, \"value\": \"empty\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 25,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 1, \"y\": 0, \"value\": \"empty\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 10,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": 1, \"value\": \"empty\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 24,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": -1, \"y\": 0, \"value\": \"empty\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 9,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": -1, \"value\": \"empty\"},\n\t\t\t\t\t{\"x\": 1, \"y\": 0, \"value\": \"empty\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 8,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": -1, \"value\": \"empty\"},\n\t\t\t\t\t{\"x\": -1, \"y\": 0, \"value\": \"empty\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 40,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": 1, \"value\": \"empty\"},\n\t\t\t\t\t{\"x\": -1, \"y\": 0, \"value\": \"empty\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 41,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 0, \"y\": 1, \"value\": \"empty\"},\n\t\t\t\t\t{\"x\": 1, \"y\": 0, \"value\": \"empty\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 12,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": -1, \"y\": 1, \"value\": \"empty\"},\n\t\t\t\t\t{\"x\": -1, \"y\": 0, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 0, \"y\": 1, \"value\": \"full\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 11,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 1, \"y\": 1, \"value\": \"empty\"},\n\t\t\t\t\t{\"x\": 1, \"y\": 0, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 0, \"y\": 1, \"value\": \"full\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 27,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": 1, \"y\": -1, \"value\": \"empty\"},\n\t\t\t\t\t{\"x\": 1, \"y\": 0, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 0, \"y\": -1, \"value\": \"full\"}\n\t\t\t\t]\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"index\": 28,\n\t\t\t\t\"condition\": [\n\t\t\t\t\t{\"x\": -1, \"y\": -1, \"value\": \"empty\"},\n\t\t\t\t\t{\"x\": -1, \"y\": 0, \"value\": \"full\"},\n\t\t\t\t\t{\"x\": 0, \"y\": -1, \"value\": \"full\"}\n\t\t\t\t]\n\t\t\t}]\n\t\t}\n\t}]\n}\n"
  },
  {
    "path": "data/editor/desert_main.rules",
    "content": "[Desert]\nIndex 1\nBaseTile\n\n#random\nIndex 2\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 150\n\nIndex 3\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 150\n\n#top\nIndex 16\nPos 0 -1 EMPTY\n\n#right \nIndex 17\nPos 1 0 EMPTY\n\n#bottom\nIndex 18\nPos 0 1 EMPTY\n\n#left\nIndex 19\nPos -1 0 EMPTY\n\n#corner top-right\nIndex 33\nPos 0 -1 EMPTY\nPos 1 0 EMPTY\n\n#corner top-left\nIndex 32\nPos 0 -1 EMPTY\nPos -1 0 EMPTY\n\n#corner bottom-left\nIndex 35\nPos 0 1 EMPTY\nPos -1 0 EMPTY\n\n#corner bottom-right\nIndex 34\nPos 0 1 EMPTY\nPos 1 0 EMPTY\n\n#inside corner top-right\nIndex 51\nPos -1 1 EMPTY\nPos -1 0 FULL\nPos 0 1 FULL\n\n#inside corner top-left\nIndex 50\nPos 1 1 EMPTY\nPos 1 0 FULL\nPos 0 1 FULL\n\n#inside corner bottom-left\nIndex 49\nPos 1 -1 EMPTY\nPos 1 0 FULL\nPos 0 -1 FULL\n\n#inside corner bottom-right\nIndex 48\nPos -1 -1 EMPTY\nPos -1 0 FULL\nPos 0 -1 FULL\n\n[Mine]\nIndex 81\nBaseTile\n\n#random\nIndex 82\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 500\n\nIndex 83\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 500\n\nIndex 84\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 500\n\nIndex 85\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 500\n\nIndex 86\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 500\n\nIndex 100\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 500\n\nIndex 101\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 500\n\nIndex 102\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 500\n\nIndex 117\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 500\n\nIndex 118\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 500\n\nIndex 133\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 500\n\nIndex 134\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 500\n\n#top\nIndex 96\nPos 0 -1 EMPTY\n\n#right \nIndex 97\nPos 1 0 EMPTY\n\n#bottom\nIndex 98\nPos 0 1 EMPTY\n\n#left\nIndex 99\nPos -1 0 EMPTY\n\n#corner top-right\nIndex 113\nPos 0 -1 EMPTY\nPos 1 0 EMPTY\n\n#corner top-left\nIndex 112\nPos 0 -1 EMPTY\nPos -1 0 EMPTY\n\n#corner bottom-left\nIndex 115\nPos 0 1 EMPTY\nPos -1 0 EMPTY\n\n#corner bottom-right\nIndex 114\nPos 0 1 EMPTY\nPos 1 0 EMPTY\n\n#inside corner top-right\nIndex 131\nPos -1 1 EMPTY\nPos -1 0 FULL\nPos 0 1 FULL\n\n#inside corner top-left\nIndex 130\nPos 1 1 EMPTY\nPos 1 0 FULL\nPos 0 1 FULL\n\n#inside corner bottom-left\nIndex 129\nPos 1 -1 EMPTY\nPos 1 0 FULL\nPos 0 -1 FULL\n\n#inside corner bottom-right\nIndex 128\nPos -1 -1 EMPTY\nPos -1 0 FULL\nPos 0 -1 FULL\n"
  },
  {
    "path": "data/editor/grass_main.rules",
    "content": "[Grass]\nIndex 1\nBaseTile\n\n#random bones\nIndex 2\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 150\n\nIndex 3\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 150\n\nIndex 66\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 150\n\nIndex 67\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 150\n\nIndex 68\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 150\n#---------\n\n#top\nIndex 16\nPos 0 -1 EMPTY\n\n#right\nIndex 21\nPos 1 0 EMPTY\n\n#bottom\nIndex 52\nPos 0 1 EMPTY\n\n#left\nIndex 20\nPos -1 0 EMPTY\n\n#corner top-right\nIndex 5\nPos 0 -1 EMPTY\nPos 1 0 EMPTY\n\n#corner top-left\nIndex 4\nPos 0 -1 EMPTY\nPos -1 0 EMPTY\n\n#corner bottom-left\nIndex 36\nPos 0 1 EMPTY\nPos -1 0 EMPTY\n\n#corner bottom-right\nIndex 37\nPos 0 1 EMPTY\nPos 1 0 EMPTY\n\n#inside corner top-right\nIndex 54\nPos -1 1 EMPTY\nPos -1 0 FULL\nPos 0 1 FULL\n\n#inside corner top-left\nIndex 53\nPos 1 1 EMPTY\nPos 1 0 FULL\nPos 0 1 FULL\n\n#inside corner bottom-left\nIndex 49\nPos 1 -1 EMPTY\nPos 1 0 FULL\nPos 0 -1 FULL\n\n#inside corner bottom-right\nIndex 48\nPos -1 -1 EMPTY\nPos -1 0 FULL\nPos 0 -1 FULL\n\n#right bottom\nIndex 22\nPos -1 0 EMPTY\nPos -1 1 FULL\nPos 0 1 FULL\n\n#left bottom\nIndex 38\nPos 1 0 EMPTY\nPos 1 1 FULL\nPos 0 1 FULL\n\n#top corner right 2\nIndex 33\nPos 0 -1 EMPTY\nPos 1 0 EMPTY\nPos 1 1 FULL\n\n#top corner left 2\nIndex 32\nPos 0 -1 EMPTY\nPos -1 0 EMPTY\nPos -1 1 FULL\n\n[Cave]\nIndex 13\nBaseTile\n\n#random bones\nIndex 29\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 150\n\nIndex 42\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 150\n\nIndex 43\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 150\n\nIndex 44\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 150\n\nIndex 45\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 150\n#---------\n\n#top\nIndex 26\nPos 0 -1 EMPTY\n\n#right\nIndex 25\nPos 1 0 EMPTY\n\n#bottom\nIndex 10\nPos 0 1 EMPTY\n\n#left\nIndex 24\nPos -1 0 EMPTY\n\n#corner top-right\nIndex 9\nPos 0 -1 EMPTY\nPos 1 0 EMPTY\n\n#corner top-left\nIndex 8\nPos 0 -1 EMPTY\nPos -1 0 EMPTY\n\n#corner bottom-left\nIndex 40\nPos 0 1 EMPTY\nPos -1 0 EMPTY\n\n#corner bottom-right\nIndex 41\nPos 0 1 EMPTY\nPos 1 0 EMPTY\n\n#inside corner top-right\nIndex 12\nPos -1 1 EMPTY\nPos -1 0 FULL\nPos 0 1 FULL\n\n#inside corner top-left\nIndex 11\nPos 1 1 EMPTY\nPos 1 0 FULL\nPos 0 1 FULL\n\n#inside corner bottom-left\nIndex 27\nPos 1 -1 EMPTY\nPos 1 0 FULL\nPos 0 -1 FULL\n\n#inside corner bottom-right\nIndex 28\nPos -1 -1 EMPTY\nPos -1 0 FULL\nPos 0 -1 FULL\n"
  },
  {
    "path": "data/editor/jungle_main.rules",
    "content": "[Jungle]\nIndex 1\nBaseTile\n\n#random bricks\nIndex 66\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 200\n\nIndex 67\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 200\n\n#top\nIndex 16\nPos 0 -1 EMPTY\n\nIndex 96\nPos 0 -1 EMPTY\nRandom 15\n\nIndex 97\nPos 0 -1 EMPTY\nRandom 15\n\nIndex 98\nPos 0 -1 EMPTY\nRandom 15\n\n#right \nIndex 21\nPos 1 0 EMPTY\n\n#bottom\nIndex 52\nPos 0 1 EMPTY\n\nIndex 99\nPos 0 1 EMPTY\nRandom 10\n\nIndex 100\nPos 0 1 EMPTY\nRandom 10\n\nIndex 101\nPos 0 1 EMPTY\nRandom 10\n\n#left\nIndex 21 XFLIP\nPos -1 0 EMPTY\n\n#corner top-right\nIndex 5\nPos 0 -1 EMPTY\nPos 1 0 EMPTY\n\n#corner top-left\nIndex 5 XFLIP\nPos 0 -1 EMPTY\nPos -1 0 EMPTY\n\n#corner bottom-left\nIndex 37 XFLIP\nPos 0 1 EMPTY\nPos -1 0 EMPTY\n\nIndex 39 XFLIP\nPos 0 1 EMPTY\nPos -1 0 EMPTY\nRandom 2\n\n#corner bottom-right\nIndex 37\nPos 0 1 EMPTY\nPos 1 0 EMPTY\n\nIndex 39\nPos 0 1 EMPTY\nPos 1 0 EMPTY\nRandom 2\n\n#inside corner top-right\nIndex 54\nPos -1 1 EMPTY\nPos -1 0 FULL\nPos 0 1 FULL\n\nIndex 53 XFLIP\nPos -1 1 EMPTY\nPos -1 0 FULL\nPos 0 1 FULL\nRandom 2\n\n#inside corner top-left\nIndex 54 XFLIP\nPos 1 1 EMPTY\nPos 1 0 FULL\nPos 0 1 FULL\n\nIndex 53\nPos 1 1 EMPTY\nPos 1 0 FULL\nPos 0 1 FULL\nRandom 2\n\n#inside corner bottom-left\nIndex 48 XFLIP\nPos 1 -1 EMPTY\nPos 1 0 FULL\nPos 0 -1 FULL\n\nIndex 49\nPos 1 -1 EMPTY\nPos 1 0 FULL\nPos 0 -1 FULL\nRandom 3\n\nIndex 50 YFLIP\nPos 1 -1 EMPTY\nPos 1 0 FULL\nPos 0 -1 FULL\nRandom 3\n\n#inside corner bottom-right\nIndex 48\nPos -1 -1 EMPTY\nPos -1 0 FULL\nPos 0 -1 FULL\n\nIndex 49 XFLIP\nPos -1 -1 EMPTY\nPos -1 0 FULL\nPos 0 -1 FULL\nRandom 3\n\nIndex 51 YFLIP\nPos -1 -1 EMPTY\nPos -1 0 FULL\nPos 0 -1 FULL\nRandom 3\n\n#right bottom\nIndex 22\nPos -1 0 EMPTY\nPos -1 1 FULL\nPos 0 1 FULL\n\n#left bottom\nIndex 22 XFLIP\nPos 1 0 EMPTY\nPos 1 1 FULL\nPos 0 1 FULL\n\n#top corner right 2\nIndex 33\nPos 0 -1 EMPTY\nPos 1 0 EMPTY\nPos 1 1 FULL\n\n#top corner left 2\nIndex 32\nPos 0 -1 EMPTY\nPos -1 0 EMPTY\nPos -1 1 FULL\n\n[Jungle dark]\nIndex 13\nBaseTile\n\n#random bricks\nIndex 42\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 150\n\nIndex 43\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 150\n\nIndex 44\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 150\n\nIndex 45\nPos 0 1 FULL\nPos 0 -1 FULL\nPos 1 0 FULL\nPos -1 0 FULL\nRandom 150\n#---------\n\n#top\nIndex 26\nPos 0 -1 EMPTY\n\n#right \nIndex 25\nPos 1 0 EMPTY\n\n#bottom\nIndex 10\nPos 0 1 EMPTY\n\n#left\nIndex 24\nPos -1 0 EMPTY\n\n#corner top-right\nIndex 9\nPos 0 -1 EMPTY\nPos 1 0 EMPTY\n\n#corner top-left\nIndex 8\nPos 0 -1 EMPTY\nPos -1 0 EMPTY\n\n#corner bottom-left\nIndex 40\nPos 0 1 EMPTY\nPos -1 0 EMPTY\n\n#corner bottom-right\nIndex 41\nPos 0 1 EMPTY\nPos 1 0 EMPTY\n\n#inside corner top-right\nIndex 12\nPos -1 1 EMPTY\nPos -1 0 FULL\nPos 0 1 FULL\n\n#inside corner top-left\nIndex 11\nPos 1 1 EMPTY\nPos 1 0 FULL\nPos 0 1 FULL\n\n#inside corner bottom-left\nIndex 27\nPos 1 -1 EMPTY\nPos 1 0 FULL\nPos 0 -1 FULL\n\n#inside corner bottom-right\nIndex 28\nPos -1 -1 EMPTY\nPos -1 0 FULL\nPos 0 -1 FULL\n"
  },
  {
    "path": "data/editor/winter_main.rules",
    "content": "[Winter]\nIndex 1\nBaseTile\n\n#top\nIndex 17\nPos 0 -1 EMPTY\n\nIndex 18\nPos 0 -1 EMPTY\nPos -1 0 INDEX 17\n\nIndex 19\nPos 0 -1 EMPTY\nPos -1 0 INDEX 18\n\n#bottom\nIndex 97\nPos 0 1 EMPTY\n\nIndex 98\nPos 0 1 EMPTY\nPos -1 0 INDEX 97\n\nIndex 99\nPos 0 1 EMPTY\nPos -1 0 INDEX 98\n\n#right\nIndex 2 XFLIP\nPos 1 0 EMPTY\n\n#left\nIndex 2\nPos -1 0 EMPTY\n\n#corner top right\nIndex 20\nPos 0 -1 EMPTY\nPos 1 0 EMPTY\n\nIndex 24\nPos 0 -1 EMPTY\nPos 1 0 EMPTY\nPos -1 0 INDEX 17\n\n#corner top left\nIndex 16\nPos 0 -1 EMPTY\nPos -1 0 EMPTY\n\n#corner bottom right\nIndex 100\nPos 0 1 EMPTY\nPos 1 0 EMPTY\n\n#corner bottom left\nIndex 96\nPos 0 1 EMPTY\nPos -1 0 EMPTY\n\n#inside corner top right\nIndex 8\nPos 0 1 FULL\nPos -1 0 FULL\nPos -1 1 EMPTY\n\n#inside corner top left\nIndex 7\nPos 0 1 FULL\nPos 1 0 FULL\nPos 1 1 EMPTY\n\n#inside corner bottom right\nIndex 4\nPos 0 -1 FULL\nPos -1 0 FULL\nPos -1 -1 EMPTY\n\n#inside corner bottom left\nIndex 3\nPos 0 -1 FULL\nPos 1 0 FULL\nPos 1 -1 EMPTY\n\n#one tile height\nIndex 113\nPos 0 1 EMPTY\nPos 0 -1 EMPTY\n\nIndex 114\nPos 0 1 EMPTY\nPos 0 -1 EMPTY\nPos -1 0 INDEX 113\n\nIndex 115\nPos 0 1 EMPTY\nPos 0 -1 EMPTY\nPos -1 0 INDEX 114\n\n#one tile height right\nIndex 116\nPos 0 1 EMPTY\nPos 0 -1 EMPTY\nPos 1 0 EMPTY\n\nIndex 120\nPos 0 1 EMPTY\nPos 0 -1 EMPTY\nPos 1 0 EMPTY\nPos -1 0 INDEX 113\n\n#one tile height left\nIndex 112\nPos 0 1 EMPTY\nPos 0 -1 EMPTY\nPos -1 0 EMPTY\n\n#one tile height link right\nIndex 6\nPos -1 -1 EMPTY\nPos -1 0 FULL\nPos 0 -1 FULL\nPos -1 1 EMPTY\n\n#one tile height link left\nIndex 5\nPos 1 -1 EMPTY\nPos 1 0 FULL\nPos 0 -1 FULL\nPos 1 1 EMPTY\n\n[Winter dark]\nIndex 177\nBaseTile\n\n#bottom\nIndex 194\nPos 0 1 EMPTY\n\nIndex 195\nPos 0 1 EMPTY\nPos -1 0 INDEX 194\n\nIndex 196\nPos 0 1 EMPTY\nPos -1 0 INDEX 195\n\n#right\nIndex 178 XFLIP\nPos 1 0 EMPTY\n\n#left\nIndex 178\nPos -1 0 EMPTY\n\n#corner bottom right\nIndex 197\nPos 0 1 EMPTY\nPos 1 0 EMPTY\n\n#corner bottom left\nIndex 193\nPos 0 1 EMPTY\nPos -1 0 EMPTY\n\n#inside corner top right\nIndex 180\nPos 0 1 FULL\nPos -1 0 FULL\nPos -1 1 EMPTY\n\n#inside corner top left\nIndex 179\nPos 0 1 FULL\nPos 1 0 FULL\nPos 1 1 EMPTY\n"
  },
  {
    "path": "data/fonts/LICENSE",
    "content": "Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.\nGlyphs imported from Arev fonts are (c) Tavmjong Bah (see below)\n\nBitstream Vera Fonts Copyright\n------------------------------\n\nCopyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is\na trademark of Bitstream, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof the fonts accompanying this license (\"Fonts\") and associated\ndocumentation files (the \"Font Software\"), to reproduce and distribute the\nFont Software, including without limitation the rights to use, copy, merge,\npublish, distribute, and/or sell copies of the Font Software, and to permit\npersons to whom the Font Software is furnished to do so, subject to the\nfollowing conditions:\n\nThe above copyright and trademark notices and this permission notice shall\nbe included in all copies of one or more of the Font Software typefaces.\n\nThe Font Software may be modified, altered, or added to, and in particular\nthe designs of glyphs or characters in the Fonts may be modified and\nadditional glyphs or characters may be added to the Fonts, only if the fonts\nare renamed to names not containing either the words \"Bitstream\" or the word\n\"Vera\".\n\nThis License becomes null and void to the extent applicable to Fonts or Font\nSoftware that has been modified and is distributed under the \"Bitstream\nVera\" names.\n\nThe Font Software may be sold as part of a larger software package but no\ncopy of one or more of the Font Software typefaces may be sold by itself.\n\nTHE FONT SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,\nTRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME\nFOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING\nANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF\nTHE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE\nFONT SOFTWARE.\n\nExcept as contained in this notice, the names of Gnome, the Gnome\nFoundation, and Bitstream Inc., shall not be used in advertising or\notherwise to promote the sale, use or other dealings in this Font Software\nwithout prior written authorization from the Gnome Foundation or Bitstream\nInc., respectively. For further information, contact: fonts at gnome dot\norg. \n\nArev Fonts Copyright\n------------------------------\n\nCopyright (c) 2006 by Tavmjong Bah. All Rights Reserved.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of the fonts accompanying this license (\"Fonts\") and\nassociated documentation files (the \"Font Software\"), to reproduce\nand distribute the modifications to the Bitstream Vera Font Software,\nincluding without limitation the rights to use, copy, merge, publish,\ndistribute, and/or sell copies of the Font Software, and to permit\npersons to whom the Font Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright and trademark notices and this permission notice\nshall be included in all copies of one or more of the Font Software\ntypefaces.\n\nThe Font Software may be modified, altered, or added to, and in\nparticular the designs of glyphs or characters in the Fonts may be\nmodified and additional glyphs or characters may be added to the\nFonts, only if the fonts are renamed to names not containing either\nthe words \"Tavmjong Bah\" or the word \"Arev\".\n\nThis License becomes null and void to the extent applicable to Fonts\nor Font Software that has been modified and is distributed under the \n\"Tavmjong Bah Arev\" names.\n\nThe Font Software may be sold as part of a larger software package but\nno copy of one or more of the Font Software typefaces may be sold by\nitself.\n\nTHE FONT SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT\nOF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL\nTAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nINCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL\nDAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM\nOTHER DEALINGS IN THE FONT SOFTWARE.\n\nExcept as contained in this notice, the name of Tavmjong Bah shall not\nbe used in advertising or otherwise to promote the sale, use or other\ndealings in this Font Software without prior written authorization\nfrom Tavmjong Bah. For further information, contact: tavmjong @ free\n. fr.\n\n$Id: LICENSE 2133 2007-11-28 02:46:28Z lechimp $\n"
  },
  {
    "path": "data/fonts/VERSION",
    "content": "2.33\r\n"
  },
  {
    "path": "data/skins/bluekitty.json",
    "content": "{\"skin\": {\n\t\"body\": {\n\t\t\"filename\": \"kitty\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 132,\n\t\t\"sat\": 118,\n\t\t\"lgt\": 184\n\t},\n\t\"tattoo\": {\n\t\t\"filename\": \"whisker\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 130,\n\t\t\"sat\": 109,\n\t\t\"lgt\": 219,\n\t\t\"alp\": 255\n\t},\n\t\"hands\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 120,\n\t\t\"sat\": 82,\n\t\t\"lgt\": 235\n\t},\n\t\"feet\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 120,\n\t\t\"sat\": 82,\n\t\t\"lgt\": 235\n\t},\n\t\"eyes\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"false\"\n\t}}\n}\n"
  },
  {
    "path": "data/skins/bluestripe.json",
    "content": "{\"skin\": {\n\t\"body\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 155,\n\t\t\"sat\": 116,\n\t\t\"lgt\": 122\n\t},\n\t\"tattoo\": {\n\t\t\"filename\": \"stripes\",\n\t\t\"custom_colors\": \"false\"\n\t},\n\t\"hands\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 11,\n\t\t\"sat\": 117,\n\t\t\"lgt\": 0\n\t},\n\t\"feet\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 29,\n\t\t\"sat\": 173,\n\t\t\"lgt\": 87\n\t},\n\t\"eyes\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"false\"\n\t}}\n}\n"
  },
  {
    "path": "data/skins/brownbear.json",
    "content": "{\"skin\": {\n\t\"body\": {\n\t\t\"filename\": \"bear\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 16,\n\t\t\"sat\": 133,\n\t\t\"lgt\": 121\n\t},\n\t\"tattoo\": {\n\t\t\"filename\": \"bear\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 17,\n\t\t\"sat\": 110,\n\t\t\"lgt\": 168,\n\t\t\"alp\": 255\n\t},\n\t\"decoration\": {\n\t\t\"filename\": \"hair\",\n\t\t\"custom_colors\": \"false\"\n\t},\n\t\"hands\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 16,\n\t\t\"sat\": 133,\n\t\t\"lgt\": 121\n\t},\n\t\"feet\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 17,\n\t\t\"sat\": 129,\n\t\t\"lgt\": 38\n\t},\n\t\"eyes\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"false\"\n\t}}\n}\n"
  },
  {
    "path": "data/skins/cammo.json",
    "content": "{\"skin\": {\n\t\"body\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 81,\n\t\t\"sat\": 101,\n\t\t\"lgt\": 70\n\t},\n\t\"tattoo\": {\n\t\t\"filename\": \"cammo2\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 76,\n\t\t\"sat\": 97,\n\t\t\"lgt\": 45,\n\t\t\"alp\": 255\n\t},\n\t\"hands\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 11,\n\t\t\"sat\": 117,\n\t\t\"lgt\": 0\n\t},\n\t\"feet\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 29,\n\t\t\"sat\": 173,\n\t\t\"lgt\": 87\n\t},\n\t\"eyes\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"false\"\n\t}}\n}\n"
  },
  {
    "path": "data/skins/cammostripes.json",
    "content": "{\"skin\": {\n\t\"body\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 81,\n\t\t\"sat\": 101,\n\t\t\"lgt\": 70\n\t},\n\t\"tattoo\": {\n\t\t\"filename\": \"cammostripes\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 29,\n\t\t\"sat\": 142,\n\t\t\"lgt\": 0,\n\t\t\"alp\": 255\n\t},\n\t\"hands\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 11,\n\t\t\"sat\": 117,\n\t\t\"lgt\": 0\n\t},\n\t\"feet\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 29,\n\t\t\"sat\": 173,\n\t\t\"lgt\": 87\n\t},\n\t\"eyes\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"false\"\n\t}}\n}\n"
  },
  {
    "path": "data/skins/coala.json",
    "content": "{\"skin\": {\n\t\"body\": {\n\t\t\"filename\": \"bear\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 0,\n\t\t\"sat\": 0,\n\t\t\"lgt\": 184\n\t},\n\t\"tattoo\": {\n\t\t\"filename\": \"bear\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 21,\n\t\t\"sat\": 12,\n\t\t\"lgt\": 226,\n\t\t\"alp\": 255\n\t},\n\t\"decoration\": {\n\t\t\"filename\": \"hair\",\n\t\t\"custom_colors\": \"false\"\n\t},\n\t\"hands\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 0,\n\t\t\"sat\": 0,\n\t\t\"lgt\": 184\n\t},\n\t\"feet\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 149,\n\t\t\"sat\": 4,\n\t\t\"lgt\": 71\n\t},\n\t\"eyes\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"false\"\n\t}}\n}\n"
  },
  {
    "path": "data/skins/default.json",
    "content": "{\"skin\": {\n\t\"body\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 27,\n\t\t\"sat\": 111,\n\t\t\"lgt\": 116\n\t},\n\t\"hands\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 27,\n\t\t\"sat\": 117,\n\t\t\"lgt\": 158\n\t},\n\t\"feet\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 28,\n\t\t\"sat\": 135,\n\t\t\"lgt\": 62\n\t},\n\t\"eyes\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"false\"\n\t}}\n}\n"
  },
  {
    "path": "data/skins/limekitty.json",
    "content": "{\"skin\": {\n\t\"body\": {\n\t\t\"filename\": \"kitty\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 70,\n\t\t\"sat\": 98,\n\t\t\"lgt\": 195\n\t},\n\t\"tattoo\": {\n\t\t\"filename\": \"whisker\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 69,\n\t\t\"sat\": 98,\n\t\t\"lgt\": 224,\n\t\t\"alp\": 255\n\t},\n\t\"hands\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 58,\n\t\t\"sat\": 104,\n\t\t\"lgt\": 239\n\t},\n\t\"feet\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 58,\n\t\t\"sat\": 104,\n\t\t\"lgt\": 239\n\t},\n\t\"eyes\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"false\"\n\t}}\n}\n"
  },
  {
    "path": "data/skins/pinky.json",
    "content": "{\"skin\": {\n\t\"body\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 242,\n\t\t\"sat\": 201,\n\t\t\"lgt\": 187\n\t},\n\t\"tattoo\": {\n\t\t\"filename\": \"whisker\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 243,\n\t\t\"sat\": 198,\n\t\t\"lgt\": 214,\n\t\t\"alp\": 255\n\t},\n\t\"hands\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 229,\n\t\t\"sat\": 137,\n\t\t\"lgt\": 218\n\t},\n\t\"feet\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 229,\n\t\t\"sat\": 137,\n\t\t\"lgt\": 218\n\t},\n\t\"eyes\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"false\"\n\t}}\n}\n"
  },
  {
    "path": "data/skins/redbopp.json",
    "content": "{\"skin\": {\n\t\"body\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 246,\n\t\t\"sat\": 216,\n\t\t\"lgt\": 108\n\t},\n\t\"tattoo\": {\n\t\t\"filename\": \"donny\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 2,\n\t\t\"sat\": 217,\n\t\t\"lgt\": 202,\n\t\t\"alp\": 255\n\t},\n\t\"decoration\": {\n\t\t\"filename\": \"unibop\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 246,\n\t\t\"sat\": 216,\n\t\t\"lgt\": 108\n\t},\n\t\"hands\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 246,\n\t\t\"sat\": 216,\n\t\t\"lgt\": 108\n\t},\n\t\"feet\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 116,\n\t\t\"sat\": 85,\n\t\t\"lgt\": 233\n\t},\n\t\"eyes\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"false\"\n\t}}\n}\n"
  },
  {
    "path": "data/skins/redstripe.json",
    "content": "{\"skin\": {\n\t\"body\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 248,\n\t\t\"sat\": 214,\n\t\t\"lgt\": 123\n\t},\n\t\"tattoo\": {\n\t\t\"filename\": \"stripe\",\n\t\t\"custom_colors\": \"false\"\n\t},\n\t\"hands\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 0,\n\t\t\"sat\": 0,\n\t\t\"lgt\": 184\n\t},\n\t\"feet\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 149,\n\t\t\"sat\": 4,\n\t\t\"lgt\": 71\n\t},\n\t\"eyes\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"false\"\n\t}}\n}\n"
  },
  {
    "path": "data/skins/saddo.json",
    "content": "{\"skin\": {\n\t\"body\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 109,\n\t\t\"sat\": 109,\n\t\t\"lgt\": 127\n\t},\n\t\"tattoo\": {\n\t\t\"filename\": \"saddo\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 108,\n\t\t\"sat\": 54,\n\t\t\"lgt\": 68,\n\t\t\"alp\": 255\n\t},\n\t\"hands\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 55,\n\t\t\"sat\": 141,\n\t\t\"lgt\": 170\n\t},\n\t\"feet\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 88,\n\t\t\"sat\": 97,\n\t\t\"lgt\": 119\n\t},\n\t\"eyes\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"false\"\n\t}}\n}\n"
  },
  {
    "path": "data/skins/toptri.json",
    "content": "{\"skin\": {\n\t\"body\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 93,\n\t\t\"sat\": 95,\n\t\t\"lgt\": 163\n\t},\n\t\"tattoo\": {\n\t\t\"filename\": \"toptri\",\n\t\t\"custom_colors\": \"false\"\n\t},\n\t\"hands\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 55,\n\t\t\"sat\": 141,\n\t\t\"lgt\": 170\n\t},\n\t\"feet\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 88,\n\t\t\"sat\": 97,\n\t\t\"lgt\": 119\n\t},\n\t\"eyes\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"false\"\n\t}}\n}\n"
  },
  {
    "path": "data/skins/twinbop.json",
    "content": "{\"skin\": {\n\t\"body\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 233,\n\t\t\"sat\": 158,\n\t\t\"lgt\": 183\n\t},\n\t\"tattoo\": {\n\t\t\"filename\": \"duodonny\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 231,\n\t\t\"sat\": 146,\n\t\t\"lgt\": 218,\n\t\t\"alp\": 255\n\t},\n\t\"decoration\": {\n\t\t\"filename\": \"twinbopp\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 233,\n\t\t\"sat\": 158,\n\t\t\"lgt\": 183\n\t},\n\t\"hands\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 233,\n\t\t\"sat\": 158,\n\t\t\"lgt\": 183\n\t},\n\t\"feet\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 0,\n\t\t\"sat\": 146,\n\t\t\"lgt\": 224\n\t},\n\t\"eyes\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"false\"\n\t}}\n}\n"
  },
  {
    "path": "data/skins/twintri.json",
    "content": "{\"skin\": {\n\t\"body\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 52,\n\t\t\"sat\": 156,\n\t\t\"lgt\": 124\n\t},\n\t\"tattoo\": {\n\t\t\"filename\": \"twintri\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 40,\n\t\t\"sat\": 222,\n\t\t\"lgt\": 227,\n\t\t\"alp\": 255\n\t},\n\t\"hands\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 0,\n\t\t\"sat\": 0,\n\t\t\"lgt\": 185\n\t},\n\t\"feet\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 147,\n\t\t\"sat\": 4,\n\t\t\"lgt\": 72\n\t},\n\t\"eyes\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"false\"\n\t}}\n}\n"
  },
  {
    "path": "data/skins/warpaint.json",
    "content": "{\"skin\": {\n\t\"body\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 29,\n\t\t\"sat\": 173,\n\t\t\"lgt\": 87\n\t},\n\t\"tattoo\": {\n\t\t\"filename\": \"warpaint\",\n\t\t\"custom_colors\": \"false\"\n\t},\n\t\"hands\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 11,\n\t\t\"sat\": 115,\n\t\t\"lgt\": 1\n\t},\n\t\"feet\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 29,\n\t\t\"sat\": 173,\n\t\t\"lgt\": 87\n\t},\n\t\"eyes\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"false\"\n\t}}\n}\n"
  },
  {
    "path": "data/skins/x_ninja.json",
    "content": "{\"skin\": {\n\t\"body\": {\n\t\t\"filename\": \"x_ninja\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 0,\n\t\t\"sat\": 0,\n\t\t\"lgt\": 0\n\t},\n\t\"tattoo\": {\n\t\t\"filename\": \"uppy\",\n\t\t\"custom_colors\": \"true\",\n\t\t\"hue\": 0,\n\t\t\"sat\": 0,\n\t\t\"lgt\": 255,\n\t\t\"alp\": 127\n\t},\n\t\"hands\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"false\"\n\t},\n\t\"feet\": {\n\t\t\"filename\": \"standard\",\n\t\t\"custom_colors\": \"false\"\n\t},\n\t\"eyes\": {\n\t\t\"filename\": \"x_ninja\",\n\t\t\"custom_colors\": \"false\"\n\t}}\n}\n"
  },
  {
    "path": "datasrc/compile.py",
    "content": "import os, imp, sys\nfrom datatypes import *\nimport content\nimport network\n\ndef create_enum_table(names, num):\n\tlines = []\n\tlines += [\"enum\", \"{\"]\n\tlines += [\"\\t%s=0,\"%names[0]]\n\tfor name in names[1:]:\n\t\tlines += [\"\\t%s,\"%name]\n\tlines += [\"\\t%s\" % num, \"};\"]\n\treturn lines\n\ndef create_flags_table(names):\n\tlines = []\n\tlines += [\"enum\", \"{\"]\n\ti = 0\n\tfor name in names:\n\t\tlines += [\"\\t%s = 1<<%d,\" % (name,i)]\n\t\ti += 1\n\tlines += [\"};\"]\n\treturn lines\n\ndef EmitEnum(names, num):\n\tprint(\"enum\")\n\tprint(\"{\")\n\tprint(\"\\t%s=0,\" % names[0])\n\tfor name in names[1:]:\n\t\tprint(\"\\t%s,\" % name)\n\tprint(\"\\t%s\" % num)\n\tprint(\"};\")\n\ndef EmitFlags(names, num):\n\tprint(\"enum\")\n\tprint(\"{\")\n\ti = 0\n\tfor name in names:\n\t\tprint(\"\\t%s = 1<<%d,\" % (name,i))\n\t\ti += 1\n\tprint(\"};\")\n\ngen_network_header = False\ngen_network_source = False\ngen_client_content_header = False\ngen_client_content_source = False\ngen_server_content_header = False\ngen_server_content_source = False\n\nif \"network_header\" in sys.argv: gen_network_header = True\nif \"network_source\" in sys.argv: gen_network_source = True\nif \"client_content_header\" in sys.argv: gen_client_content_header = True\nif \"client_content_source\" in sys.argv: gen_client_content_source = True\nif \"server_content_header\" in sys.argv: gen_server_content_header = True\nif \"server_content_source\" in sys.argv: gen_server_content_source = True\n\nif gen_client_content_header:\n\tprint(\"#ifndef CLIENT_CONTENT_HEADER\")\n\tprint(\"#define CLIENT_CONTENT_HEADER\")\n\nif gen_server_content_header:\n\tprint(\"#ifndef SERVER_CONTENT_HEADER\")\n\tprint(\"#define SERVER_CONTENT_HEADER\")\n\n\nif gen_client_content_header or gen_server_content_header:\n\t# print some includes\n\tprint('#include <engine/graphics.h>')\n\tprint('#include <engine/sound.h>')\n\n\t# emit the type declarations\n\tcontentlines = open(\"datasrc/content.py\", \"rb\").readlines()\n\torder = []\n\tfor line in contentlines:\n\t\tline = line.strip()\n\t\tif line[:6] == \"class \".encode() and \"(Struct)\".encode() in line:\n\t\t\torder += [line.split()[1].split(\"(\".encode())[0].decode(\"ascii\")]\n\tfor name in order:\n\t\tEmitTypeDeclaration(content.__dict__[name])\n\n\t# the container pointer\n\tprint('extern CDataContainer *g_pData;')\n\n\t# enums\n\tEmitEnum([\"IMAGE_%s\"%i.name.value.upper() for i in content.container.images.items], \"NUM_IMAGES\")\n\tEmitEnum([\"ANIM_%s\"%i.name.value.upper() for i in content.container.animations.items], \"NUM_ANIMS\")\n\tEmitEnum([\"SPRITE_%s\"%i.name.value.upper() for i in content.container.sprites.items], \"NUM_SPRITES\")\n\nif gen_client_content_source or gen_server_content_source:\n\tif gen_client_content_source:\n\t\tprint('#include \"client_data.h\"')\n\tif gen_server_content_source:\n\t\tprint('#include \"server_data.h\"')\n\tEmitDefinition(content.container, \"datacontainer\")\n\tprint('CDataContainer *g_pData = &datacontainer;')\n\n# NETWORK\nif gen_network_header:\n\n\tprint(\"#ifndef GAME_GENERATED_PROTOCOL_H\")\n\tprint(\"#define GAME_GENERATED_PROTOCOL_H\")\n\tprint(network.RawHeader)\n\n\tfor e in network.Enums:\n\t\tfor l in create_enum_table([\"%s_%s\"%(e.name, v) for v in e.values], 'NUM_%sS'%e.name): print(l)\n\t\tprint(\"\")\n\n\tfor e in network.Flags:\n\t\tfor l in create_flags_table([\"%s_%s\" % (e.name, v) for v in e.values]): print(l)\n\t\tprint(\"\")\n\n\tfor l in create_enum_table([\"NETOBJ_INVALID\"]+[o.enum_name for o in network.Objects], \"NUM_NETOBJTYPES\"): print(l)\n\tprint(\"\")\n\tfor l in create_enum_table([\"NETMSG_INVALID\"]+[o.enum_name for o in network.Messages], \"NUM_NETMSGTYPES\"): print(l)\n\tprint(\"\")\n\n\tfor item in network.Objects + network.Messages:\n\t\tfor line in item.emit_declaration():\n\t\t\tprint(line)\n\t\tprint(\"\")\n\n\tEmitEnum([\"SOUND_%s\"%i.name.value.upper() for i in content.container.sounds.items], \"NUM_SOUNDS\")\n\tEmitEnum([\"WEAPON_%s\"%i.name.value.upper() for i in content.container.weapons.id.items], \"NUM_WEAPONS\")\n\n\tprint(\"\"\"\n\nclass CNetObjHandler\n{\n\tconst char *m_pMsgFailedOn;\n\tconst char *m_pObjCorrectedOn;\n\tchar m_aMsgData[1024];\n\tint m_NumObjCorrections;\n\tint ClampInt(const char *pErrorMsg, int Value, int Min, int Max);\n\tint ClampFlag(const char *pErrorMsg, int Value, int Mask);\n\n\tstatic const char *ms_apObjNames[];\n\tstatic int ms_aObjSizes[];\n\tstatic const char *ms_apMsgNames[];\n\npublic:\n\tCNetObjHandler();\n\n\tint ValidateObj(int Type, void *pData, int Size);\n\tconst char *GetObjName(int Type);\n\tint GetObjSize(int Type);\n\tint NumObjCorrections();\n\tconst char *CorrectedObjOn();\n\n\tconst char *GetMsgName(int Type);\n\tvoid *SecureUnpackMsg(int Type, CUnpacker *pUnpacker);\n\tconst char *FailedMsgOn();\n};\n\n\"\"\")\n\n\tprint(\"#endif // GAME_GENERATED_PROTOCOL_H\")\n\n\nif gen_network_source:\n\t# create names\n\tlines = []\n\n\tlines += ['#include <engine/shared/protocol.h>']\n\tlines += ['#include <engine/message.h>']\n\tlines += ['#include \"protocol.h\"']\n\n\tlines += ['CNetObjHandler::CNetObjHandler()']\n\tlines += ['{']\n\tlines += ['\\tm_pMsgFailedOn = \"\";']\n\tlines += ['\\tm_pObjCorrectedOn = \"\";']\n\tlines += ['\\tm_NumObjCorrections = 0;']\n\tlines += ['}']\n\tlines += ['']\n\tlines += ['int CNetObjHandler::NumObjCorrections() { return m_NumObjCorrections; }']\n\tlines += ['const char *CNetObjHandler::CorrectedObjOn() { return m_pObjCorrectedOn; }']\n\tlines += ['const char *CNetObjHandler::FailedMsgOn() { return m_pMsgFailedOn; }']\n\tlines += ['']\n\tlines += ['']\n\tlines += ['']\n\tlines += ['']\n\tlines += ['']\n\n\tlines += ['static const int max_int = 0x7fffffff;']\n\tlines += ['']\n\n\tlines += ['int CNetObjHandler::ClampInt(const char *pErrorMsg, int Value, int Min, int Max)']\n\tlines += ['{']\n\tlines += ['\\tif(Value < Min) { m_pObjCorrectedOn = pErrorMsg; m_NumObjCorrections++; return Min; }']\n\tlines += ['\\tif(Value > Max) { m_pObjCorrectedOn = pErrorMsg; m_NumObjCorrections++; return Max; }']\n\tlines += ['\\treturn Value;']\n\tlines += ['}']\n\tlines += ['']\n\n\tlines += ['int CNetObjHandler::ClampFlag(const char *pErrorMsg, int Value, int Mask)']\n\tlines += ['{']\n\tlines += ['\\tif((Value&Mask) != Value) { m_pObjCorrectedOn = pErrorMsg; m_NumObjCorrections++; return (Value&Mask); }']\n\tlines += ['\\treturn Value;']\n\tlines += ['}']\n\tlines += ['']\n\n\tlines += [\"const char *CNetObjHandler::ms_apObjNames[] = {\"]\n\tlines += ['\\t\"invalid\",']\n\tlines += ['\\t\"%s\",' % o.name for o in network.Objects]\n\tlines += ['\\t\"\"', \"};\", \"\"]\n\n\tlines += [\"int CNetObjHandler::ms_aObjSizes[] = {\"]\n\tlines += ['\\t0,']\n\tlines += ['\\tsizeof(%s),' % o.struct_name for o in network.Objects]\n\tlines += ['\\t0', \"};\", \"\"]\n\n\n\tlines += ['const char *CNetObjHandler::ms_apMsgNames[] = {']\n\tlines += ['\\t\"invalid\",']\n\tfor msg in network.Messages:\n\t\tlines += ['\\t\"%s\",' % msg.name]\n\tlines += ['\\t\"\"']\n\tlines += ['};']\n\tlines += ['']\n\n\tlines += ['const char *CNetObjHandler::GetObjName(int Type)']\n\tlines += ['{']\n\tlines += ['\\tif(Type < 0 || Type >= NUM_NETOBJTYPES) return \"(out of range)\";']\n\tlines += ['\\treturn ms_apObjNames[Type];']\n\tlines += ['};']\n\tlines += ['']\n\n\tlines += ['int CNetObjHandler::GetObjSize(int Type)']\n\tlines += ['{']\n\tlines += ['\\tif(Type < 0 || Type >= NUM_NETOBJTYPES) return 0;']\n\tlines += ['\\treturn ms_aObjSizes[Type];']\n\tlines += ['};']\n\tlines += ['']\n\n\n\tlines += ['const char *CNetObjHandler::GetMsgName(int Type)']\n\tlines += ['{']\n\tlines += ['\\tif(Type < 0 || Type >= NUM_NETMSGTYPES) return \"(out of range)\";']\n\tlines += ['\\treturn ms_apMsgNames[Type];']\n\tlines += ['};']\n\tlines += ['']\n\n\n\tfor l in lines:\n\t\tprint(l)\n\n\tif 0:\n\t\tfor item in network.Objects:\n\t\t\tfor line in item.emit_validate():\n\t\t\t\tprint(line)\n\t\t\tprint(\"\")\n\n\t# create validate tables\n\t\tlines = []\n\t\tlines += ['static int validate_invalid(void *data, int size) { return -1; }']\n\t\tlines += [\"typedef int(*VALIDATEFUNC)(void *data, int size);\"]\n\t\tlines += [\"static VALIDATEFUNC validate_funcs[] = {\"]\n\t\tlines += ['\\tvalidate_invalid,']\n\t\tlines += ['\\tvalidate_%s,' % o.name for o in network.Objects]\n\t\tlines += [\"\\t0x0\", \"};\", \"\"]\n\n\t\tlines += [\"int netobj_validate(int type, void *data, int size)\"]\n\t\tlines += [\"{\"]\n\t\tlines += [\"\\tif(type < 0 || type >= NUM_NETOBJTYPES) return -1;\"]\n\t\tlines += [\"\\treturn validate_funcs[type](data, size);\"]\n\t\tlines += [\"};\", \"\"]\n\n\tlines = []\n\tlines += ['int CNetObjHandler::ValidateObj(int Type, void *pData, int Size)']\n\tlines += ['{']\n\tlines += ['\\tswitch(Type)']\n\tlines += ['\\t{']\n\n\tfor item in network.Objects:\n\t\tfor line in item.emit_validate():\n\t\t\tlines += [\"\\t\" + line]\n\t\tlines += ['\\t']\n\tlines += ['\\t}']\n\tlines += ['\\treturn -1;']\n\tlines += ['};']\n\tlines += ['']\n\n #int Validate(int Type, void *pData, int Size);\n\n\tif 0:\n\t\tfor item in network.Messages:\n\t\t\tfor line in item.emit_unpack():\n\t\t\t\tprint(line)\n\t\t\tprint(\"\")\n\n\t\tlines += ['static void *secure_unpack_invalid(CUnpacker *pUnpacker) { return 0; }']\n\t\tlines += ['typedef void *(*SECUREUNPACKFUNC)(CUnpacker *pUnpacker);']\n\t\tlines += ['static SECUREUNPACKFUNC secure_unpack_funcs[] = {']\n\t\tlines += ['\\tsecure_unpack_invalid,']\n\t\tfor msg in network.Messages:\n\t\t\tlines += ['\\tsecure_unpack_%s,' % msg.name]\n\t\tlines += ['\\t0x0']\n\t\tlines += ['};']\n\n\t#\n\tlines += ['void *CNetObjHandler::SecureUnpackMsg(int Type, CUnpacker *pUnpacker)']\n\tlines += ['{']\n\tlines += ['\\tm_pMsgFailedOn = 0;']\n\tlines += ['\\tswitch(Type)']\n\tlines += ['\\t{']\n\n\n\tfor item in network.Messages:\n\t\tfor line in item.emit_unpack():\n\t\t\tlines += [\"\\t\" + line]\n\t\tlines += ['\\t']\n\n\tlines += ['\\tdefault:']\n\tlines += ['\\t\\tm_pMsgFailedOn = \"(type out of range)\";']\n\tlines += ['\\t\\tbreak;']\n\tlines += ['\\t}']\n\tlines += ['\\t']\n\tlines += ['\\tif(pUnpacker->Error())']\n\tlines += ['\\t\\tm_pMsgFailedOn = \"(unpack error)\";']\n\tlines += ['\\t']\n\tlines += ['\\tif(m_pMsgFailedOn)']\n\tlines += ['\\t\\treturn 0;']\n\tlines += ['\\tm_pMsgFailedOn = \"\";']\n\tlines += ['\\treturn m_aMsgData;']\n\tlines += ['};']\n\tlines += ['']\n\n\n\tfor l in lines:\n\t\tprint(l)\n\nif gen_client_content_header or gen_server_content_header:\n\tprint(\"#endif\")\n"
  },
  {
    "path": "datasrc/content.py",
    "content": "import copy\nfrom datatypes import *\n\nclass Sound(Struct):\n\tdef __init__(self, filename=\"\"):\n\t\tStruct.__init__(self, \"CDataSound\")\n\t\tself.id = SampleHandle()\n\t\tself.filename = String(filename)\n\nclass SoundSet(Struct):\n\tdef __init__(self, name=\"\", files=[]):\n\t\tStruct.__init__(self, \"CDataSoundset\")\n\t\tself.name = String(name)\n\t\tself.sounds = Array(Sound())\n\t\tself.last = Int(-1)\n\t\tfor name in files:\n\t\t\tself.sounds.Add(Sound(name))\n\nclass Image(Struct):\n\tdef __init__(self, name=\"\", filename=\"\"):\n\t\tStruct.__init__(self, \"CDataImage\")\n\t\tself.name = String(name)\n\t\tself.filename = String(filename)\n\t\tself.id = TextureHandle()\n\nclass SpriteSet(Struct):\n\tdef __init__(self, name=\"\", image=None, gridx=0, gridy=0):\n\t\tStruct.__init__(self, \"CDataSpriteset\")\n\t\tself.image = Pointer(Image, image) # TODO\n\t\tself.gridx = Int(gridx)\n\t\tself.gridy = Int(gridy)\n\nclass Sprite(Struct):\n\tdef __init__(self, name=\"\", Set=None, x=0, y=0, w=0, h=0):\n\t\tStruct.__init__(self, \"CDataSprite\")\n\t\tself.name = String(name)\n\t\tself.set = Pointer(SpriteSet, Set) # TODO\n\t\tself.x = Int(x)\n\t\tself.y = Int(y)\n\t\tself.w = Int(w)\n\t\tself.h = Int(h)\n\nclass Pickup(Struct):\n\tdef __init__(self, name=\"\", respawntime=15, spawndelay=0):\n\t\tStruct.__init__(self, \"CDataPickupspec\")\n\t\tself.name = String(name)\n\t\tself.respawntime = Int(respawntime)\n\t\tself.spawndelay = Int(spawndelay)\n\nclass AnimKeyframe(Struct):\n\tdef __init__(self, time=0, x=0, y=0, angle=0):\n\t\tStruct.__init__(self, \"CAnimKeyframe\")\n\t\tself.time = Float(time)\n\t\tself.x = Float(x)\n\t\tself.y = Float(y)\n\t\tself.angle = Float(angle)\n\nclass AnimSequence(Struct):\n\tdef __init__(self):\n\t\tStruct.__init__(self, \"CAnimSequence\")\n\t\tself.frames = Array(AnimKeyframe())\n\nclass Animation(Struct):\n\tdef __init__(self, name=\"\"):\n\t\tStruct.__init__(self, \"CAnimation\")\n\t\tself.name = String(name)\n\t\tself.body = AnimSequence()\n\t\tself.back_foot = AnimSequence()\n\t\tself.front_foot = AnimSequence()\n\t\tself.attach = AnimSequence()\n\nclass WeaponSpec(Struct):\n\tdef __init__(self, container=None, name=\"\"):\n\t\tStruct.__init__(self, \"CDataWeaponspec\")\n\t\tself.name = String(name)\n\t\tself.sprite_body = Pointer(Sprite, Sprite())\n\t\tself.sprite_cursor = Pointer(Sprite, Sprite())\n\t\tself.sprite_proj = Pointer(Sprite, Sprite())\n\t\tself.sprite_muzzles = Array(Pointer(Sprite, Sprite()))\n\t\tself.visual_size = Int(96)\n\n\t\tself.firedelay = Int(500)\n\t\tself.maxammo = Int(10)\n\t\tself.ammoregentime = Int(0)\n\t\tself.damage = Int(1)\n\n\t\tself.offsetx = Float(0)\n\t\tself.offsety = Float(0)\n\t\tself.muzzleoffsetx = Float(0)\n\t\tself.muzzleoffsety = Float(0)\n\t\tself.muzzleduration = Float(5)\n\n\t\t# dig out sprites if we have a container\n\t\tif container:\n\t\t\tfor sprite in container.sprites.items:\n\t\t\t\tif sprite.name.value == \"weapon_\"+name+\"_body\": self.sprite_body.Set(sprite)\n\t\t\t\telif sprite.name.value == \"weapon_\"+name+\"_cursor\": self.sprite_cursor.Set(sprite)\n\t\t\t\telif sprite.name.value == \"weapon_\"+name+\"_proj\": self.sprite_proj.Set(sprite)\n\t\t\t\telif \"weapon_\"+name+\"_muzzle\" in sprite.name.value:\n\t\t\t\t\tself.sprite_muzzles.Add(Pointer(Sprite, sprite))\n\nclass Weapon_Hammer(Struct):\n\tdef __init__(self):\n\t\tStruct.__init__(self, \"CDataWeaponspecHammer\")\n\t\tself.base = Pointer(WeaponSpec, WeaponSpec())\n\nclass Weapon_Gun(Struct):\n\tdef __init__(self):\n\t\tStruct.__init__(self, \"CDataWeaponspecGun\")\n\t\tself.base = Pointer(WeaponSpec, WeaponSpec())\n\t\tself.curvature = Float(1.25)\n\t\tself.speed = Float(2200)\n\t\tself.lifetime = Float(2.0)\n\nclass Weapon_Shotgun(Struct):\n\tdef __init__(self):\n\t\tStruct.__init__(self, \"CDataWeaponspecShotgun\")\n\t\tself.base = Pointer(WeaponSpec, WeaponSpec())\n\t\tself.curvature = Float(1.25)\n\t\tself.speed = Float(2200)\n\t\tself.speeddiff = Float(0.8)\n\t\tself.lifetime = Float(0.25)\n\nclass Weapon_Grenade(Struct):\n\tdef __init__(self):\n\t\tStruct.__init__(self, \"CDataWeaponspecGrenade\")\n\t\tself.base = Pointer(WeaponSpec, WeaponSpec())\n\t\tself.curvature = Float(7.0)\n\t\tself.speed = Float(1000)\n\t\tself.lifetime = Float(2.0)\n\nclass Weapon_Laser(Struct):\n\tdef __init__(self):\n\t\tStruct.__init__(self, \"CDataWeaponspecLaser\")\n\t\tself.base = Pointer(WeaponSpec, WeaponSpec())\n\t\tself.reach = Float(800.0)\n\t\tself.bounce_delay = Int(150)\n\t\tself.bounce_num = Int(1)\n\t\tself.bounce_cost = Float(0)\n\nclass Weapon_Ninja(Struct):\n\tdef __init__(self):\n\t\tStruct.__init__(self, \"CDataWeaponspecNinja\")\n\t\tself.base = Pointer(WeaponSpec, WeaponSpec())\n\t\tself.duration = Int(15000)\n\t\tself.movetime = Int(200)\n\t\tself.velocity = Int(50)\n\nclass Weapons(Struct):\n\tdef __init__(self):\n\t\tStruct.__init__(self, \"CDataWeaponspecs\")\n\t\tself.hammer = Weapon_Hammer()\n\t\tself.gun = Weapon_Gun()\n\t\tself.shotgun = Weapon_Shotgun()\n\t\tself.grenade = Weapon_Grenade()\n\t\tself.laser = Weapon_Laser()\n\t\tself.ninja = Weapon_Ninja()\n\t\tself.id = Array(WeaponSpec())\n\nclass DataContainer(Struct):\n\tdef __init__(self):\n\t\tStruct.__init__(self, \"CDataContainer\")\n\t\tself.sounds = Array(SoundSet())\n\t\tself.images = Array(Image())\n\t\tself.pickups = Array(Pickup())\n\t\tself.spritesets = Array(SpriteSet())\n\t\tself.sprites = Array(Sprite())\n\t\tself.animations = Array(Animation())\n\t\tself.weapons = Weapons()\n\ndef FileList(format, num):\n\treturn [format%(x+1) for x in range(0,num)]\n\ncontainer = DataContainer()\ncontainer.sounds.Add(SoundSet(\"gun_fire\", FileList(\"audio/wp_gun_fire-%02d.wv\", 3)))\ncontainer.sounds.Add(SoundSet(\"shotgun_fire\", FileList(\"audio/wp_shotty_fire-%02d.wv\", 3)))\n\ncontainer.sounds.Add(SoundSet(\"grenade_fire\", FileList(\"audio/wp_flump_launch-%02d.wv\", 3)))\ncontainer.sounds.Add(SoundSet(\"hammer_fire\", FileList(\"audio/wp_hammer_swing-%02d.wv\", 3)))\ncontainer.sounds.Add(SoundSet(\"hammer_hit\", FileList(\"audio/wp_hammer_hit-%02d.wv\", 3)))\ncontainer.sounds.Add(SoundSet(\"ninja_fire\", FileList(\"audio/wp_ninja_attack-%02d.wv\", 3)))\ncontainer.sounds.Add(SoundSet(\"grenade_explode\", FileList(\"audio/wp_flump_explo-%02d.wv\", 3)))\ncontainer.sounds.Add(SoundSet(\"ninja_hit\", FileList(\"audio/wp_ninja_hit-%02d.wv\", 3)))\ncontainer.sounds.Add(SoundSet(\"laser_fire\", FileList(\"audio/wp_laser_fire-%02d.wv\", 3)))\ncontainer.sounds.Add(SoundSet(\"laser_bounce\", FileList(\"audio/wp_laser_bnce-%02d.wv\", 3)))\ncontainer.sounds.Add(SoundSet(\"weapon_switch\", FileList(\"audio/wp_switch-%02d.wv\", 3)))\n\ncontainer.sounds.Add(SoundSet(\"player_pain_short\", FileList(\"audio/vo_teefault_pain_short-%02d.wv\", 12)))\ncontainer.sounds.Add(SoundSet(\"player_pain_long\", FileList(\"audio/vo_teefault_pain_long-%02d.wv\", 2)))\n\ncontainer.sounds.Add(SoundSet(\"body_land\", FileList(\"audio/foley_land-%02d.wv\", 4)))\ncontainer.sounds.Add(SoundSet(\"player_airjump\", FileList(\"audio/foley_dbljump-%02d.wv\", 3)))\ncontainer.sounds.Add(SoundSet(\"player_jump\", FileList(\"audio/foley_foot_left-%02d.wv\", 4) + FileList(\"audio/foley_foot_right-%02d.wv\", 4)))\ncontainer.sounds.Add(SoundSet(\"player_die\", FileList(\"audio/foley_body_splat-%02d.wv\", 3)))\ncontainer.sounds.Add(SoundSet(\"player_spawn\", FileList(\"audio/vo_teefault_spawn-%02d.wv\", 7)))\ncontainer.sounds.Add(SoundSet(\"player_skid\", FileList(\"audio/sfx_skid-%02d.wv\", 4)))\ncontainer.sounds.Add(SoundSet(\"tee_cry\", FileList(\"audio/vo_teefault_cry-%02d.wv\", 2)))\n\ncontainer.sounds.Add(SoundSet(\"hook_loop\", FileList(\"audio/hook_loop-%02d.wv\", 2)))\n\ncontainer.sounds.Add(SoundSet(\"hook_attach_ground\", FileList(\"audio/hook_attach-%02d.wv\", 3)))\ncontainer.sounds.Add(SoundSet(\"hook_attach_player\", FileList(\"audio/foley_body_impact-%02d.wv\", 3)))\ncontainer.sounds.Add(SoundSet(\"hook_noattach\", FileList(\"audio/hook_noattach-%02d.wv\", 2)))\ncontainer.sounds.Add(SoundSet(\"pickup_health\", FileList(\"audio/sfx_pickup_hrt-%02d.wv\", 2)))\ncontainer.sounds.Add(SoundSet(\"pickup_armor\", FileList(\"audio/sfx_pickup_arm-%02d.wv\", 4)))\n\ncontainer.sounds.Add(SoundSet(\"pickup_grenade\", [\"audio/sfx_pickup_launcher.wv\"]))\ncontainer.sounds.Add(SoundSet(\"pickup_shotgun\", [\"audio/sfx_pickup_sg.wv\"]))\ncontainer.sounds.Add(SoundSet(\"pickup_ninja\", [\"audio/sfx_pickup_ninja.wv\"]))\ncontainer.sounds.Add(SoundSet(\"weapon_spawn\", FileList(\"audio/sfx_spawn_wpn-%02d.wv\", 3)))\ncontainer.sounds.Add(SoundSet(\"weapon_noammo\", FileList(\"audio/wp_noammo-%02d.wv\", 5)))\n\ncontainer.sounds.Add(SoundSet(\"hit\", FileList(\"audio/sfx_hit_weak-%02d.wv\", 2)))\n\ncontainer.sounds.Add(SoundSet(\"chat_server\", [\"audio/sfx_msg-server.wv\"]))\ncontainer.sounds.Add(SoundSet(\"chat_client\", [\"audio/sfx_msg-client.wv\"]))\ncontainer.sounds.Add(SoundSet(\"chat_highlight\", [\"audio/sfx_msg-highlight.wv\"]))\ncontainer.sounds.Add(SoundSet(\"ctf_drop\", [\"audio/sfx_ctf_drop.wv\"]))\ncontainer.sounds.Add(SoundSet(\"ctf_return\", [\"audio/sfx_ctf_rtn.wv\"]))\ncontainer.sounds.Add(SoundSet(\"ctf_grab_pl\", [\"audio/sfx_ctf_grab_pl.wv\"]))\ncontainer.sounds.Add(SoundSet(\"ctf_grab_en\", [\"audio/sfx_ctf_grab_en.wv\"]))\ncontainer.sounds.Add(SoundSet(\"ctf_capture\", [\"audio/sfx_ctf_cap_pl.wv\"]))\n\ncontainer.sounds.Add(SoundSet(\"menu\", [\"audio/music_menu.wv\"]))\n\nimage_null = Image(\"null\", \"\")\nimage_particles = Image(\"particles\", \"particles.png\")\nimage_game = Image(\"game\", \"game.png\")\nimage_browseicons = Image(\"browseicons\", \"icons/browse.png\")\nimage_emoticons = Image(\"emoticons\", \"emoticons.png\")\nimage_demobuttons = Image(\"demobuttons\", \"demo_buttons.png\")\nimage_fileicons = Image(\"fileicons\", \"file_icons.png\")\nimage_guibuttons = Image(\"guibuttons\", \"gui_buttons.png\")\nimage_guiicons = Image(\"guiicons\", \"gui_icons.png\")\nimage_menuicons = Image(\"menuicons\", \"icons/menu.png\")\nimage_toolicons = Image(\"toolicons\", \"icons/tools.png\")\nimage_infoicons = Image(\"infoicons\", \"icons/info.png\")\n\ncontainer.images.Add(image_null)\ncontainer.images.Add(image_game)\ncontainer.images.Add(Image(\"deadtee\", \"deadtee.png\"))\ncontainer.images.Add(image_particles)\ncontainer.images.Add(Image(\"cursor\", \"gui_cursor.png\"))\ncontainer.images.Add(Image(\"banner\", \"gui_logo.png\"))\ncontainer.images.Add(image_emoticons)\ncontainer.images.Add(image_browseicons)\ncontainer.images.Add(Image(\"console_bg\", \"console.png\"))\ncontainer.images.Add(Image(\"console_bar\", \"console_bar.png\"))\ncontainer.images.Add(image_demobuttons)\ncontainer.images.Add(image_fileicons)\ncontainer.images.Add(image_guibuttons)\ncontainer.images.Add(image_guiicons)\ncontainer.images.Add(Image(\"no_skinpart\", \"no_skinpart.png\"))\ncontainer.images.Add(image_menuicons)\ncontainer.images.Add(image_toolicons)\ncontainer.images.Add(image_infoicons)\n\ncontainer.pickups.Add(Pickup(\"health\"))\ncontainer.pickups.Add(Pickup(\"armor\"))\ncontainer.pickups.Add(Pickup(\"grenade\"))\ncontainer.pickups.Add(Pickup(\"shotgun\"))\ncontainer.pickups.Add(Pickup(\"laser\"))\ncontainer.pickups.Add(Pickup(\"ninja\", 90, 90))\n\nset_particles = SpriteSet(\"particles\", image_particles, 8, 8)\nset_game = SpriteSet(\"game\", image_game, 32, 16)\nset_tee_body = SpriteSet(\"tee_body\", image_null, 2, 2)\nset_tee_tattoos = SpriteSet(\"tee_tattoos\", image_null, 1, 1)\nset_tee_decoration = SpriteSet(\"tee_decoration\", image_null, 2, 1)\nset_tee_hands = SpriteSet(\"tee_hands\", image_null, 2, 1)\nset_tee_feet = SpriteSet(\"tee_feet\", image_null, 2, 1)\nset_tee_eyes = SpriteSet(\"tee_eyes\", image_null, 2, 4)\nset_browseicons = SpriteSet(\"browseicons\", image_browseicons, 4, 2)\nset_emoticons = SpriteSet(\"emoticons\", image_emoticons, 4, 4)\nset_demobuttons = SpriteSet(\"demobuttons\", image_demobuttons, 5, 1)\nset_fileicons = SpriteSet(\"fileicons\", image_fileicons, 8, 1)\nset_guibuttons = SpriteSet(\"guibuttons\", image_guibuttons, 12, 4)\nset_guiicons = SpriteSet(\"guiicons\", image_guiicons, 8, 2)\nset_menuicons = SpriteSet(\"menuicons\", image_menuicons, 2, 2)\nset_toolicons = SpriteSet(\"toolicons\", image_toolicons, 4, 2)\nset_infoicons = SpriteSet(\"infoicons\", image_infoicons, 1, 2)\n\ncontainer.spritesets.Add(set_particles)\ncontainer.spritesets.Add(set_game)\ncontainer.spritesets.Add(set_tee_body)\ncontainer.spritesets.Add(set_tee_tattoos)\ncontainer.spritesets.Add(set_tee_decoration)\ncontainer.spritesets.Add(set_tee_hands)\ncontainer.spritesets.Add(set_tee_feet)\ncontainer.spritesets.Add(set_tee_eyes)\ncontainer.spritesets.Add(set_browseicons)\ncontainer.spritesets.Add(set_emoticons)\ncontainer.spritesets.Add(set_demobuttons)\ncontainer.spritesets.Add(set_fileicons)\ncontainer.spritesets.Add(set_guibuttons)\ncontainer.spritesets.Add(set_guiicons)\ncontainer.spritesets.Add(set_menuicons)\ncontainer.spritesets.Add(set_toolicons)\ncontainer.spritesets.Add(set_infoicons)\n\ncontainer.sprites.Add(Sprite(\"part_slice\", set_particles, 0,0,1,1))\ncontainer.sprites.Add(Sprite(\"part_ball\", set_particles, 1,0,1,1))\ncontainer.sprites.Add(Sprite(\"part_splat01\", set_particles, 2,0,1,1))\ncontainer.sprites.Add(Sprite(\"part_splat02\", set_particles, 3,0,1,1))\ncontainer.sprites.Add(Sprite(\"part_splat03\", set_particles, 4,0,1,1))\n\ncontainer.sprites.Add(Sprite(\"part_smoke\", set_particles, 0,1,1,1))\ncontainer.sprites.Add(Sprite(\"part_shell\", set_particles, 0,2,2,2))\ncontainer.sprites.Add(Sprite(\"part_expl01\", set_particles, 0,4,4,4))\ncontainer.sprites.Add(Sprite(\"part_airjump\", set_particles, 2,2,2,2))\ncontainer.sprites.Add(Sprite(\"part_hit01\", set_particles, 4,1,2,2))\n\ncontainer.sprites.Add(Sprite(\"health_full\", set_game, 21,0,2,2))\ncontainer.sprites.Add(Sprite(\"health_empty\", set_game, 23,0,2,2))\ncontainer.sprites.Add(Sprite(\"armor_full\", set_game, 21,2,2,2))\ncontainer.sprites.Add(Sprite(\"armor_empty\", set_game, 23,2,2,2))\n\ncontainer.sprites.Add(Sprite(\"star1\", set_game, 15,0,2,2))\ncontainer.sprites.Add(Sprite(\"star2\", set_game, 17,0,2,2))\ncontainer.sprites.Add(Sprite(\"star3\", set_game, 19,0,2,2))\n\ncontainer.sprites.Add(Sprite(\"part1\", set_game, 6,0,1,1))\ncontainer.sprites.Add(Sprite(\"part2\", set_game, 6,1,1,1))\ncontainer.sprites.Add(Sprite(\"part3\", set_game, 7,0,1,1))\ncontainer.sprites.Add(Sprite(\"part4\", set_game, 7,1,1,1))\ncontainer.sprites.Add(Sprite(\"part5\", set_game, 8,0,1,1))\ncontainer.sprites.Add(Sprite(\"part6\", set_game, 8,1,1,1))\ncontainer.sprites.Add(Sprite(\"part7\", set_game, 9,0,2,2))\ncontainer.sprites.Add(Sprite(\"part8\", set_game, 11,0,2,2))\ncontainer.sprites.Add(Sprite(\"part9\", set_game, 13,0,2,2))\n\ncontainer.sprites.Add(Sprite(\"weapon_gun_body\", set_game, 2,4,4,2))\ncontainer.sprites.Add(Sprite(\"weapon_gun_cursor\", set_game, 0,4,2,2))\ncontainer.sprites.Add(Sprite(\"weapon_gun_proj\", set_game, 6,4,2,2))\ncontainer.sprites.Add(Sprite(\"weapon_gun_muzzle1\", set_game, 8,4,3,2))\ncontainer.sprites.Add(Sprite(\"weapon_gun_muzzle2\", set_game, 12,4,3,2))\ncontainer.sprites.Add(Sprite(\"weapon_gun_muzzle3\", set_game, 16,4,3,2))\n\ncontainer.sprites.Add(Sprite(\"weapon_shotgun_body\", set_game, 2,6,8,2))\ncontainer.sprites.Add(Sprite(\"weapon_shotgun_cursor\", set_game, 0,6,2,2))\ncontainer.sprites.Add(Sprite(\"weapon_shotgun_proj\", set_game, 10,6,2,2))\ncontainer.sprites.Add(Sprite(\"weapon_shotgun_muzzle1\", set_game, 12,6,3,2))\ncontainer.sprites.Add(Sprite(\"weapon_shotgun_muzzle2\", set_game, 16,6,3,2))\ncontainer.sprites.Add(Sprite(\"weapon_shotgun_muzzle3\", set_game, 20,6,3,2))\n\ncontainer.sprites.Add(Sprite(\"weapon_grenade_body\", set_game, 2,8,7,2))\ncontainer.sprites.Add(Sprite(\"weapon_grenade_cursor\", set_game, 0,8,2,2))\ncontainer.sprites.Add(Sprite(\"weapon_grenade_proj\", set_game, 10,8,2,2))\n\ncontainer.sprites.Add(Sprite(\"weapon_hammer_body\", set_game, 2,1,4,3))\ncontainer.sprites.Add(Sprite(\"weapon_hammer_cursor\", set_game, 0,0,2,2))\ncontainer.sprites.Add(Sprite(\"weapon_hammer_proj\", set_game, 0,0,0,0))\n\ncontainer.sprites.Add(Sprite(\"weapon_ninja_body\", set_game, 2,10,8,2))\ncontainer.sprites.Add(Sprite(\"weapon_ninja_cursor\", set_game, 0,10,2,2))\ncontainer.sprites.Add(Sprite(\"weapon_ninja_proj\", set_game, 0,0,0,0))\n\ncontainer.sprites.Add(Sprite(\"weapon_laser_body\", set_game, 2,12,7,3))\ncontainer.sprites.Add(Sprite(\"weapon_laser_cursor\", set_game, 0,12,2,2))\ncontainer.sprites.Add(Sprite(\"weapon_laser_proj\", set_game, 10,12,2,2))\n\ncontainer.sprites.Add(Sprite(\"hook_chain\", set_game, 2,0,1,1))\ncontainer.sprites.Add(Sprite(\"hook_head\", set_game, 3,0,2,1))\n\ncontainer.sprites.Add(Sprite(\"weapon_ninja_muzzle1\", set_game, 25,0,7,4))\ncontainer.sprites.Add(Sprite(\"weapon_ninja_muzzle2\", set_game, 25,4,7,4))\ncontainer.sprites.Add(Sprite(\"weapon_ninja_muzzle3\", set_game, 25,8,7,4))\n\ncontainer.sprites.Add(Sprite(\"pickup_health\", set_game, 10,2,2,2))\ncontainer.sprites.Add(Sprite(\"pickup_armor\", set_game, 12,2,2,2))\ncontainer.sprites.Add(Sprite(\"pickup_grenade\", set_game, 2,8,7,2))\ncontainer.sprites.Add(Sprite(\"pickup_shotgun\", set_game, 2,6,8,2))\ncontainer.sprites.Add(Sprite(\"pickup_laser\", set_game, 2,12,7,3))\ncontainer.sprites.Add(Sprite(\"pickup_ninja\", set_game, 2,10,8,2))\n\ncontainer.sprites.Add(Sprite(\"flag_blue\", set_game, 12,8,4,8))\ncontainer.sprites.Add(Sprite(\"flag_red\", set_game, 16,8,4,8))\n\ncontainer.sprites.Add(Sprite(\"tee_body_outline\", set_tee_body, 0,0,1,1))\ncontainer.sprites.Add(Sprite(\"tee_body\", set_tee_body, 1,0,1,1))\ncontainer.sprites.Add(Sprite(\"tee_body_shadow\", set_tee_body, 0,1,1,1))\ncontainer.sprites.Add(Sprite(\"tee_body_upper_outline\", set_tee_body, 1,1,1,1))\n\ncontainer.sprites.Add(Sprite(\"tee_tattoo\", set_tee_tattoos, 0,0,1,1))\n\ncontainer.sprites.Add(Sprite(\"tee_decoration\", set_tee_decoration, 0,0,1,1))\ncontainer.sprites.Add(Sprite(\"tee_decoration_outline\", set_tee_decoration, 1,0,1,1))\n\ncontainer.sprites.Add(Sprite(\"tee_hand\", set_tee_hands, 0,0,1,1))\ncontainer.sprites.Add(Sprite(\"tee_hand_outline\", set_tee_hands, 1,0,1,1))\n\ncontainer.sprites.Add(Sprite(\"tee_foot\", set_tee_feet, 0,0,1,1))\ncontainer.sprites.Add(Sprite(\"tee_foot_outline\", set_tee_feet, 1,0,1,1))\n\ncontainer.sprites.Add(Sprite(\"tee_eyes_normal\", set_tee_eyes, 0,0,1,1))\ncontainer.sprites.Add(Sprite(\"tee_eyes_angry\", set_tee_eyes, 1,0,1,1))\ncontainer.sprites.Add(Sprite(\"tee_eyes_pain\", set_tee_eyes, 0,1,1,1))\ncontainer.sprites.Add(Sprite(\"tee_eyes_happy\", set_tee_eyes, 1,1,1,1))\ncontainer.sprites.Add(Sprite(\"tee_eyes_surprise\", set_tee_eyes, 0,2,1,1))\n\ncontainer.sprites.Add(Sprite(\"oop\", set_emoticons, 0, 0, 1, 1))\ncontainer.sprites.Add(Sprite(\"exclamation\", set_emoticons, 1, 0, 1, 1))\ncontainer.sprites.Add(Sprite(\"hearts\", set_emoticons, 2, 0, 1, 1))\ncontainer.sprites.Add(Sprite(\"drop\", set_emoticons, 3, 0, 1, 1))\ncontainer.sprites.Add(Sprite(\"dotdot\", set_emoticons, 0, 1, 1, 1))\ncontainer.sprites.Add(Sprite(\"music\", set_emoticons, 1, 1, 1, 1))\ncontainer.sprites.Add(Sprite(\"sorry\", set_emoticons, 2, 1, 1, 1))\ncontainer.sprites.Add(Sprite(\"ghost\", set_emoticons, 3, 1, 1, 1))\ncontainer.sprites.Add(Sprite(\"sushi\", set_emoticons, 0, 2, 1, 1))\ncontainer.sprites.Add(Sprite(\"splattee\", set_emoticons, 1, 2, 1, 1))\ncontainer.sprites.Add(Sprite(\"deviltee\", set_emoticons, 2, 2, 1, 1))\ncontainer.sprites.Add(Sprite(\"zomg\", set_emoticons, 3, 2, 1, 1))\ncontainer.sprites.Add(Sprite(\"zzz\", set_emoticons, 0, 3, 1, 1))\ncontainer.sprites.Add(Sprite(\"wtf\", set_emoticons, 1, 3, 1, 1))\ncontainer.sprites.Add(Sprite(\"eyes\", set_emoticons, 2, 3, 1, 1))\ncontainer.sprites.Add(Sprite(\"question\", set_emoticons, 3, 3, 1, 1))\n\ncontainer.sprites.Add(Sprite(\"browse_lock_a\", set_browseicons, 0,0,1,1))\ncontainer.sprites.Add(Sprite(\"browse_lock_b\", set_browseicons, 0,1,1,1))\n#container.sprites.Add(Sprite(\"browse_lock_c\", set_browseicons, 2,0,1,1))\ncontainer.sprites.Add(Sprite(\"browse_unpure_a\", set_browseicons, 1,0,1,1))\ncontainer.sprites.Add(Sprite(\"browse_unpure_b\", set_browseicons, 1,1,1,1))\n#container.sprites.Add(Sprite(\"browse_unpure_c\", set_browseicons, 2,1,1,1))\ncontainer.sprites.Add(Sprite(\"browse_star_a\", set_browseicons, 2,0,1,1))\ncontainer.sprites.Add(Sprite(\"browse_star_b\", set_browseicons, 2,1,1,1))\n#container.sprites.Add(Sprite(\"browse_star_c\", set_browseicons, 2,2,1,1))\ncontainer.sprites.Add(Sprite(\"browse_heart_a\", set_browseicons, 3,0,1,1))\ncontainer.sprites.Add(Sprite(\"browse_heart_b\", set_browseicons, 3,1,1,1))\n#container.sprites.Add(Sprite(\"browse_heart_c\", set_browseicons, 2,3,1,1))\n\ncontainer.sprites.Add(Sprite(\"demobutton_play\", set_demobuttons, 0,0,1,1))\ncontainer.sprites.Add(Sprite(\"demobutton_pause\", set_demobuttons, 1,0,1,1))\ncontainer.sprites.Add(Sprite(\"demobutton_stop\", set_demobuttons, 2,0,1,1))\ncontainer.sprites.Add(Sprite(\"demobutton_slower\", set_demobuttons, 3,0,1,1))\ncontainer.sprites.Add(Sprite(\"demobutton_faster\", set_demobuttons, 4,0,1,1))\n\ncontainer.sprites.Add(Sprite(\"file_demo1\", set_fileicons, 0,0,1,1))\ncontainer.sprites.Add(Sprite(\"file_demo2\", set_fileicons, 1,0,1,1))\ncontainer.sprites.Add(Sprite(\"file_folder\", set_fileicons, 2,0,1,1))\ncontainer.sprites.Add(Sprite(\"file_map1\", set_fileicons, 5,0,1,1))\ncontainer.sprites.Add(Sprite(\"file_map2\", set_fileicons, 6,0,1,1))\n\ncontainer.sprites.Add(Sprite(\"guibutton_off\", set_guibuttons, 0,0,4,4))\ncontainer.sprites.Add(Sprite(\"guibutton_on\", set_guibuttons, 4,0,4,4))\ncontainer.sprites.Add(Sprite(\"guibutton_hover\", set_guibuttons, 8,0,4,4))\n\ncontainer.sprites.Add(Sprite(\"guiicon_mute\", set_guiicons, 0,0,4,2))\ncontainer.sprites.Add(Sprite(\"guiicon_friend\", set_guiicons, 4,0,4,2))\n\ncontainer.sprites.Add(Sprite(\"menu_checkbox_active\", set_menuicons, 0,0,1,1))\ncontainer.sprites.Add(Sprite(\"menu_checkbox_inactive\", set_menuicons, 0,1,1,1))\ncontainer.sprites.Add(Sprite(\"menu_collapsed\", set_menuicons, 1,0,1,1))\ncontainer.sprites.Add(Sprite(\"menu_expanded\", set_menuicons, 1,1,1,1))\n\ncontainer.sprites.Add(Sprite(\"tool_up_a\", set_toolicons, 0,0,1,1))\ncontainer.sprites.Add(Sprite(\"tool_up_b\", set_toolicons, 0,1,1,1))\ncontainer.sprites.Add(Sprite(\"tool_down_a\", set_toolicons, 1,0,1,1))\ncontainer.sprites.Add(Sprite(\"tool_down_b\", set_toolicons, 1,1,1,1))\ncontainer.sprites.Add(Sprite(\"tool_edit_a\", set_toolicons, 2,0,1,1))\ncontainer.sprites.Add(Sprite(\"tool_edit_b\", set_toolicons, 2,1,1,1))\ncontainer.sprites.Add(Sprite(\"tool_x_a\", set_toolicons, 3,0,1,1))\ncontainer.sprites.Add(Sprite(\"tool_x_b\", set_toolicons, 3,1,1,1))\n\ncontainer.sprites.Add(Sprite(\"info_a\", set_infoicons, 0,0,1,1))\ncontainer.sprites.Add(Sprite(\"info_b\", set_infoicons, 0,1,1,1))\n\n\nanim = Animation(\"base\")\nanim.body.frames.Add(AnimKeyframe(0, 0, -4, 0))\nanim.back_foot.frames.Add(AnimKeyframe(0, 0, 10, 0))\nanim.front_foot.frames.Add(AnimKeyframe(0, 0, 10, 0))\ncontainer.animations.Add(anim)\n\nanim = Animation(\"idle\")\nanim.back_foot.frames.Add(AnimKeyframe(0, -7, 0, 0))\nanim.front_foot.frames.Add(AnimKeyframe(0, 7, 0, 0))\ncontainer.animations.Add(anim)\n\nanim = Animation(\"inair\")\nanim.back_foot.frames.Add(AnimKeyframe(0, -3, 0, -0.1))\nanim.front_foot.frames.Add(AnimKeyframe(0, 3, 0, -0.1))\ncontainer.animations.Add(anim)\n\nanim = Animation(\"walk\")\nanim.body.frames.Add(AnimKeyframe(0.0, 0, 0, 0))\nanim.body.frames.Add(AnimKeyframe(0.2, 0,-1, 0))\nanim.body.frames.Add(AnimKeyframe(0.4, 0, 0, 0))\nanim.body.frames.Add(AnimKeyframe(0.6, 0, 0, 0))\nanim.body.frames.Add(AnimKeyframe(0.8, 0,-1, 0))\nanim.body.frames.Add(AnimKeyframe(1.0, 0, 0, 0))\n\nanim.back_foot.frames.Add(AnimKeyframe(0.0, 8, 0, 0))\nanim.back_foot.frames.Add(AnimKeyframe(0.2, -8, 0, 0))\nanim.back_foot.frames.Add(AnimKeyframe(0.4,-10,-4, 0.2))\nanim.back_foot.frames.Add(AnimKeyframe(0.6, -8,-8, 0.3))\nanim.back_foot.frames.Add(AnimKeyframe(0.8, 4,-4,-0.2))\nanim.back_foot.frames.Add(AnimKeyframe(1.0, 8, 0, 0))\n\nanim.front_foot.frames.Add(AnimKeyframe(0.0,-10,-4, 0.2))\nanim.front_foot.frames.Add(AnimKeyframe(0.2, -8,-8, 0.3))\nanim.front_foot.frames.Add(AnimKeyframe(0.4, 4,-4,-0.2))\nanim.front_foot.frames.Add(AnimKeyframe(0.6, 8, 0, 0))\nanim.front_foot.frames.Add(AnimKeyframe(0.8, 8, 0, 0))\nanim.front_foot.frames.Add(AnimKeyframe(1.0,-10,-4, 0.2))\ncontainer.animations.Add(anim)\n\nanim = Animation(\"hammer_swing\")\nanim.attach.frames.Add(AnimKeyframe(0.0, 0, 0, -0.10))\nanim.attach.frames.Add(AnimKeyframe(0.3, 0, 0, 0.25))\nanim.attach.frames.Add(AnimKeyframe(0.4, 0, 0, 0.30))\nanim.attach.frames.Add(AnimKeyframe(0.5, 0, 0, 0.25))\nanim.attach.frames.Add(AnimKeyframe(1.0, 0, 0, -0.10))\ncontainer.animations.Add(anim)\n\nanim = Animation(\"ninja_swing\")\nanim.attach.frames.Add(AnimKeyframe(0.00, 0, 0, -0.25))\nanim.attach.frames.Add(AnimKeyframe(0.10, 0, 0, -0.05))\nanim.attach.frames.Add(AnimKeyframe(0.15, 0, 0, 0.35))\nanim.attach.frames.Add(AnimKeyframe(0.42, 0, 0, 0.40))\nanim.attach.frames.Add(AnimKeyframe(0.50, 0, 0, 0.35))\nanim.attach.frames.Add(AnimKeyframe(1.00, 0, 0, -0.25))\ncontainer.animations.Add(anim)\n\nweapon = WeaponSpec(container, \"hammer\")\nweapon.firedelay.Set(125)\nweapon.damage.Set(3)\nweapon.visual_size.Set(96)\nweapon.offsetx.Set(4)\nweapon.offsety.Set(-20)\ncontainer.weapons.hammer.base.Set(weapon)\ncontainer.weapons.id.Add(weapon)\n\nweapon = WeaponSpec(container, \"gun\")\nweapon.firedelay.Set(125)\nweapon.ammoregentime.Set(500)\nweapon.visual_size.Set(64)\nweapon.offsetx.Set(32)\nweapon.offsety.Set(4)\nweapon.muzzleoffsetx.Set(50)\nweapon.muzzleoffsety.Set(6)\ncontainer.weapons.gun.base.Set(weapon)\ncontainer.weapons.id.Add(weapon)\n\nweapon = WeaponSpec(container, \"shotgun\")\nweapon.firedelay.Set(500)\nweapon.visual_size.Set(96)\nweapon.offsetx.Set(24)\nweapon.offsety.Set(-2)\nweapon.muzzleoffsetx.Set(70)\nweapon.muzzleoffsety.Set(6)\ncontainer.weapons.shotgun.base.Set(weapon)\ncontainer.weapons.id.Add(weapon)\n\nweapon = WeaponSpec(container, \"grenade\")\nweapon.firedelay.Set(500) # TODO: fix this\nweapon.visual_size.Set(96)\nweapon.offsetx.Set(24)\nweapon.offsety.Set(-2)\ncontainer.weapons.grenade.base.Set(weapon)\ncontainer.weapons.id.Add(weapon)\n\nweapon = WeaponSpec(container, \"laser\")\nweapon.firedelay.Set(800)\nweapon.visual_size.Set(92)\nweapon.damage.Set(5)\nweapon.offsetx.Set(24)\nweapon.offsety.Set(-2)\ncontainer.weapons.laser.base.Set(weapon)\ncontainer.weapons.id.Add(weapon)\n\nweapon = WeaponSpec(container, \"ninja\")\nweapon.firedelay.Set(800)\nweapon.damage.Set(9)\nweapon.visual_size.Set(96)\nweapon.offsetx.Set(0)\nweapon.offsety.Set(0)\nweapon.muzzleoffsetx.Set(40)\nweapon.muzzleoffsety.Set(-4)\ncontainer.weapons.ninja.base.Set(weapon)\ncontainer.weapons.id.Add(weapon)\n"
  },
  {
    "path": "datasrc/datatypes.py",
    "content": "import sys\n\nGlobalIdCounter = 0\ndef GetID():\n\tglobal GlobalIdCounter\n\tGlobalIdCounter += 1\n\treturn GlobalIdCounter\ndef GetUID():\n\treturn \"x%d\"%GetID()\n\ndef FixCasing(Str):\n\tNewStr = \"\"\n\tNextUpperCase = True\n\tfor c in Str:\n\t\tif NextUpperCase:\n\t\t\tNextUpperCase = False\n\t\t\tNewStr += c.upper()\n\t\telse:\n\t\t\tif c == \"_\":\n\t\t\t\tNextUpperCase = True\n\t\t\telse:\n\t\t\t\tNewStr += c.lower()\n\treturn NewStr\n\ndef FormatName(type, name):\n\tif \"*\" in type:\n\t\treturn \"m_p\" + FixCasing(name)\n\tif \"[]\" in type:\n\t\treturn \"m_a\" + FixCasing(name)\n\treturn \"m_\" + FixCasing(name)\n\nclass BaseType:\n\tdef __init__(self, type_name):\n\t\tself._type_name = type_name\n\t\tself._target_name = \"INVALID\"\n\t\tself._id = GetID() # this is used to remember what order the members have in structures etc\n\n\tdef Identifyer(self): return \"x\"+str(self._id)\n\tdef TargetName(self): return self._target_name\n\tdef TypeName(self): return self._type_name\n\tdef ID(self): return self._id;\n\n\tdef EmitDeclaration(self, name):\n\t\treturn [\"%s %s;\"%(self.TypeName(), FormatName(self.TypeName(), name))]\n\tdef EmitPreDefinition(self, target_name):\n\t\tself._target_name = target_name\n\t\treturn []\n\tdef EmitDefinition(self, name):\n\t\treturn []\n\nclass MemberType:\n\tdef __init__(self, name, var):\n\t\tself.name = name\n\t\tself.var = var\n\nclass Struct(BaseType):\n\tdef __init__(self, type_name):\n\t\tBaseType.__init__(self, type_name)\n\tdef Members(self):\n\t\tdef sorter(a):\n\t\t\treturn a.var.ID()\n\t\tm = []\n\t\tfor name in self.__dict__:\n\t\t\tif name[0] == \"_\":\n\t\t\t\tcontinue\n\t\t\tm += [MemberType(name, self.__dict__[name])]\n\t\ttry:\n\t\t\tm.sort(key = sorter)\n\t\texcept:\n\t\t\tfor v in m:\n\t\t\t\tprint(v.name, v.var)\n\t\t\tsys.exit(-1)\n\t\treturn m\n\n\tdef EmitTypeDeclaration(self, name):\n\t\tlines = []\n\t\tlines += [\"struct \" + self.TypeName()]\n\t\tlines += [\"{\"]\n\t\tfor member in self.Members():\n\t\t\tlines += [\"\\t\"+l for l in member.var.EmitDeclaration(member.name)]\n\t\tlines += [\"};\"]\n\t\treturn lines\n\n\tdef EmitPreDefinition(self, target_name):\n\t\tBaseType.EmitPreDefinition(self, target_name)\n\t\tlines = []\n\t\tfor member in self.Members():\n\t\t\tlines += member.var.EmitPreDefinition(target_name+\".\"+member.name)\n\t\treturn lines\n\tdef EmitDefinition(self, name):\n\t\tlines = [\"/* %s */ {\" % self.TargetName()]\n\t\tfor member in self.Members():\n\t\t\tlines += [\"\\t\" + \" \".join(member.var.EmitDefinition(\"\")) + \",\"]\n\t\tlines += [\"}\"]\n\t\treturn lines\n\nclass Array(BaseType):\n\tdef __init__(self, type):\n\t\tBaseType.__init__(self, type.TypeName())\n\t\tself.type = type\n\t\tself.items = []\n\tdef Add(self, instance):\n\t\tif instance.TypeName() != self.type.TypeName():\n\t\t\terror(\"bah\")\n\t\tself.items += [instance]\n\tdef EmitDeclaration(self, name):\n\t\treturn [\"int m_Num%s;\"%(FixCasing(name)),\n\t\t\t\"%s *%s;\"%(self.TypeName(), FormatName(\"[]\", name))]\n\tdef EmitPreDefinition(self, target_name):\n\t\tBaseType.EmitPreDefinition(self, target_name)\n\n\t\tlines = []\n\t\ti = 0\n\t\tfor item in self.items:\n\t\t\tlines += item.EmitPreDefinition(\"%s[%d]\"%(self.Identifyer(), i))\n\t\t\ti += 1\n\n\t\tif len(self.items):\n\t\t\tlines += [\"static %s %s[] = {\"%(self.TypeName(), self.Identifyer())]\n\t\t\tfor item in self.items:\n\t\t\t\titemlines = item.EmitDefinition(\"\")\n\t\t\t\tlines += [\"\\t\" + \" \".join(itemlines).replace(\"\\t\", \" \") + \",\"]\n\t\t\tlines += [\"};\"]\n\t\telse:\n\t\t\tlines += [\"static %s *%s = 0;\"%(self.TypeName(), self.Identifyer())]\n\n\t\treturn lines\n\tdef EmitDefinition(self, name):\n\t\treturn [str(len(self.items))+\",\"+self.Identifyer()]\n\n# Basic Types\n\nclass Int(BaseType):\n\tdef __init__(self, value):\n\t\tBaseType.__init__(self, \"int\")\n\t\tself.value = value\n\tdef Set(self, value):\n\t\tself.value = value\n\tdef EmitDefinition(self, name):\n\t\treturn [\"%d\"%self.value]\n\t\t#return [\"%d /* %s */\"%(self.value, self._target_name)]\n\nclass Float(BaseType):\n\tdef __init__(self, value):\n\t\tBaseType.__init__(self, \"float\")\n\t\tself.value = value\n\tdef Set(self, value):\n\t\tself.value = value\n\tdef EmitDefinition(self, name):\n\t\treturn [\"%f\"%self.value]\n\t\t#return [\"%d /* %s */\"%(self.value, self._target_name)]\n\nclass String(BaseType):\n\tdef __init__(self, value):\n\t\tBaseType.__init__(self, \"const char*\")\n\t\tself.value = value\n\tdef Set(self, value):\n\t\tself.value = value\n\tdef EmitDefinition(self, name):\n\t\treturn ['\"'+self.value+'\"']\n\nclass Pointer(BaseType):\n\tdef __init__(self, type, target):\n\t\tBaseType.__init__(self, \"%s*\"%type().TypeName())\n\t\tself.target = target\n\tdef Set(self, target):\n\t\tself.target = target\n\tdef EmitDefinition(self, name):\n\t\treturn [\"&\"+self.target.TargetName()]\n\nclass TextureHandle(BaseType):\n\tdef __init__(self):\n\t\tBaseType.__init__(self, \"IGraphics::CTextureHandle\")\n\tdef EmitDefinition(self, name):\n\t\treturn [\"IGraphics::CTextureHandle()\"]\t\n\nclass SampleHandle(BaseType):\n\tdef __init__(self):\n\t\tBaseType.__init__(self, \"ISound::CSampleHandle\")\n\tdef EmitDefinition(self, name):\n\t\treturn [\"ISound::CSampleHandle()\"]\t\n\n# helper functions\n\ndef EmitTypeDeclaration(root):\n\tfor l in root().EmitTypeDeclaration(\"\"):\n\t\tprint(l)\n\ndef EmitDefinition(root, name):\n\tfor l in root.EmitPreDefinition(name):\n\t\tprint(l)\n\tprint(\"%s %s = \" % (root.TypeName(), name))\n\tfor l in root.EmitDefinition(name):\n\t\tprint(l)\n\tprint(\";\")\n\n# Network stuff after this\n\nclass Object:\n\tpass\n\nclass Enum:\n\tdef __init__(self, name, values):\n\t\tself.name = name\n\t\tself.values = values\n\nclass Flags:\n\tdef __init__(self, name, values):\n\t\tself.name = name\n\t\tself.values = values\n\nclass NetObject:\n\tdef __init__(self, name, variables):\n\t\tl = name.split(\":\")\n\t\tself.name = l[0]\n\t\tself.base = \"\"\n\t\tif len(l) > 1:\n\t\t\tself.base = l[1]\n\t\tself.base_struct_name = \"CNetObj_%s\" % self.base\n\t\tself.struct_name = \"CNetObj_%s\" % self.name\n\t\tself.enum_name = \"NETOBJTYPE_%s\" % self.name.upper()\n\t\tself.variables = variables\n\tdef emit_declaration(self):\n\t\tif self.base:\n\t\t\tlines = [\"struct %s : public %s\"%(self.struct_name,self.base_struct_name), \"{\"]\n\t\telse:\n\t\t\tlines = [\"struct %s\"%self.struct_name, \"{\"]\n\t\tfor v in self.variables:\n\t\t\tlines += [\"\\t\"+line for line in v.emit_declaration()]\n\t\tlines += [\"};\"]\n\t\treturn lines\n\tdef emit_validate(self):\n\t\tlines = [\"case %s:\" % self.enum_name]\n\t\tlines += [\"{\"]\n\t\tlines += [\"\\t%s *pObj = (%s *)pData;\"%(self.struct_name, self.struct_name)]\n\t\tlines += [\"\\tif(sizeof(*pObj) != Size) return -1;\"]\n\t\tfor v in self.variables:\n\t\t\tlines += [\"\\t\"+line for line in v.emit_validate()]\n\t\tlines += [\"\\treturn 0;\"]\n\t\tlines += [\"}\"]\n\t\treturn lines\n\n\nclass NetEvent(NetObject):\n\tdef __init__(self, name, variables):\n\t\tNetObject.__init__(self, name, variables)\n\t\tself.base_struct_name = \"CNetEvent_%s\" % self.base\n\t\tself.struct_name = \"CNetEvent_%s\" % self.name\n\t\tself.enum_name = \"NETEVENTTYPE_%s\" % self.name.upper()\n\nclass NetMessage(NetObject):\n\tdef __init__(self, name, variables):\n\t\tNetObject.__init__(self, name, variables)\n\t\tself.base_struct_name = \"CNetMsg_%s\" % self.base\n\t\tself.struct_name = \"CNetMsg_%s\" % self.name\n\t\tself.enum_name = \"NETMSGTYPE_%s\" % self.name.upper()\n\tdef emit_unpack(self):\n\t\tlines = []\n\t\tlines += [\"case %s:\" % self.enum_name]\n\t\tlines += [\"{\"]\n\t\tlines += [\"\\t%s *pMsg = (%s *)m_aMsgData;\" % (self.struct_name, self.struct_name)]\n\t\tlines += [\"\\t(void)pMsg;\"]\n\t\tfor v in self.variables:\n\t\t\tlines += [\"\\t\"+line for line in v.emit_unpack()]\n\t\tfor v in self.variables:\n\t\t\tlines += [\"\\t\"+line for line in v.emit_unpack_check()]\n\t\tlines += [\"} break;\"]\n\t\treturn lines\n\tdef emit_declaration(self):\n\t\textra = []\n\t\textra += [\"\\tint MsgID() const { return %s; }\" % self.enum_name]\n\t\textra += [\"\\t\"]\n\t\textra += [\"\\tbool Pack(CMsgPacker *pPacker)\"]\n\t\textra += [\"\\t{\"]\n\t\t#extra += [\"\\t\\tmsg_pack_start(%s, flags);\"%self.enum_name]\n\t\tfor v in self.variables:\n\t\t\textra += [\"\\t\\t\"+line for line in v.emit_pack()]\n\t\textra += [\"\\t\\treturn pPacker->Error() != 0;\"]\n\t\textra += [\"\\t}\"]\n\n\n\t\tlines = NetObject.emit_declaration(self)\n\t\tlines = lines[:-1] + extra + lines[-1:]\n\t\treturn lines\n\n\nclass NetVariable:\n\tdef __init__(self, name):\n\t\tself.name = name\n\tdef emit_declaration(self):\n\t\treturn []\n\tdef emit_validate(self):\n\t\treturn []\n\tdef emit_pack(self):\n\t\treturn []\n\tdef emit_unpack(self):\n\t\treturn []\n\tdef emit_unpack_check(self):\n\t\treturn []\n\nclass NetString(NetVariable):\n\tdef emit_declaration(self):\n\t\treturn [\"const char *%s;\"%self.name]\n\tdef emit_unpack(self):\n\t\treturn [\"pMsg->%s = pUnpacker->GetString();\" % self.name]\n\tdef emit_pack(self):\n\t\treturn [\"pPacker->AddString(%s, -1);\" % self.name]\n\nclass NetStringStrict(NetVariable):\n\tdef emit_declaration(self):\n\t\treturn [\"const char *%s;\"%self.name]\n\tdef emit_unpack(self):\n\t\treturn [\"pMsg->%s = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);\" % self.name]\n\tdef emit_pack(self):\n\t\treturn [\"pPacker->AddString(%s, -1);\" % self.name]\n\nclass NetIntAny(NetVariable):\n\tdef emit_declaration(self):\n\t\treturn [\"int %s;\"%self.name]\n\tdef emit_unpack(self):\n\t\treturn [\"pMsg->%s = pUnpacker->GetInt();\" % self.name]\n\tdef emit_pack(self):\n\t\treturn [\"pPacker->AddInt(%s);\" % self.name]\n\nclass NetIntRange(NetIntAny):\n\tdef __init__(self, name, min, max):\n\t\tNetIntAny.__init__(self,name)\n\t\tself.min = str(min)\n\t\tself.max = str(max)\n\tdef emit_validate(self):\n\t\treturn [\"ClampInt(\\\"%s\\\", pObj->%s, %s, %s);\"%(self.name,self.name, self.min, self.max)]\n\tdef emit_unpack_check(self):\n\t\treturn [\"if(pMsg->%s < %s || pMsg->%s > %s) { m_pMsgFailedOn = \\\"%s\\\"; break; }\" % (self.name, self.min, self.name, self.max, self.name)]\n\nclass NetEnum(NetIntRange):\n\tdef __init__(self, name, enum):\n\t\tNetIntRange.__init__(self, name, 0, len(enum.values))\n\nclass NetFlag(NetIntAny):\n\tdef __init__(self, name, flag):\n\t\tNetIntAny.__init__(self, name)\n\t\tif len(flag.values) > 0:\n\t\t\tself.mask = \"%s_%s\" % (flag.name, flag.values[0])\n\t\t\tfor i in flag.values[1:]:\n\t\t\t\tself.mask += \"|%s_%s\" % (flag.name, i)\n\t\telse:\n\t\t\tself.mask = \"0\"\n\tdef emit_validate(self):\n\t\treturn [\"ClampFlag(\\\"%s\\\", pObj->%s, %s);\"%(self.name, self.name, self.mask)]\n\tdef emit_unpack_check(self):\n\t\treturn [\"if((pMsg->%s & (%s)) != pMsg->%s) { m_pMsgFailedOn = \\\"%s\\\"; break; }\" % (self.name, self.mask, self.name, self.name)]\n\nclass NetBool(NetIntRange):\n\tdef __init__(self, name):\n\t\tNetIntRange.__init__(self,name,0,1)\n\nclass NetTick(NetIntRange):\n\tdef __init__(self, name):\n\t\tNetIntRange.__init__(self,name,0,'max_int')\n\nclass NetArray(NetVariable):\n\tdef __init__(self, var, size):\n\t\tself.base_name = var.name\n\t\tself.var = var\n\t\tself.size = size\n\t\tself.name = self.base_name + \"[%d]\"%self.size\n\tdef emit_declaration(self):\n\t\tself.var.name = self.name\n\t\treturn self.var.emit_declaration()\n\tdef emit_validate(self):\n\t\tlines = []\n\t\tfor i in range(self.size):\n\t\t\tself.var.name = self.base_name + \"[%d]\"%i\n\t\t\tlines += self.var.emit_validate()\n\t\treturn lines\n\tdef emit_unpack(self):\n\t\tlines = []\n\t\tfor i in range(self.size):\n\t\t\tself.var.name = self.base_name + \"[%d]\"%i\n\t\t\tlines += self.var.emit_unpack()\n\t\treturn lines\n\tdef emit_pack(self):\n\t\tlines = []\n\t\tfor i in range(self.size):\n\t\t\tself.var.name = self.base_name + \"[%d]\"%i\n\t\t\tlines += self.var.emit_pack()\n\t\treturn lines\n\tdef emit_unpack_check(self):\n\t\tlines = []\n\t\tfor i in range(self.size):\n\t\t\tself.var.name = self.base_name + \"[%d]\"%i\n\t\t\tlines += self.var.emit_unpack_check()\n\t\treturn lines\n"
  },
  {
    "path": "datasrc/network.py",
    "content": "from datatypes import *\n\nPickups = Enum(\"PICKUP\", [\"HEALTH\", \"ARMOR\", \"GRENADE\", \"SHOTGUN\", \"LASER\", \"NINJA\"])\nEmotes = Enum(\"EMOTE\", [\"NORMAL\", \"PAIN\", \"HAPPY\", \"SURPRISE\", \"ANGRY\", \"BLINK\"])\nEmoticons = Enum(\"EMOTICON\", [\"OOP\", \"EXCLAMATION\", \"HEARTS\", \"DROP\", \"DOTDOT\", \"MUSIC\", \"SORRY\", \"GHOST\", \"SUSHI\", \"SPLATTEE\", \"DEVILTEE\", \"ZOMG\", \"ZZZ\", \"WTF\", \"EYES\", \"QUESTION\"])\nVotes = Enum(\"VOTE\", [\"UNKNOWN\", \"START_OP\", \"START_KICK\", \"START_SPEC\", \"END_ABORT\", \"END_PASS\", \"END_FAIL\"])\n\nPlayerFlags = Flags(\"PLAYERFLAG\", [\"ADMIN\", \"CHATTING\", \"SCOREBOARD\", \"READY\", \"DEAD\", \"WATCHING\"])\nGameFlags = Flags(\"GAMEFLAG\", [\"TEAMS\", \"FLAGS\", \"SURVIVAL\"])\nGameStateFlags = Flags(\"GAMESTATEFLAG\", [\"WARMUP\", \"SUDDENDEATH\", \"ROUNDOVER\", \"GAMEOVER\", \"PAUSED\", \"STARTCOUNTDOWN\"])\nCoreEventFlags = Flags(\"COREEVENTFLAG\", [\"GROUND_JUMP\", \"AIR_JUMP\", \"HOOK_ATTACH_PLAYER\", \"HOOK_ATTACH_GROUND\", \"HOOK_HIT_NOHOOK\"])\n\nGameMsgIDs = Enum(\"GAMEMSG\", [\"TEAM_SWAP\", \"SPEC_INVALIDID\", \"TEAM_SHUFFLE\", \"TEAM_BALANCE\", \"CTF_DROP\", \"CTF_RETURN\",\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\"TEAM_ALL\", \"TEAM_BALANCE_VICTIM\", \"CTF_GRAB\",\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\"CTF_CAPTURE\"])\n\n\nRawHeader = '''\n\n#include <engine/message.h>\n\nenum\n{\n\tINPUT_STATE_MASK=0x3f\n};\n\nenum\n{\n\tTEAM_SPECTATORS=-1,\n\tTEAM_RED,\n\tTEAM_BLUE,\n\tNUM_TEAMS,\n\n\tFLAG_MISSING=-3,\n\tFLAG_ATSTAND,\n\tFLAG_TAKEN,\n\n\tSPEC_FREEVIEW=-1,\n};\n'''\n\nRawSource = '''\n#include <engine/message.h>\n#include \"protocol.h\"\n'''\n\nEnums = [\n\tPickups,\n\tEmotes,\n\tEmoticons,\n\tVotes,\n\tGameMsgIDs,\n]\n\nFlags = [\n\tPlayerFlags,\n\tGameFlags,\n\tGameStateFlags,\n\tCoreEventFlags,\n]\n\nObjects = [\n\n\tNetObject(\"PlayerInput\", [\n\t\tNetIntRange(\"m_Direction\", -1, 1),\n\t\tNetIntAny(\"m_TargetX\"),\n\t\tNetIntAny(\"m_TargetY\"),\n\n\t\tNetBool(\"m_Jump\"),\n\t\tNetIntAny(\"m_Fire\"),\n\t\tNetBool(\"m_Hook\"),\n\n\t\tNetFlag(\"m_PlayerFlags\", PlayerFlags),\n\n\t\tNetIntRange(\"m_WantedWeapon\", 0, 'NUM_WEAPONS-1'),\n\t\tNetIntAny(\"m_NextWeapon\"),\n\t\tNetIntAny(\"m_PrevWeapon\"),\n\t]),\n\n\tNetObject(\"Projectile\", [\n\t\tNetIntAny(\"m_X\"),\n\t\tNetIntAny(\"m_Y\"),\n\t\tNetIntAny(\"m_VelX\"),\n\t\tNetIntAny(\"m_VelY\"),\n\n\t\tNetIntRange(\"m_Type\", 0, 'NUM_WEAPONS-1'),\n\t\tNetTick(\"m_StartTick\"),\n\t]),\n\n\tNetObject(\"Laser\", [\n\t\tNetIntAny(\"m_X\"),\n\t\tNetIntAny(\"m_Y\"),\n\t\tNetIntAny(\"m_FromX\"),\n\t\tNetIntAny(\"m_FromY\"),\n\n\t\tNetTick(\"m_StartTick\"),\n\t]),\n\n\tNetObject(\"Pickup\", [\n\t\tNetIntAny(\"m_X\"),\n\t\tNetIntAny(\"m_Y\"),\n\n\t\tNetEnum(\"m_Type\", Pickups),\n\t]),\n\n\tNetObject(\"Flag\", [\n\t\tNetIntAny(\"m_X\"),\n\t\tNetIntAny(\"m_Y\"),\n\n\t\tNetIntRange(\"m_Team\", 'TEAM_RED', 'TEAM_BLUE')\n\t]),\n\n\tNetObject(\"GameData\", [\n\t\tNetTick(\"m_GameStartTick\"),\n\t\tNetFlag(\"m_GameStateFlags\", GameStateFlags),\n\t\tNetTick(\"m_GameStateEndTick\"),\n\t]),\n\n\tNetObject(\"GameDataTeam\", [\n\t\tNetIntAny(\"m_TeamscoreRed\"),\n\t\tNetIntAny(\"m_TeamscoreBlue\"),\n\t]),\n\n\tNetObject(\"GameDataFlag\", [\n\t\tNetIntRange(\"m_FlagCarrierRed\", 'FLAG_MISSING', 'MAX_CLIENTS-1'),\n\t\tNetIntRange(\"m_FlagCarrierBlue\", 'FLAG_MISSING', 'MAX_CLIENTS-1'),\n\t\tNetTick(\"m_FlagDropTickRed\"),\n\t\tNetTick(\"m_FlagDropTickBlue\"),\n\t]),\n\n\tNetObject(\"CharacterCore\", [\n\t\tNetTick(\"m_Tick\"),\n\t\tNetIntAny(\"m_X\"),\n\t\tNetIntAny(\"m_Y\"),\n\t\tNetIntAny(\"m_VelX\"),\n\t\tNetIntAny(\"m_VelY\"),\n\n\t\tNetIntAny(\"m_Angle\"),\n\t\tNetIntRange(\"m_Direction\", -1, 1),\n\n\t\tNetIntRange(\"m_Jumped\", 0, 3),\n\t\tNetIntRange(\"m_HookedPlayer\", 0, 'MAX_CLIENTS-1'),\n\t\tNetIntRange(\"m_HookState\", -1, 5),\n\t\tNetTick(\"m_HookTick\"),\n\n\t\tNetIntAny(\"m_HookX\"),\n\t\tNetIntAny(\"m_HookY\"),\n\t]),\n\n\tNetObject(\"Character:CharacterCore\", [\n\t\tNetIntRange(\"m_Health\", 0, 10),\n\t\tNetIntRange(\"m_Armor\", 0, 10),\n\t\tNetIntAny(\"m_AmmoCount\"),\n\t\tNetIntRange(\"m_Weapon\", 0, 'NUM_WEAPONS-1'),\n\t\tNetEnum(\"m_Emote\", Emotes),\n\t\tNetTick(\"m_AttackTick\"),\n\t\tNetFlag(\"m_TriggeredEvents\", CoreEventFlags),\n\t]),\n\n\tNetObject(\"PlayerInfo\", [\n\t\tNetFlag(\"m_PlayerFlags\", PlayerFlags),\n\t\tNetIntAny(\"m_Score\"),\n\t\tNetIntAny(\"m_Latency\"),\n\t]),\n\n\tNetObject(\"SpectatorInfo\", [\n\t\tNetIntRange(\"m_SpectatorID\", 'SPEC_FREEVIEW', 'MAX_CLIENTS-1'),\n\t\tNetIntAny(\"m_X\"),\n\t\tNetIntAny(\"m_Y\"),\n\t]),\n\n\t## Demo\n\n\tNetObject(\"De_ClientInfo\", [\n\t\tNetBool(\"m_Local\"),\n\t\tNetIntRange(\"m_Team\", 'TEAM_SPECTATORS', 'TEAM_BLUE'),\n\n\t\tNetArray(NetIntAny(\"m_aName\"), 4),\n\t\tNetArray(NetIntAny(\"m_aClan\"), 3),\n\n\t\tNetIntAny(\"m_Country\"),\n\n\t\tNetArray(NetArray(NetIntAny(\"m_aaSkinPartNames\"), 6), 6),\n\t\tNetArray(NetBool(\"m_aUseCustomColors\"), 6),\n\t\tNetArray(NetIntAny(\"m_aSkinPartColors\"), 6),\n\t]),\n\n\tNetObject(\"De_GameInfo\", [\n\t\tNetFlag(\"m_GameFlags\", GameFlags),\n\t\t\n\t\tNetIntRange(\"m_ScoreLimit\", 0, 'max_int'),\n\t\tNetIntRange(\"m_TimeLimit\", 0, 'max_int'),\n\n\t\tNetIntRange(\"m_MatchNum\", 0, 'max_int'),\n\t\tNetIntRange(\"m_MatchCurrent\", 0, 'max_int'),\n\t]),\n\n\tNetObject(\"De_TuneParams\", [\n\t\t# todo: should be done differently\n\t\tNetArray(NetIntAny(\"m_aTuneParams\"), 33),\n\t]),\n\n\t## Events\n\n\tNetEvent(\"Common\", [\n\t\tNetIntAny(\"m_X\"),\n\t\tNetIntAny(\"m_Y\"),\n\t]),\n\n\n\tNetEvent(\"Explosion:Common\", []),\n\tNetEvent(\"Spawn:Common\", []),\n\tNetEvent(\"HammerHit:Common\", []),\n\n\tNetEvent(\"Death:Common\", [\n\t\tNetIntRange(\"m_ClientID\", 0, 'MAX_CLIENTS-1'),\n\t]),\n\n\tNetEvent(\"SoundWorld:Common\", [\n\t\tNetIntRange(\"m_SoundID\", 0, 'NUM_SOUNDS-1'),\n\t]),\n\n\tNetEvent(\"DamageInd:Common\", [\n\t\tNetIntAny(\"m_Angle\"),\n\t]),\n]\n\nMessages = [\n\n\t### Server messages\n\tNetMessage(\"Sv_Motd\", [\n\t\tNetString(\"m_pMessage\"),\n\t]),\n\n\tNetMessage(\"Sv_Chat\", [\n\t\tNetIntRange(\"m_Team\", 'TEAM_SPECTATORS', 'TEAM_BLUE'),\n\t\tNetIntRange(\"m_ClientID\", -1, 'MAX_CLIENTS-1'),\n\t\tNetString(\"m_pMessage\"),\n\t]),\n\n\tNetMessage(\"Sv_Team\", [\n\t\tNetIntRange(\"m_ClientID\", -1, 'MAX_CLIENTS-1'),\n\t\tNetIntRange(\"m_Team\", 'TEAM_SPECTATORS', 'TEAM_BLUE'),\n\t\tNetBool(\"m_Silent\"),\n\t\tNetTick(\"m_CooldownTick\"),\n\t]),\n\n\tNetMessage(\"Sv_KillMsg\", [\n\t\tNetIntRange(\"m_Killer\", 0, 'MAX_CLIENTS-1'),\n\t\tNetIntRange(\"m_Victim\", 0, 'MAX_CLIENTS-1'),\n\t\tNetIntRange(\"m_Weapon\", -3, 'NUM_WEAPONS-1'),\n\t\tNetIntAny(\"m_ModeSpecial\"),\n\t]),\n\n\tNetMessage(\"Sv_TuneParams\", []),\n\tNetMessage(\"Sv_ExtraProjectile\", []),\n\tNetMessage(\"Sv_ReadyToEnter\", []),\n\n\tNetMessage(\"Sv_WeaponPickup\", [\n\t\tNetIntRange(\"m_Weapon\", 0, 'NUM_WEAPONS-1'),\n\t]),\n\n\tNetMessage(\"Sv_Emoticon\", [\n\t\tNetIntRange(\"m_ClientID\", 0, 'MAX_CLIENTS-1'),\n\t\tNetEnum(\"m_Emoticon\", Emoticons),\n\t]),\n\n\tNetMessage(\"Sv_VoteClearOptions\", []),\n\n\tNetMessage(\"Sv_VoteOptionListAdd\", []),\n\n\tNetMessage(\"Sv_VoteOptionAdd\", [\n\t\tNetStringStrict(\"m_pDescription\"),\n\t]),\n\n\tNetMessage(\"Sv_VoteOptionRemove\", [\n\t\tNetStringStrict(\"m_pDescription\"),\n\t]),\n\n\tNetMessage(\"Sv_VoteSet\", [\n\t\tNetIntRange(\"m_ClientID\", -1, 'MAX_CLIENTS-1'),\n\t\tNetEnum(\"m_Type\", Votes),\n\t\tNetIntRange(\"m_Timeout\", 0, 60),\n\t\tNetStringStrict(\"m_pDescription\"),\n\t\tNetStringStrict(\"m_pReason\"),\n\t]),\n\n\tNetMessage(\"Sv_VoteStatus\", [\n\t\tNetIntRange(\"m_Yes\", 0, 'MAX_CLIENTS'),\n\t\tNetIntRange(\"m_No\", 0, 'MAX_CLIENTS'),\n\t\tNetIntRange(\"m_Pass\", 0, 'MAX_CLIENTS'),\n\t\tNetIntRange(\"m_Total\", 0, 'MAX_CLIENTS'),\n\t]),\n\n\tNetMessage(\"Sv_ServerSettings\", [\n\t\tNetBool(\"m_KickVote\"),\n\t\tNetIntRange(\"m_KickMin\", 0, 'MAX_CLIENTS'),\n\t\tNetBool(\"m_SpecVote\"),\n\t\tNetBool(\"m_TeamLock\"),\n\t\tNetBool(\"m_TeamBalance\"),\n\t\tNetIntRange(\"m_PlayerSlots\", 0, 'MAX_CLIENTS'),\n\t]),\n\n\tNetMessage(\"Sv_ClientInfo\", [\n\t\tNetIntRange(\"m_ClientID\", 0, 'MAX_CLIENTS-1'),\n\t\tNetBool(\"m_Local\"),\n\t\tNetIntRange(\"m_Team\", 'TEAM_SPECTATORS', 'TEAM_BLUE'),\n\t\tNetStringStrict(\"m_pName\"),\n\t\tNetStringStrict(\"m_pClan\"),\n\t\tNetIntAny(\"m_Country\"),\n\t\tNetArray(NetStringStrict(\"m_apSkinPartNames\"), 6),\n\t\tNetArray(NetBool(\"m_aUseCustomColors\"), 6),\n\t\tNetArray(NetIntAny(\"m_aSkinPartColors\"), 6),\n\t]),\n\n\tNetMessage(\"Sv_GameInfo\", [\n\t\tNetFlag(\"m_GameFlags\", GameFlags),\n\t\t\n\t\tNetIntRange(\"m_ScoreLimit\", 0, 'max_int'),\n\t\tNetIntRange(\"m_TimeLimit\", 0, 'max_int'),\n\n\t\tNetIntRange(\"m_MatchNum\", 0, 'max_int'),\n\t\tNetIntRange(\"m_MatchCurrent\", 0, 'max_int'),\n\t]),\n\n\tNetMessage(\"Sv_ClientDrop\", [\n\t\tNetIntRange(\"m_ClientID\", 0, 'MAX_CLIENTS-1'),\n\t\tNetStringStrict(\"m_pReason\"),\n\t]),\n\n\tNetMessage(\"Sv_GameMsg\", []),\n\n\t## Demo messages\n\tNetMessage(\"De_ClientEnter\", [\n\t\tNetStringStrict(\"m_pName\"),\n\t\tNetIntRange(\"m_Team\", 'TEAM_SPECTATORS', 'TEAM_BLUE'),\n\t]),\n\n\tNetMessage(\"De_ClientLeave\", [\n\t\tNetStringStrict(\"m_pName\"),\n\t\tNetStringStrict(\"m_pReason\"),\n\t]),\n\n\t### Client messages\n\tNetMessage(\"Cl_Say\", [\n\t\tNetBool(\"m_Team\"),\n\t\tNetString(\"m_pMessage\"),\n\t]),\n\n\tNetMessage(\"Cl_SetTeam\", [\n\t\tNetIntRange(\"m_Team\", 'TEAM_SPECTATORS', 'TEAM_BLUE'),\n\t]),\n\n\tNetMessage(\"Cl_SetSpectatorMode\", [\n\t\tNetIntRange(\"m_SpectatorID\", 'SPEC_FREEVIEW', 'MAX_CLIENTS-1'),\n\t]),\n\n\tNetMessage(\"Cl_StartInfo\", [\n\t\tNetStringStrict(\"m_pName\"),\n\t\tNetStringStrict(\"m_pClan\"),\n\t\tNetIntAny(\"m_Country\"),\n\t\tNetArray(NetStringStrict(\"m_apSkinPartNames\"), 6),\n\t\tNetArray(NetBool(\"m_aUseCustomColors\"), 6),\n\t\tNetArray(NetIntAny(\"m_aSkinPartColors\"), 6),\n\t]),\n\n\tNetMessage(\"Cl_Kill\", []),\n\n\tNetMessage(\"Cl_ReadyChange\", []),\n\n\tNetMessage(\"Cl_Emoticon\", [\n\t\tNetEnum(\"m_Emoticon\", Emoticons),\n\t]),\n\n\tNetMessage(\"Cl_Vote\", [\n\t\tNetIntRange(\"m_Vote\", -1, 1),\n\t]),\n\n\tNetMessage(\"Cl_CallVote\", [\n\t\tNetStringStrict(\"m_Type\"),\n\t\tNetStringStrict(\"m_Value\"),\n\t\tNetStringStrict(\"m_Reason\"),\n\t\tNetBool(\"m_Force\"),\n\t]),\n]\n"
  },
  {
    "path": "license.txt",
    "content": "Copyright (C) 2007-2013 Magnus Auvinen\n\nThis software is provided 'as-is', without any express or implied\nwarranty.  In no event will the authors be held liable for any damages\narising from the use of this software.\n\nPermission is granted to anyone to use this software for any purpose,\nincluding commercial applications, and to alter it and redistribute it\nfreely, subject to the following restrictions:\n\n1. The origin of this software must not be misrepresented; you must not\n  claim that you wrote the original software. If you use this software\n  in a product, an acknowledgment in the product documentation would be\n  appreciated but is not required.\n2. Altered source versions must be plainly marked as such, and must not be\n  misrepresented as being the original software.\n3. This notice may not be removed or altered from any source distribution.\n\n------------------------------------------------------------------------\n\nAll content under 'data' except the font (which has its own license) is\nreleased under CC-BY-SA 3.0 (http://creativecommons.org/licenses/by-sa/3.0/).\n\n------------------------------------------------------------------------\n\nIMPORTANT NOTE! The source under src/engine/external are stripped\nlibraries with their own licenses. Mostly BSD or zlib/libpng license but\ncheck the individual libraries.\n\n------------------------------------------------------------------------\n\nWith that being said, contact us if there is anything you want to do\nthat the license does not permit.\n"
  },
  {
    "path": "other/config_directory.bat",
    "content": "@start explorer %APPDATA%\\Teeworlds\n"
  },
  {
    "path": "other/freetype/VERSION",
    "content": "2.4.8\n"
  },
  {
    "path": "other/freetype/freetype.lua",
    "content": "FreeType = {\n\tbasepath = PathDir(ModuleFilename()),\n\t\n\tOptFind = function (name, required)\t\n\t\tlocal check = function(option, settings)\n\t\t\toption.value = false\n\t\t\toption.use_ftconfig = false\n\t\t\toption.use_winlib = 0\n\t\t\toption.lib_path = nil\n\t\t\t\n\t\t\tif ExecuteSilent(\"freetype-config\") > 0 and ExecuteSilent(\"freetype-config --cflags\") == 0 then\n\t\t\t\toption.value = true\n\t\t\t\toption.use_ftconfig = true\n\t\t\tend\n\t\t\t\t\n\t\t\tif platform == \"win32\" then\n\t\t\t\toption.value = true\n\t\t\t\toption.use_winlib = 32\n\t\t\telseif platform == \"win64\" then\n\t\t\t\toption.value = true\n\t\t\t\toption.use_winlib = 64\n\t\t\tend\n\t\tend\n\t\t\n\t\tlocal apply = function(option, settings)\n\t\t\t-- include path\n\t\t\tsettings.cc.includes:Add(FreeType.basepath .. \"/include\")\n\t\t\t\n\t\t\tif option.use_ftconfig == true then\n\t\t\t\tsettings.cc.flags:Add(\"`freetype-config --cflags`\")\n\t\t\t\tsettings.link.flags:Add(\"`freetype-config --libs`\")\n\t\t\t\t\n\t\t\telseif option.use_winlib > 0 then\n\t\t\t\tif option.use_winlib == 32 then\n\t\t\t\t\tsettings.link.libpath:Add(FreeType.basepath .. \"/lib32\")\n\t\t\t\telse\n\t\t\t\t\tsettings.link.libpath:Add(FreeType.basepath .. \"/lib64\")\n\t\t\t\tend\n\t\t\t\tsettings.link.libs:Add(\"freetype\")\n\t\t\tend\n\t\tend\n\t\t\n\t\tlocal save = function(option, output)\n\t\t\toutput:option(option, \"value\")\n\t\t\toutput:option(option, \"use_ftconfig\")\n\t\t\toutput:option(option, \"use_winlib\")\n\t\tend\n\t\t\n\t\tlocal display = function(option)\n\t\t\tif option.value == true then\n\t\t\t\tif option.use_ftconfig == true then return \"using freetype-config\" end\n\t\t\t\tif option.use_winlib == 32 then return \"using supplied win32 libraries\" end\n\t\t\t\tif option.use_winlib == 64 then return \"using supplied win64 libraries\" end\n\t\t\t\treturn \"using unknown method\"\n\t\t\telse\n\t\t\t\tif option.required then\n\t\t\t\t\treturn \"not found (required)\"\n\t\t\t\telse\n\t\t\t\t\treturn \"not found (optional)\"\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t\n\t\tlocal o = MakeOption(name, 0, check, save, display)\n\t\to.Apply = apply\n\t\to.include_path = nil\n\t\to.lib_path = nil\n\t\to.required = required\n\t\treturn o\n\tend\n}\n"
  },
  {
    "path": "other/freetype/include/freetype/config/ftconfig.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftconfig.h                                                             */\r\n/*                                                                         */\r\n/*    ANSI-specific configuration file (specification only).               */\r\n/*                                                                         */\r\n/*  Copyright 1996-2004, 2006-2008, 2010-2011 by                           */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* This header file contains a number of macro definitions that are used */\r\n  /* by the rest of the engine.  Most of the macros here are automatically */\r\n  /* determined at compile time, and you should not need to change it to   */\r\n  /* port FreeType, except to compile the library with a non-ANSI          */\r\n  /* compiler.                                                             */\r\n  /*                                                                       */\r\n  /* Note however that if some specific modifications are needed, we       */\r\n  /* advise you to place a modified copy in your build directory.          */\r\n  /*                                                                       */\r\n  /* The build directory is usually `freetype/builds/<system>', and        */\r\n  /* contains system-specific files that are always included first when    */\r\n  /* building the library.                                                 */\r\n  /*                                                                       */\r\n  /* This ANSI version should stay in `include/freetype/config'.           */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n#ifndef __FTCONFIG_H__\r\n#define __FTCONFIG_H__\r\n\r\n#include <ft2build.h>\r\n#include FT_CONFIG_OPTIONS_H\r\n#include FT_CONFIG_STANDARD_LIBRARY_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /*               PLATFORM-SPECIFIC CONFIGURATION MACROS                  */\r\n  /*                                                                       */\r\n  /* These macros can be toggled to suit a specific system.  The current   */\r\n  /* ones are defaults used to compile FreeType in an ANSI C environment   */\r\n  /* (16bit compilers are also supported).  Copy this file to your own     */\r\n  /* `freetype/builds/<system>' directory, and edit it to port the engine. */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /* There are systems (like the Texas Instruments 'C54x) where a `char' */\r\n  /* has 16 bits.  ANSI C says that sizeof(char) is always 1.  Since an  */\r\n  /* `int' has 16 bits also for this system, sizeof(int) gives 1 which   */\r\n  /* is probably unexpected.                                             */\r\n  /*                                                                     */\r\n  /* `CHAR_BIT' (defined in limits.h) gives the number of bits in a      */\r\n  /* `char' type.                                                        */\r\n\r\n#ifndef FT_CHAR_BIT\r\n#define FT_CHAR_BIT  CHAR_BIT\r\n#endif\r\n\r\n\r\n  /* The size of an `int' type.  */\r\n#if                                 FT_UINT_MAX == 0xFFFFUL\r\n#define FT_SIZEOF_INT  (16 / FT_CHAR_BIT)\r\n#elif                               FT_UINT_MAX == 0xFFFFFFFFUL\r\n#define FT_SIZEOF_INT  (32 / FT_CHAR_BIT)\r\n#elif FT_UINT_MAX > 0xFFFFFFFFUL && FT_UINT_MAX == 0xFFFFFFFFFFFFFFFFUL\r\n#define FT_SIZEOF_INT  (64 / FT_CHAR_BIT)\r\n#else\r\n#error \"Unsupported size of `int' type!\"\r\n#endif\r\n\r\n  /* The size of a `long' type.  A five-byte `long' (as used e.g. on the */\r\n  /* DM642) is recognized but avoided.                                   */\r\n#if                                  FT_ULONG_MAX == 0xFFFFFFFFUL\r\n#define FT_SIZEOF_LONG  (32 / FT_CHAR_BIT)\r\n#elif FT_ULONG_MAX > 0xFFFFFFFFUL && FT_ULONG_MAX == 0xFFFFFFFFFFUL\r\n#define FT_SIZEOF_LONG  (32 / FT_CHAR_BIT)\r\n#elif FT_ULONG_MAX > 0xFFFFFFFFUL && FT_ULONG_MAX == 0xFFFFFFFFFFFFFFFFUL\r\n#define FT_SIZEOF_LONG  (64 / FT_CHAR_BIT)\r\n#else\r\n#error \"Unsupported size of `long' type!\"\r\n#endif\r\n\r\n\r\n  /* FT_UNUSED is a macro used to indicate that a given parameter is not  */\r\n  /* used -- this is only used to get rid of unpleasant compiler warnings */\r\n#ifndef FT_UNUSED\r\n#define FT_UNUSED( arg )  ( (arg) = (arg) )\r\n#endif\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /*                     AUTOMATIC CONFIGURATION MACROS                    */\r\n  /*                                                                       */\r\n  /* These macros are computed from the ones defined above.  Don't touch   */\r\n  /* their definition, unless you know precisely what you are doing.  No   */\r\n  /* porter should need to mess with them.                                 */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Mac support                                                           */\r\n  /*                                                                       */\r\n  /*   This is the only necessary change, so it is defined here instead    */\r\n  /*   providing a new configuration file.                                 */\r\n  /*                                                                       */\r\n#if ( defined( __APPLE__ ) && !defined( DARWIN_NO_CARBON ) ) || \\\r\n    ( defined( __MWERKS__ ) && defined( macintosh )        )\r\n  /* no Carbon frameworks for 64bit 10.4.x */\r\n  /* AvailabilityMacros.h is available since Mac OS X 10.2,        */\r\n  /* so guess the system version by maximum errno before inclusion */\r\n#include <errno.h>\r\n#ifdef ECANCELED /* defined since 10.2 */\r\n#include \"AvailabilityMacros.h\"\r\n#endif\r\n#if defined( __LP64__ ) && \\\r\n    ( MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4 )\r\n#define DARWIN_NO_CARBON 1\r\n#else\r\n#define FT_MACINTOSH 1\r\n#endif\r\n\r\n#elif defined( __SC__ ) || defined( __MRC__ )\r\n  /* Classic MacOS compilers */\r\n#include \"ConditionalMacros.h\"\r\n#if TARGET_OS_MAC\r\n#define FT_MACINTOSH 1\r\n#endif\r\n\r\n#endif\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    basic_types                                                        */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Int16                                                           */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A typedef for a 16bit signed integer type.                         */\r\n  /*                                                                       */\r\n  typedef signed short  FT_Int16;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_UInt16                                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A typedef for a 16bit unsigned integer type.                       */\r\n  /*                                                                       */\r\n  typedef unsigned short  FT_UInt16;\r\n\r\n  /* */\r\n\r\n\r\n  /* this #if 0 ... #endif clause is for documentation purposes */\r\n#if 0\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Int32                                                           */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A typedef for a 32bit signed integer type.  The size depends on    */\r\n  /*    the configuration.                                                 */\r\n  /*                                                                       */\r\n  typedef signed XXX  FT_Int32;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_UInt32                                                          */\r\n  /*                                                                       */\r\n  /*    A typedef for a 32bit unsigned integer type.  The size depends on  */\r\n  /*    the configuration.                                                 */\r\n  /*                                                                       */\r\n  typedef unsigned XXX  FT_UInt32;\r\n\r\n  /* */\r\n\r\n#endif\r\n\r\n#if FT_SIZEOF_INT == (32 / FT_CHAR_BIT)\r\n\r\n  typedef signed int      FT_Int32;\r\n  typedef unsigned int    FT_UInt32;\r\n\r\n#elif FT_SIZEOF_LONG == (32 / FT_CHAR_BIT)\r\n\r\n  typedef signed long     FT_Int32;\r\n  typedef unsigned long   FT_UInt32;\r\n\r\n#else\r\n#error \"no 32bit type found -- please check your configuration files\"\r\n#endif\r\n\r\n\r\n  /* look up an integer type that is at least 32 bits */\r\n#if FT_SIZEOF_INT >= (32 / FT_CHAR_BIT)\r\n\r\n  typedef int            FT_Fast;\r\n  typedef unsigned int   FT_UFast;\r\n\r\n#elif FT_SIZEOF_LONG >= (32 / FT_CHAR_BIT)\r\n\r\n  typedef long           FT_Fast;\r\n  typedef unsigned long  FT_UFast;\r\n\r\n#endif\r\n\r\n\r\n  /* determine whether we have a 64-bit int type for platforms without */\r\n  /* Autoconf                                                          */\r\n#if FT_SIZEOF_LONG == (64 / FT_CHAR_BIT)\r\n\r\n  /* FT_LONG64 must be defined if a 64-bit type is available */\r\n#define FT_LONG64\r\n#define FT_INT64  long\r\n\r\n#elif defined( _MSC_VER ) && _MSC_VER >= 900  /* Visual C++ (and Intel C++) */\r\n\r\n  /* this compiler provides the __int64 type */\r\n#define FT_LONG64\r\n#define FT_INT64  __int64\r\n\r\n#elif defined( __BORLANDC__ )  /* Borland C++ */\r\n\r\n  /* XXXX: We should probably check the value of __BORLANDC__ in order */\r\n  /*       to test the compiler version.                               */\r\n\r\n  /* this compiler provides the __int64 type */\r\n#define FT_LONG64\r\n#define FT_INT64  __int64\r\n\r\n#elif defined( __WATCOMC__ )   /* Watcom C++ */\r\n\r\n  /* Watcom doesn't provide 64-bit data types */\r\n\r\n#elif defined( __MWERKS__ )    /* Metrowerks CodeWarrior */\r\n\r\n#define FT_LONG64\r\n#define FT_INT64  long long int\r\n\r\n#elif defined( __GNUC__ )\r\n\r\n  /* GCC provides the `long long' type */\r\n#define FT_LONG64\r\n#define FT_INT64  long long int\r\n\r\n#endif /* FT_SIZEOF_LONG == (64 / FT_CHAR_BIT) */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* A 64-bit data type will create compilation problems if you compile    */\r\n  /* in strict ANSI mode.  To avoid them, we disable its use if __STDC__   */\r\n  /* is defined.  You can however ignore this rule by defining the         */\r\n  /* FT_CONFIG_OPTION_FORCE_INT64 configuration macro.                     */\r\n  /*                                                                       */\r\n#if defined( FT_LONG64 ) && !defined( FT_CONFIG_OPTION_FORCE_INT64 )\r\n\r\n#ifdef __STDC__\r\n\r\n  /* undefine the 64-bit macros in strict ANSI compilation mode */\r\n#undef FT_LONG64\r\n#undef FT_INT64\r\n\r\n#endif /* __STDC__ */\r\n\r\n#endif /* FT_LONG64 && !FT_CONFIG_OPTION_FORCE_INT64 */\r\n\r\n\r\n#define FT_BEGIN_STMNT  do {\r\n#define FT_END_STMNT    } while ( 0 )\r\n#define FT_DUMMY_STMNT  FT_BEGIN_STMNT FT_END_STMNT\r\n\r\n\r\n#ifndef  FT_CONFIG_OPTION_NO_ASSEMBLER\r\n  /* Provide assembler fragments for performance-critical functions. */\r\n  /* These must be defined `static __inline__' with GCC.             */\r\n\r\n#if defined( __CC_ARM ) || defined( __ARMCC__ )  /* RVCT */\r\n#define FT_MULFIX_ASSEMBLER  FT_MulFix_arm\r\n\r\n  /* documentation is in freetype.h */\r\n\r\n  static __inline FT_Int32\r\n  FT_MulFix_arm( FT_Int32  a,\r\n                 FT_Int32  b )\r\n  {\r\n    register FT_Int32  t, t2;\r\n\r\n\r\n    __asm\r\n    {\r\n      smull t2, t,  b,  a           /* (lo=t2,hi=t) = a*b */\r\n      mov   a,  t,  asr #31         /* a   = (hi >> 31) */\r\n      add   a,  a,  #0x8000         /* a  += 0x8000 */\r\n      adds  t2, t2, a               /* t2 += a */\r\n      adc   t,  t,  #0              /* t  += carry */\r\n      mov   a,  t2, lsr #16         /* a   = t2 >> 16 */\r\n      orr   a,  a,  t,  lsl #16     /* a  |= t << 16 */\r\n    }\r\n    return a;\r\n  }\r\n\r\n#endif /* __CC_ARM || __ARMCC__ */\r\n\r\n\r\n#ifdef __GNUC__\r\n\r\n#if defined( __arm__ ) && !defined( __thumb__ )    && \\\r\n    !( defined( __CC_ARM ) || defined( __ARMCC__ ) )\r\n#define FT_MULFIX_ASSEMBLER  FT_MulFix_arm\r\n\r\n  /* documentation is in freetype.h */\r\n\r\n  static __inline__ FT_Int32\r\n  FT_MulFix_arm( FT_Int32  a,\r\n                 FT_Int32  b )\r\n  {\r\n    register FT_Int32  t, t2;\r\n\r\n\r\n    __asm__ __volatile__ (\r\n      \"smull  %1, %2, %4, %3\\n\\t\"       /* (lo=%1,hi=%2) = a*b */\r\n      \"mov    %0, %2, asr #31\\n\\t\"      /* %0  = (hi >> 31) */\r\n      \"add    %0, %0, #0x8000\\n\\t\"      /* %0 += 0x8000 */\r\n      \"adds   %1, %1, %0\\n\\t\"           /* %1 += %0 */\r\n      \"adc    %2, %2, #0\\n\\t\"           /* %2 += carry */\r\n      \"mov    %0, %1, lsr #16\\n\\t\"      /* %0  = %1 >> 16 */\r\n      \"orr    %0, %0, %2, lsl #16\\n\\t\"  /* %0 |= %2 << 16 */\r\n      : \"=r\"(a), \"=&r\"(t2), \"=&r\"(t)\r\n      : \"r\"(a), \"r\"(b) );\r\n    return a;\r\n  }\r\n\r\n#endif /* __arm__ && !__thumb__ && !( __CC_ARM || __ARMCC__ ) */\r\n\r\n#if defined( __i386__ )\r\n#define FT_MULFIX_ASSEMBLER  FT_MulFix_i386\r\n\r\n  /* documentation is in freetype.h */\r\n\r\n  static __inline__ FT_Int32\r\n  FT_MulFix_i386( FT_Int32  a,\r\n                  FT_Int32  b )\r\n  {\r\n    register FT_Int32  result;\r\n\r\n\r\n    __asm__ __volatile__ (\r\n      \"imul  %%edx\\n\"\r\n      \"movl  %%edx, %%ecx\\n\"\r\n      \"sarl  $31, %%ecx\\n\"\r\n      \"addl  $0x8000, %%ecx\\n\"\r\n      \"addl  %%ecx, %%eax\\n\"\r\n      \"adcl  $0, %%edx\\n\"\r\n      \"shrl  $16, %%eax\\n\"\r\n      \"shll  $16, %%edx\\n\"\r\n      \"addl  %%edx, %%eax\\n\"\r\n      : \"=a\"(result), \"=d\"(b)\r\n      : \"a\"(a), \"d\"(b)\r\n      : \"%ecx\", \"cc\" );\r\n    return result;\r\n  }\r\n\r\n#endif /* i386 */\r\n\r\n#endif /* __GNUC__ */\r\n\r\n\r\n#ifdef _MSC_VER /* Visual C++ */\r\n\r\n#ifdef _M_IX86\r\n\r\n#define FT_MULFIX_ASSEMBLER  FT_MulFix_i386\r\n\r\n  /* documentation is in freetype.h */\r\n\r\n  static __inline FT_Int32\r\n  FT_MulFix_i386( FT_Int32  a,\r\n                  FT_Int32  b )\r\n  {\r\n    register FT_Int32  result;\r\n\r\n    __asm\r\n    {\r\n      mov eax, a\r\n      mov edx, b\r\n      imul edx\r\n      mov ecx, edx\r\n      sar ecx, 31\r\n      add ecx, 8000h\r\n      add eax, ecx\r\n      adc edx, 0\r\n      shr eax, 16\r\n      shl edx, 16\r\n      add eax, edx\r\n      mov result, eax\r\n    }\r\n    return result;\r\n  }\r\n\r\n#endif /* _M_IX86 */\r\n\r\n#endif /* _MSC_VER */\r\n\r\n#endif /* !FT_CONFIG_OPTION_NO_ASSEMBLER */\r\n\r\n\r\n#ifdef FT_CONFIG_OPTION_INLINE_MULFIX\r\n#ifdef FT_MULFIX_ASSEMBLER\r\n#define FT_MULFIX_INLINED  FT_MULFIX_ASSEMBLER\r\n#endif\r\n#endif\r\n\r\n\r\n#ifdef FT_MAKE_OPTION_SINGLE_OBJECT\r\n\r\n#define FT_LOCAL( x )      static  x\r\n#define FT_LOCAL_DEF( x )  static  x\r\n\r\n#else\r\n\r\n#ifdef __cplusplus\r\n#define FT_LOCAL( x )      extern \"C\"  x\r\n#define FT_LOCAL_DEF( x )  extern \"C\"  x\r\n#else\r\n#define FT_LOCAL( x )      extern  x\r\n#define FT_LOCAL_DEF( x )  x\r\n#endif\r\n\r\n#endif /* FT_MAKE_OPTION_SINGLE_OBJECT */\r\n\r\n\r\n#ifndef FT_BASE\r\n\r\n#ifdef __cplusplus\r\n#define FT_BASE( x )  extern \"C\"  x\r\n#else\r\n#define FT_BASE( x )  extern  x\r\n#endif\r\n\r\n#endif /* !FT_BASE */\r\n\r\n\r\n#ifndef FT_BASE_DEF\r\n\r\n#ifdef __cplusplus\r\n#define FT_BASE_DEF( x )  x\r\n#else\r\n#define FT_BASE_DEF( x )  x\r\n#endif\r\n\r\n#endif /* !FT_BASE_DEF */\r\n\r\n\r\n#ifndef FT_EXPORT\r\n\r\n#ifdef __cplusplus\r\n#define FT_EXPORT( x )  extern \"C\"  x\r\n#else\r\n#define FT_EXPORT( x )  extern  x\r\n#endif\r\n\r\n#endif /* !FT_EXPORT */\r\n\r\n\r\n#ifndef FT_EXPORT_DEF\r\n\r\n#ifdef __cplusplus\r\n#define FT_EXPORT_DEF( x )  extern \"C\"  x\r\n#else\r\n#define FT_EXPORT_DEF( x )  extern  x\r\n#endif\r\n\r\n#endif /* !FT_EXPORT_DEF */\r\n\r\n\r\n#ifndef FT_EXPORT_VAR\r\n\r\n#ifdef __cplusplus\r\n#define FT_EXPORT_VAR( x )  extern \"C\"  x\r\n#else\r\n#define FT_EXPORT_VAR( x )  extern  x\r\n#endif\r\n\r\n#endif /* !FT_EXPORT_VAR */\r\n\r\n  /* The following macros are needed to compile the library with a   */\r\n  /* C++ compiler and with 16bit compilers.                          */\r\n  /*                                                                 */\r\n\r\n  /* This is special.  Within C++, you must specify `extern \"C\"' for */\r\n  /* functions which are used via function pointers, and you also    */\r\n  /* must do that for structures which contain function pointers to  */\r\n  /* assure C linkage -- it's not possible to have (local) anonymous */\r\n  /* functions which are accessed by (global) function pointers.     */\r\n  /*                                                                 */\r\n  /*                                                                 */\r\n  /* FT_CALLBACK_DEF is used to _define_ a callback function.        */\r\n  /*                                                                 */\r\n  /* FT_CALLBACK_TABLE is used to _declare_ a constant variable that */\r\n  /* contains pointers to callback functions.                        */\r\n  /*                                                                 */\r\n  /* FT_CALLBACK_TABLE_DEF is used to _define_ a constant variable   */\r\n  /* that contains pointers to callback functions.                   */\r\n  /*                                                                 */\r\n  /*                                                                 */\r\n  /* Some 16bit compilers have to redefine these macros to insert    */\r\n  /* the infamous `_cdecl' or `__fastcall' declarations.             */\r\n  /*                                                                 */\r\n#ifndef FT_CALLBACK_DEF\r\n#ifdef __cplusplus\r\n#define FT_CALLBACK_DEF( x )  extern \"C\"  x\r\n#else\r\n#define FT_CALLBACK_DEF( x )  static  x\r\n#endif\r\n#endif /* FT_CALLBACK_DEF */\r\n\r\n#ifndef FT_CALLBACK_TABLE\r\n#ifdef __cplusplus\r\n#define FT_CALLBACK_TABLE      extern \"C\"\r\n#define FT_CALLBACK_TABLE_DEF  extern \"C\"\r\n#else\r\n#define FT_CALLBACK_TABLE      extern\r\n#define FT_CALLBACK_TABLE_DEF  /* nothing */\r\n#endif\r\n#endif /* FT_CALLBACK_TABLE */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n\r\n#endif /* __FTCONFIG_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/config/ftheader.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftheader.h                                                             */\r\n/*                                                                         */\r\n/*    Build macros of the FreeType 2 library.                              */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2010 by */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n#ifndef __FT_HEADER_H__\r\n#define __FT_HEADER_H__\r\n\r\n\r\n  /*@***********************************************************************/\r\n  /*                                                                       */\r\n  /* <Macro>                                                               */\r\n  /*    FT_BEGIN_HEADER                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This macro is used in association with @FT_END_HEADER in header    */\r\n  /*    files to ensure that the declarations within are properly          */\r\n  /*    encapsulated in an `extern \"C\" { .. }' block when included from a  */\r\n  /*    C++ compiler.                                                      */\r\n  /*                                                                       */\r\n#ifdef __cplusplus\r\n#define FT_BEGIN_HEADER  extern \"C\" {\r\n#else\r\n#define FT_BEGIN_HEADER  /* nothing */\r\n#endif\r\n\r\n\r\n  /*@***********************************************************************/\r\n  /*                                                                       */\r\n  /* <Macro>                                                               */\r\n  /*    FT_END_HEADER                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This macro is used in association with @FT_BEGIN_HEADER in header  */\r\n  /*    files to ensure that the declarations within are properly          */\r\n  /*    encapsulated in an `extern \"C\" { .. }' block when included from a  */\r\n  /*    C++ compiler.                                                      */\r\n  /*                                                                       */\r\n#ifdef __cplusplus\r\n#define FT_END_HEADER  }\r\n#else\r\n#define FT_END_HEADER  /* nothing */\r\n#endif\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Aliases for the FreeType 2 public and configuration files.            */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    header_file_macros                                                 */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    Header File Macros                                                 */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    Macro definitions used to #include specific header files.          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    The following macros are defined to the name of specific           */\r\n  /*    FreeType~2 header files.  They can be used directly in #include    */\r\n  /*    statements as in:                                                  */\r\n  /*                                                                       */\r\n  /*    {                                                                  */\r\n  /*      #include FT_FREETYPE_H                                           */\r\n  /*      #include FT_MULTIPLE_MASTERS_H                                   */\r\n  /*      #include FT_GLYPH_H                                              */\r\n  /*    }                                                                  */\r\n  /*                                                                       */\r\n  /*    There are several reasons why we are now using macros to name      */\r\n  /*    public header files.  The first one is that such macros are not    */\r\n  /*    limited to the infamous 8.3~naming rule required by DOS (and       */\r\n  /*    `FT_MULTIPLE_MASTERS_H' is a lot more meaningful than `ftmm.h').   */\r\n  /*                                                                       */\r\n  /*    The second reason is that it allows for more flexibility in the    */\r\n  /*    way FreeType~2 is installed on a given system.                     */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /* configuration files */\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_CONFIG_CONFIG_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing\r\n   *   FreeType~2 configuration data.\r\n   *\r\n   */\r\n#ifndef FT_CONFIG_CONFIG_H\r\n#define FT_CONFIG_CONFIG_H  <freetype/config/ftconfig.h>\r\n#endif\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_CONFIG_STANDARD_LIBRARY_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing\r\n   *   FreeType~2 interface to the standard C library functions.\r\n   *\r\n   */\r\n#ifndef FT_CONFIG_STANDARD_LIBRARY_H\r\n#define FT_CONFIG_STANDARD_LIBRARY_H  <freetype/config/ftstdlib.h>\r\n#endif\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_CONFIG_OPTIONS_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing\r\n   *   FreeType~2 project-specific configuration options.\r\n   *\r\n   */\r\n#ifndef FT_CONFIG_OPTIONS_H\r\n#define FT_CONFIG_OPTIONS_H  <freetype/config/ftoption.h>\r\n#endif\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_CONFIG_MODULES_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   list of FreeType~2 modules that are statically linked to new library\r\n   *   instances in @FT_Init_FreeType.\r\n   *\r\n   */\r\n#ifndef FT_CONFIG_MODULES_H\r\n#define FT_CONFIG_MODULES_H  <freetype/config/ftmodule.h>\r\n#endif\r\n\r\n  /* */\r\n\r\n  /* public headers */\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_FREETYPE_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   base FreeType~2 API.\r\n   *\r\n   */\r\n#define FT_FREETYPE_H  <freetype/freetype.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_ERRORS_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   list of FreeType~2 error codes (and messages).\r\n   *\r\n   *   It is included by @FT_FREETYPE_H.\r\n   *\r\n   */\r\n#define FT_ERRORS_H  <freetype/fterrors.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_MODULE_ERRORS_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   list of FreeType~2 module error offsets (and messages).\r\n   *\r\n   */\r\n#define FT_MODULE_ERRORS_H  <freetype/ftmoderr.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_SYSTEM_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   FreeType~2 interface to low-level operations (i.e., memory management\r\n   *   and stream i/o).\r\n   *\r\n   *   It is included by @FT_FREETYPE_H.\r\n   *\r\n   */\r\n#define FT_SYSTEM_H  <freetype/ftsystem.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_IMAGE_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing type\r\n   *   definitions related to glyph images (i.e., bitmaps, outlines,\r\n   *   scan-converter parameters).\r\n   *\r\n   *   It is included by @FT_FREETYPE_H.\r\n   *\r\n   */\r\n#define FT_IMAGE_H  <freetype/ftimage.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_TYPES_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   basic data types defined by FreeType~2.\r\n   *\r\n   *   It is included by @FT_FREETYPE_H.\r\n   *\r\n   */\r\n#define FT_TYPES_H  <freetype/fttypes.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_LIST_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   list management API of FreeType~2.\r\n   *\r\n   *   (Most applications will never need to include this file.)\r\n   *\r\n   */\r\n#define FT_LIST_H  <freetype/ftlist.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_OUTLINE_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   scalable outline management API of FreeType~2.\r\n   *\r\n   */\r\n#define FT_OUTLINE_H  <freetype/ftoutln.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_SIZES_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   API which manages multiple @FT_Size objects per face.\r\n   *\r\n   */\r\n#define FT_SIZES_H  <freetype/ftsizes.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_MODULE_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   module management API of FreeType~2.\r\n   *\r\n   */\r\n#define FT_MODULE_H  <freetype/ftmodapi.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_RENDER_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   renderer module management API of FreeType~2.\r\n   *\r\n   */\r\n#define FT_RENDER_H  <freetype/ftrender.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_TYPE1_TABLES_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   types and API specific to the Type~1 format.\r\n   *\r\n   */\r\n#define FT_TYPE1_TABLES_H  <freetype/t1tables.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_TRUETYPE_IDS_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   enumeration values which identify name strings, languages, encodings,\r\n   *   etc.  This file really contains a _large_ set of constant macro\r\n   *   definitions, taken from the TrueType and OpenType specifications.\r\n   *\r\n   */\r\n#define FT_TRUETYPE_IDS_H  <freetype/ttnameid.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_TRUETYPE_TABLES_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   types and API specific to the TrueType (as well as OpenType) format.\r\n   *\r\n   */\r\n#define FT_TRUETYPE_TABLES_H  <freetype/tttables.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_TRUETYPE_TAGS_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   definitions of TrueType four-byte `tags' which identify blocks in\r\n   *   SFNT-based font formats (i.e., TrueType and OpenType).\r\n   *\r\n   */\r\n#define FT_TRUETYPE_TAGS_H  <freetype/tttags.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_BDF_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   definitions of an API which accesses BDF-specific strings from a\r\n   *   face.\r\n   *\r\n   */\r\n#define FT_BDF_H  <freetype/ftbdf.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_CID_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   definitions of an API which access CID font information from a\r\n   *   face.\r\n   *\r\n   */\r\n#define FT_CID_H  <freetype/ftcid.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_GZIP_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   definitions of an API which supports gzip-compressed files.\r\n   *\r\n   */\r\n#define FT_GZIP_H  <freetype/ftgzip.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_LZW_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   definitions of an API which supports LZW-compressed files.\r\n   *\r\n   */\r\n#define FT_LZW_H  <freetype/ftlzw.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_BZIP2_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   definitions of an API which supports bzip2-compressed files.\r\n   *\r\n   */\r\n#define FT_BZIP2_H  <freetype/ftbzip2.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_WINFONTS_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   definitions of an API which supports Windows FNT files.\r\n   *\r\n   */\r\n#define FT_WINFONTS_H   <freetype/ftwinfnt.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_GLYPH_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   API of the optional glyph management component.\r\n   *\r\n   */\r\n#define FT_GLYPH_H  <freetype/ftglyph.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_BITMAP_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   API of the optional bitmap conversion component.\r\n   *\r\n   */\r\n#define FT_BITMAP_H  <freetype/ftbitmap.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_BBOX_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   API of the optional exact bounding box computation routines.\r\n   *\r\n   */\r\n#define FT_BBOX_H  <freetype/ftbbox.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_CACHE_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   API of the optional FreeType~2 cache sub-system.\r\n   *\r\n   */\r\n#define FT_CACHE_H  <freetype/ftcache.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_CACHE_IMAGE_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   `glyph image' API of the FreeType~2 cache sub-system.\r\n   *\r\n   *   It is used to define a cache for @FT_Glyph elements.  You can also\r\n   *   use the API defined in @FT_CACHE_SMALL_BITMAPS_H if you only need to\r\n   *   store small glyph bitmaps, as it will use less memory.\r\n   *\r\n   *   This macro is deprecated.  Simply include @FT_CACHE_H to have all\r\n   *   glyph image-related cache declarations.\r\n   *\r\n   */\r\n#define FT_CACHE_IMAGE_H  FT_CACHE_H\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_CACHE_SMALL_BITMAPS_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   `small bitmaps' API of the FreeType~2 cache sub-system.\r\n   *\r\n   *   It is used to define a cache for small glyph bitmaps in a relatively\r\n   *   memory-efficient way.  You can also use the API defined in\r\n   *   @FT_CACHE_IMAGE_H if you want to cache arbitrary glyph images,\r\n   *   including scalable outlines.\r\n   *\r\n   *   This macro is deprecated.  Simply include @FT_CACHE_H to have all\r\n   *   small bitmaps-related cache declarations.\r\n   *\r\n   */\r\n#define FT_CACHE_SMALL_BITMAPS_H  FT_CACHE_H\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_CACHE_CHARMAP_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   `charmap' API of the FreeType~2 cache sub-system.\r\n   *\r\n   *   This macro is deprecated.  Simply include @FT_CACHE_H to have all\r\n   *   charmap-based cache declarations.\r\n   *\r\n   */\r\n#define FT_CACHE_CHARMAP_H  FT_CACHE_H\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_MAC_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   Macintosh-specific FreeType~2 API.  The latter is used to access\r\n   *   fonts embedded in resource forks.\r\n   *\r\n   *   This header file must be explicitly included by client applications\r\n   *   compiled on the Mac (note that the base API still works though).\r\n   *\r\n   */\r\n#define FT_MAC_H  <freetype/ftmac.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_MULTIPLE_MASTERS_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   optional multiple-masters management API of FreeType~2.\r\n   *\r\n   */\r\n#define FT_MULTIPLE_MASTERS_H  <freetype/ftmm.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_SFNT_NAMES_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   optional FreeType~2 API which accesses embedded `name' strings in\r\n   *   SFNT-based font formats (i.e., TrueType and OpenType).\r\n   *\r\n   */\r\n#define FT_SFNT_NAMES_H  <freetype/ftsnames.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_OPENTYPE_VALIDATE_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   optional FreeType~2 API which validates OpenType tables (BASE, GDEF,\r\n   *   GPOS, GSUB, JSTF).\r\n   *\r\n   */\r\n#define FT_OPENTYPE_VALIDATE_H  <freetype/ftotval.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_GX_VALIDATE_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   optional FreeType~2 API which validates TrueTypeGX/AAT tables (feat,\r\n   *   mort, morx, bsln, just, kern, opbd, trak, prop).\r\n   *\r\n   */\r\n#define FT_GX_VALIDATE_H  <freetype/ftgxval.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_PFR_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   FreeType~2 API which accesses PFR-specific data.\r\n   *\r\n   */\r\n#define FT_PFR_H  <freetype/ftpfr.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_STROKER_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   FreeType~2 API which provides functions to stroke outline paths.\r\n   */\r\n#define FT_STROKER_H  <freetype/ftstroke.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_SYNTHESIS_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   FreeType~2 API which performs artificial obliquing and emboldening.\r\n   */\r\n#define FT_SYNTHESIS_H  <freetype/ftsynth.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_XFREE86_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   FreeType~2 API which provides functions specific to the XFree86 and\r\n   *   X.Org X11 servers.\r\n   */\r\n#define FT_XFREE86_H  <freetype/ftxf86.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_TRIGONOMETRY_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   FreeType~2 API which performs trigonometric computations (e.g.,\r\n   *   cosines and arc tangents).\r\n   */\r\n#define FT_TRIGONOMETRY_H  <freetype/fttrigon.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_LCD_FILTER_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   FreeType~2 API which performs color filtering for subpixel rendering.\r\n   */\r\n#define FT_LCD_FILTER_H  <freetype/ftlcdfil.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_UNPATENTED_HINTING_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   FreeType~2 API which performs color filtering for subpixel rendering.\r\n   */\r\n#define FT_UNPATENTED_HINTING_H  <freetype/ttunpat.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_INCREMENTAL_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   FreeType~2 API which performs color filtering for subpixel rendering.\r\n   */\r\n#define FT_INCREMENTAL_H  <freetype/ftincrem.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_GASP_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   FreeType~2 API which returns entries from the TrueType GASP table.\r\n   */\r\n#define FT_GASP_H  <freetype/ftgasp.h>\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_ADVANCES_H\r\n   *\r\n   * @description:\r\n   *   A macro used in #include statements to name the file containing the\r\n   *   FreeType~2 API which returns individual and ranged glyph advances.\r\n   */\r\n#define FT_ADVANCES_H  <freetype/ftadvanc.h>\r\n\r\n\r\n  /* */\r\n\r\n#define FT_ERROR_DEFINITIONS_H  <freetype/fterrdef.h>\r\n\r\n\r\n  /* The internals of the cache sub-system are no longer exposed.  We */\r\n  /* default to FT_CACHE_H at the moment just in case, but we know of */\r\n  /* no rogue client that uses them.                                  */\r\n  /*                                                                  */\r\n#define FT_CACHE_MANAGER_H           <freetype/ftcache.h>\r\n#define FT_CACHE_INTERNAL_MRU_H      <freetype/ftcache.h>\r\n#define FT_CACHE_INTERNAL_MANAGER_H  <freetype/ftcache.h>\r\n#define FT_CACHE_INTERNAL_CACHE_H    <freetype/ftcache.h>\r\n#define FT_CACHE_INTERNAL_GLYPH_H    <freetype/ftcache.h>\r\n#define FT_CACHE_INTERNAL_IMAGE_H    <freetype/ftcache.h>\r\n#define FT_CACHE_INTERNAL_SBITS_H    <freetype/ftcache.h>\r\n\r\n\r\n#define FT_INCREMENTAL_H          <freetype/ftincrem.h>\r\n\r\n#define FT_TRUETYPE_UNPATENTED_H  <freetype/ttunpat.h>\r\n\r\n\r\n  /*\r\n   * Include internal headers definitions from <freetype/internal/...>\r\n   * only when building the library.\r\n   */\r\n#ifdef FT2_BUILD_LIBRARY\r\n#define  FT_INTERNAL_INTERNAL_H  <freetype/internal/internal.h>\r\n#include FT_INTERNAL_INTERNAL_H\r\n#endif /* FT2_BUILD_LIBRARY */\r\n\r\n\r\n#endif /* __FT2_BUILD_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/config/ftmodule.h",
    "content": "/*\r\n *  This file registers the FreeType modules compiled into the library.\r\n *\r\n *  If you use GNU make, this file IS NOT USED!  Instead, it is created in\r\n *  the objects directory (normally `<topdir>/objs/') based on information\r\n *  from `<topdir>/modules.cfg'.\r\n *\r\n *  Please read `docs/INSTALL.ANY' and `docs/CUSTOMIZE' how to compile\r\n *  FreeType without GNU make.\r\n *\r\n */\r\n\r\nFT_USE_MODULE( FT_Module_Class, autofit_module_class )\r\nFT_USE_MODULE( FT_Driver_ClassRec, tt_driver_class )\r\nFT_USE_MODULE( FT_Driver_ClassRec, t1_driver_class )\r\nFT_USE_MODULE( FT_Driver_ClassRec, cff_driver_class )\r\nFT_USE_MODULE( FT_Driver_ClassRec, t1cid_driver_class )\r\nFT_USE_MODULE( FT_Driver_ClassRec, pfr_driver_class )\r\nFT_USE_MODULE( FT_Driver_ClassRec, t42_driver_class )\r\nFT_USE_MODULE( FT_Driver_ClassRec, winfnt_driver_class )\r\nFT_USE_MODULE( FT_Driver_ClassRec, pcf_driver_class )\r\nFT_USE_MODULE( FT_Module_Class, psaux_module_class )\r\nFT_USE_MODULE( FT_Module_Class, psnames_module_class )\r\nFT_USE_MODULE( FT_Module_Class, pshinter_module_class )\r\nFT_USE_MODULE( FT_Renderer_Class, ft_raster1_renderer_class )\r\nFT_USE_MODULE( FT_Module_Class, sfnt_module_class )\r\nFT_USE_MODULE( FT_Renderer_Class, ft_smooth_renderer_class )\r\nFT_USE_MODULE( FT_Renderer_Class, ft_smooth_lcd_renderer_class )\r\nFT_USE_MODULE( FT_Renderer_Class, ft_smooth_lcdv_renderer_class )\r\nFT_USE_MODULE( FT_Driver_ClassRec, bdf_driver_class )\r\n\r\n/* EOF */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/config/ftoption.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftoption.h                                                             */\r\n/*                                                                         */\r\n/*    User-selectable configuration macros (specification only).           */\r\n/*                                                                         */\r\n/*  Copyright 1996-2011 by                                                 */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTOPTION_H__\r\n#define __FTOPTION_H__\r\n\r\n\r\n#include <ft2build.h>\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /*                 USER-SELECTABLE CONFIGURATION MACROS                  */\r\n  /*                                                                       */\r\n  /* This file contains the default configuration macro definitions for    */\r\n  /* a standard build of the FreeType library.  There are three ways to    */\r\n  /* use this file to build project-specific versions of the library:      */\r\n  /*                                                                       */\r\n  /*  - You can modify this file by hand, but this is not recommended in   */\r\n  /*    cases where you would like to build several versions of the        */\r\n  /*    library from a single source directory.                            */\r\n  /*                                                                       */\r\n  /*  - You can put a copy of this file in your build directory, more      */\r\n  /*    precisely in `$BUILD/freetype/config/ftoption.h', where `$BUILD'   */\r\n  /*    is the name of a directory that is included _before_ the FreeType  */\r\n  /*    include path during compilation.                                   */\r\n  /*                                                                       */\r\n  /*    The default FreeType Makefiles and Jamfiles use the build          */\r\n  /*    directory `builds/<system>' by default, but you can easily change  */\r\n  /*    that for your own projects.                                        */\r\n  /*                                                                       */\r\n  /*  - Copy the file <ft2build.h> to `$BUILD/ft2build.h' and modify it    */\r\n  /*    slightly to pre-define the macro FT_CONFIG_OPTIONS_H used to       */\r\n  /*    locate this file during the build.  For example,                   */\r\n  /*                                                                       */\r\n  /*      #define FT_CONFIG_OPTIONS_H  <myftoptions.h>                     */\r\n  /*      #include <freetype/config/ftheader.h>                            */\r\n  /*                                                                       */\r\n  /*    will use `$BUILD/myftoptions.h' instead of this file for macro     */\r\n  /*    definitions.                                                       */\r\n  /*                                                                       */\r\n  /*    Note also that you can similarly pre-define the macro              */\r\n  /*    FT_CONFIG_MODULES_H used to locate the file listing of the modules */\r\n  /*    that are statically linked to the library at compile time.  By     */\r\n  /*    default, this file is <freetype/config/ftmodule.h>.                */\r\n  /*                                                                       */\r\n  /*  We highly recommend using the third method whenever possible.        */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /****                                                                 ****/\r\n  /**** G E N E R A L   F R E E T Y P E   2   C O N F I G U R A T I O N ****/\r\n  /****                                                                 ****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Uncomment the line below if you want to activate sub-pixel rendering  */\r\n  /* (a.k.a. LCD rendering, or ClearType) in this build of the library.    */\r\n  /*                                                                       */\r\n  /* Note that this feature is covered by several Microsoft patents        */\r\n  /* and should not be activated in any default build of the library.      */\r\n  /*                                                                       */\r\n  /* This macro has no impact on the FreeType API, only on its             */\r\n  /* _implementation_.  For example, using FT_RENDER_MODE_LCD when calling */\r\n  /* FT_Render_Glyph still generates a bitmap that is 3 times wider than   */\r\n  /* the original size in case this macro isn't defined; however, each     */\r\n  /* triplet of subpixels has R=G=B.                                       */\r\n  /*                                                                       */\r\n  /* This is done to allow FreeType clients to run unmodified, forcing     */\r\n  /* them to display normal gray-level anti-aliased glyphs.                */\r\n  /*                                                                       */\r\n/* #define FT_CONFIG_OPTION_SUBPIXEL_RENDERING */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Many compilers provide a non-ANSI 64-bit data type that can be used   */\r\n  /* by FreeType to speed up some computations.  However, this will create */\r\n  /* some problems when compiling the library in strict ANSI mode.         */\r\n  /*                                                                       */\r\n  /* For this reason, the use of 64-bit integers is normally disabled when */\r\n  /* the __STDC__ macro is defined.  You can however disable this by       */\r\n  /* defining the macro FT_CONFIG_OPTION_FORCE_INT64 here.                 */\r\n  /*                                                                       */\r\n  /* For most compilers, this will only create compilation warnings when   */\r\n  /* building the library.                                                 */\r\n  /*                                                                       */\r\n  /* ObNote: The compiler-specific 64-bit integers are detected in the     */\r\n  /*         file `ftconfig.h' either statically or through the            */\r\n  /*         `configure' script on supported platforms.                    */\r\n  /*                                                                       */\r\n#undef FT_CONFIG_OPTION_FORCE_INT64\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* If this macro is defined, do not try to use an assembler version of   */\r\n  /* performance-critical functions (e.g. FT_MulFix).  You should only do  */\r\n  /* that to verify that the assembler function works properly, or to      */\r\n  /* execute benchmark tests of the various implementations.               */\r\n/* #define FT_CONFIG_OPTION_NO_ASSEMBLER */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* If this macro is defined, try to use an inlined assembler version of  */\r\n  /* the `FT_MulFix' function, which is a `hotspot' when loading and       */\r\n  /* hinting glyphs, and which should be executed as fast as possible.     */\r\n  /*                                                                       */\r\n  /* Note that if your compiler or CPU is not supported, this will default */\r\n  /* to the standard and portable implementation found in `ftcalc.c'.      */\r\n  /*                                                                       */\r\n#define FT_CONFIG_OPTION_INLINE_MULFIX\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* LZW-compressed file support.                                          */\r\n  /*                                                                       */\r\n  /*   FreeType now handles font files that have been compressed with the  */\r\n  /*   `compress' program.  This is mostly used to parse many of the PCF   */\r\n  /*   files that come with various X11 distributions.  The implementation */\r\n  /*   uses NetBSD's `zopen' to partially uncompress the file on the fly   */\r\n  /*   (see src/lzw/ftgzip.c).                                             */\r\n  /*                                                                       */\r\n  /*   Define this macro if you want to enable this `feature'.             */\r\n  /*                                                                       */\r\n#define FT_CONFIG_OPTION_USE_LZW\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Gzip-compressed file support.                                         */\r\n  /*                                                                       */\r\n  /*   FreeType now handles font files that have been compressed with the  */\r\n  /*   `gzip' program.  This is mostly used to parse many of the PCF files */\r\n  /*   that come with XFree86.  The implementation uses `zlib' to          */\r\n  /*   partially uncompress the file on the fly (see src/gzip/ftgzip.c).   */\r\n  /*                                                                       */\r\n  /*   Define this macro if you want to enable this `feature'.  See also   */\r\n  /*   the macro FT_CONFIG_OPTION_SYSTEM_ZLIB below.                       */\r\n  /*                                                                       */\r\n#define FT_CONFIG_OPTION_USE_ZLIB\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* ZLib library selection                                                */\r\n  /*                                                                       */\r\n  /*   This macro is only used when FT_CONFIG_OPTION_USE_ZLIB is defined.  */\r\n  /*   It allows FreeType's `ftgzip' component to link to the system's     */\r\n  /*   installation of the ZLib library.  This is useful on systems like   */\r\n  /*   Unix or VMS where it generally is already available.                */\r\n  /*                                                                       */\r\n  /*   If you let it undefined, the component will use its own copy        */\r\n  /*   of the zlib sources instead.  These have been modified to be        */\r\n  /*   included directly within the component and *not* export external    */\r\n  /*   function names.  This allows you to link any program with FreeType  */\r\n  /*   _and_ ZLib without linking conflicts.                               */\r\n  /*                                                                       */\r\n  /*   Do not #undef this macro here since the build system might define   */\r\n  /*   it for certain configurations only.                                 */\r\n  /*                                                                       */\r\n/* #define FT_CONFIG_OPTION_SYSTEM_ZLIB */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Bzip2-compressed file support.                                        */\r\n  /*                                                                       */\r\n  /*   FreeType now handles font files that have been compressed with the  */\r\n  /*   `bzip2' program.  This is mostly used to parse many of the PCF      */\r\n  /*   files that come with XFree86.  The implementation uses `libbz2' to  */\r\n  /*   partially uncompress the file on the fly (see src/bzip2/ftbzip2.c). */\r\n  /*   Contrary to gzip, bzip2 currently is not included and need to use   */\r\n  /*   the system available bzip2 implementation.                          */\r\n  /*                                                                       */\r\n  /*   Define this macro if you want to enable this `feature'.             */\r\n  /*                                                                       */\r\n/* #define FT_CONFIG_OPTION_USE_BZIP2 */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Define to disable the use of file stream functions and types, FILE,   */\r\n  /* fopen() etc.  Enables the use of smaller system libraries on embedded */\r\n  /* systems that have multiple system libraries, some with or without     */\r\n  /* file stream support, in the cases where file stream support is not    */\r\n  /* necessary such as memory loading of font files.                       */\r\n  /*                                                                       */\r\n/* #define FT_CONFIG_OPTION_DISABLE_STREAM_SUPPORT */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* DLL export compilation                                                */\r\n  /*                                                                       */\r\n  /*   When compiling FreeType as a DLL, some systems/compilers need a     */\r\n  /*   special keyword in front OR after the return type of function       */\r\n  /*   declarations.                                                       */\r\n  /*                                                                       */\r\n  /*   Two macros are used within the FreeType source code to define       */\r\n  /*   exported library functions: FT_EXPORT and FT_EXPORT_DEF.            */\r\n  /*                                                                       */\r\n  /*     FT_EXPORT( return_type )                                          */\r\n  /*                                                                       */\r\n  /*       is used in a function declaration, as in                        */\r\n  /*                                                                       */\r\n  /*         FT_EXPORT( FT_Error )                                         */\r\n  /*         FT_Init_FreeType( FT_Library*  alibrary );                    */\r\n  /*                                                                       */\r\n  /*                                                                       */\r\n  /*     FT_EXPORT_DEF( return_type )                                      */\r\n  /*                                                                       */\r\n  /*       is used in a function definition, as in                         */\r\n  /*                                                                       */\r\n  /*         FT_EXPORT_DEF( FT_Error )                                     */\r\n  /*         FT_Init_FreeType( FT_Library*  alibrary )                     */\r\n  /*         {                                                             */\r\n  /*           ... some code ...                                           */\r\n  /*           return FT_Err_Ok;                                           */\r\n  /*         }                                                             */\r\n  /*                                                                       */\r\n  /*   You can provide your own implementation of FT_EXPORT and            */\r\n  /*   FT_EXPORT_DEF here if you want.  If you leave them undefined, they  */\r\n  /*   will be later automatically defined as `extern return_type' to      */\r\n  /*   allow normal compilation.                                           */\r\n  /*                                                                       */\r\n  /*   Do not #undef these macros here since the build system might define */\r\n  /*   them for certain configurations only.                               */\r\n  /*                                                                       */\r\n/* #define FT_EXPORT(x)      extern x */\r\n/* #define FT_EXPORT_DEF(x)  x */\r\n#define FT_EXPORT(x) __declspec(dllexport) x\r\n#define FT_EXPORT_DEF(x) __declspec(dllexport) x\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Glyph Postscript Names handling                                       */\r\n  /*                                                                       */\r\n  /*   By default, FreeType 2 is compiled with the `psnames' module.  This */\r\n  /*   module is in charge of converting a glyph name string into a        */\r\n  /*   Unicode value, or return a Macintosh standard glyph name for the    */\r\n  /*   use with the TrueType `post' table.                                 */\r\n  /*                                                                       */\r\n  /*   Undefine this macro if you do not want `psnames' compiled in your   */\r\n  /*   build of FreeType.  This has the following effects:                 */\r\n  /*                                                                       */\r\n  /*   - The TrueType driver will provide its own set of glyph names,      */\r\n  /*     if you build it to support postscript names in the TrueType       */\r\n  /*     `post' table.                                                     */\r\n  /*                                                                       */\r\n  /*   - The Type 1 driver will not be able to synthesize a Unicode        */\r\n  /*     charmap out of the glyphs found in the fonts.                     */\r\n  /*                                                                       */\r\n  /*   You would normally undefine this configuration macro when building  */\r\n  /*   a version of FreeType that doesn't contain a Type 1 or CFF driver.  */\r\n  /*                                                                       */\r\n#define FT_CONFIG_OPTION_POSTSCRIPT_NAMES\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Postscript Names to Unicode Values support                            */\r\n  /*                                                                       */\r\n  /*   By default, FreeType 2 is built with the `PSNames' module compiled  */\r\n  /*   in.  Among other things, the module is used to convert a glyph name */\r\n  /*   into a Unicode value.  This is especially useful in order to        */\r\n  /*   synthesize on the fly a Unicode charmap from the CFF/Type 1 driver  */\r\n  /*   through a big table named the `Adobe Glyph List' (AGL).             */\r\n  /*                                                                       */\r\n  /*   Undefine this macro if you do not want the Adobe Glyph List         */\r\n  /*   compiled in your `PSNames' module.  The Type 1 driver will not be   */\r\n  /*   able to synthesize a Unicode charmap out of the glyphs found in the */\r\n  /*   fonts.                                                              */\r\n  /*                                                                       */\r\n#define FT_CONFIG_OPTION_ADOBE_GLYPH_LIST\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Support for Mac fonts                                                 */\r\n  /*                                                                       */\r\n  /*   Define this macro if you want support for outline fonts in Mac      */\r\n  /*   format (mac dfont, mac resource, macbinary containing a mac         */\r\n  /*   resource) on non-Mac platforms.                                     */\r\n  /*                                                                       */\r\n  /*   Note that the `FOND' resource isn't checked.                        */\r\n  /*                                                                       */\r\n#define FT_CONFIG_OPTION_MAC_FONTS\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Guessing methods to access embedded resource forks                    */\r\n  /*                                                                       */\r\n  /*   Enable extra Mac fonts support on non-Mac platforms (e.g.           */\r\n  /*   GNU/Linux).                                                         */\r\n  /*                                                                       */\r\n  /*   Resource forks which include fonts data are stored sometimes in     */\r\n  /*   locations which users or developers don't expected.  In some cases, */\r\n  /*   resource forks start with some offset from the head of a file.  In  */\r\n  /*   other cases, the actual resource fork is stored in file different   */\r\n  /*   from what the user specifies.  If this option is activated,         */\r\n  /*   FreeType tries to guess whether such offsets or different file      */\r\n  /*   names must be used.                                                 */\r\n  /*                                                                       */\r\n  /*   Note that normal, direct access of resource forks is controlled via */\r\n  /*   the FT_CONFIG_OPTION_MAC_FONTS option.                              */\r\n  /*                                                                       */\r\n#ifdef FT_CONFIG_OPTION_MAC_FONTS\r\n#define FT_CONFIG_OPTION_GUESSING_EMBEDDED_RFORK\r\n#endif\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Allow the use of FT_Incremental_Interface to load typefaces that      */\r\n  /* contain no glyph data, but supply it via a callback function.         */\r\n  /* This is required by clients supporting document formats which         */\r\n  /* supply font data incrementally as the document is parsed, such        */\r\n  /* as the Ghostscript interpreter for the PostScript language.           */\r\n  /*                                                                       */\r\n#define FT_CONFIG_OPTION_INCREMENTAL\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* The size in bytes of the render pool used by the scan-line converter  */\r\n  /* to do all of its work.                                                */\r\n  /*                                                                       */\r\n  /* This must be greater than 4KByte if you use FreeType to rasterize     */\r\n  /* glyphs; otherwise, you may set it to zero to avoid unnecessary        */\r\n  /* allocation of the render pool.                                        */\r\n  /*                                                                       */\r\n#define FT_RENDER_POOL_SIZE  16384L\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* FT_MAX_MODULES                                                        */\r\n  /*                                                                       */\r\n  /*   The maximum number of modules that can be registered in a single    */\r\n  /*   FreeType library object.  32 is the default.                        */\r\n  /*                                                                       */\r\n#define FT_MAX_MODULES  32\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Debug level                                                           */\r\n  /*                                                                       */\r\n  /*   FreeType can be compiled in debug or trace mode.  In debug mode,    */\r\n  /*   errors are reported through the `ftdebug' component.  In trace      */\r\n  /*   mode, additional messages are sent to the standard output during    */\r\n  /*   execution.                                                          */\r\n  /*                                                                       */\r\n  /*   Define FT_DEBUG_LEVEL_ERROR to build the library in debug mode.     */\r\n  /*   Define FT_DEBUG_LEVEL_TRACE to build it in trace mode.              */\r\n  /*                                                                       */\r\n  /*   Don't define any of these macros to compile in `release' mode!      */\r\n  /*                                                                       */\r\n  /*   Do not #undef these macros here since the build system might define */\r\n  /*   them for certain configurations only.                               */\r\n  /*                                                                       */\r\n/* #define FT_DEBUG_LEVEL_ERROR */\r\n/* #define FT_DEBUG_LEVEL_TRACE */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Autofitter debugging                                                  */\r\n  /*                                                                       */\r\n  /*   If FT_DEBUG_AUTOFIT is defined, FreeType provides some means to     */\r\n  /*   control the autofitter behaviour for debugging purposes with global */\r\n  /*   boolean variables (consequently, you should *never* enable this     */\r\n  /*   while compiling in `release' mode):                                 */\r\n  /*                                                                       */\r\n  /*     _af_debug_disable_horz_hints                                      */\r\n  /*     _af_debug_disable_vert_hints                                      */\r\n  /*     _af_debug_disable_blue_hints                                      */\r\n  /*                                                                       */\r\n  /*   Additionally, the following functions provide dumps of various      */\r\n  /*   internal autofit structures to stdout (using `printf'):             */\r\n  /*                                                                       */\r\n  /*     af_glyph_hints_dump_points                                        */\r\n  /*     af_glyph_hints_dump_segments                                      */\r\n  /*     af_glyph_hints_dump_edges                                         */\r\n  /*                                                                       */\r\n  /*   As an argument, they use another global variable:                   */\r\n  /*                                                                       */\r\n  /*     _af_debug_hints                                                   */\r\n  /*                                                                       */\r\n  /*   Please have a look at the `ftgrid' demo program to see how those    */\r\n  /*   variables and macros should be used.                                */\r\n  /*                                                                       */\r\n  /*   Do not #undef these macros here since the build system might define */\r\n  /*   them for certain configurations only.                               */\r\n  /*                                                                       */\r\n/* #define FT_DEBUG_AUTOFIT */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Memory Debugging                                                      */\r\n  /*                                                                       */\r\n  /*   FreeType now comes with an integrated memory debugger that is       */\r\n  /*   capable of detecting simple errors like memory leaks or double      */\r\n  /*   deletes.  To compile it within your build of the library, you       */\r\n  /*   should define FT_DEBUG_MEMORY here.                                 */\r\n  /*                                                                       */\r\n  /*   Note that the memory debugger is only activated at runtime when     */\r\n  /*   when the _environment_ variable `FT2_DEBUG_MEMORY' is defined also! */\r\n  /*                                                                       */\r\n  /*   Do not #undef this macro here since the build system might define   */\r\n  /*   it for certain configurations only.                                 */\r\n  /*                                                                       */\r\n/* #define FT_DEBUG_MEMORY */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Module errors                                                         */\r\n  /*                                                                       */\r\n  /*   If this macro is set (which is _not_ the default), the higher byte  */\r\n  /*   of an error code gives the module in which the error has occurred,  */\r\n  /*   while the lower byte is the real error code.                        */\r\n  /*                                                                       */\r\n  /*   Setting this macro makes sense for debugging purposes only, since   */\r\n  /*   it would break source compatibility of certain programs that use    */\r\n  /*   FreeType 2.                                                         */\r\n  /*                                                                       */\r\n  /*   More details can be found in the files ftmoderr.h and fterrors.h.   */\r\n  /*                                                                       */\r\n#undef FT_CONFIG_OPTION_USE_MODULE_ERRORS\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Position Independent Code                                             */\r\n  /*                                                                       */\r\n  /*   If this macro is set (which is _not_ the default), FreeType2 will   */\r\n  /*   avoid creating constants that require address fixups.  Instead the  */\r\n  /*   constants will be moved into a struct and additional intialization  */\r\n  /*   code will be used.                                                  */\r\n  /*                                                                       */\r\n  /*   Setting this macro is needed for systems that prohibit address      */\r\n  /*   fixups, such as BREW.                                               */\r\n  /*                                                                       */\r\n/* #define FT_CONFIG_OPTION_PIC */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /****                                                                 ****/\r\n  /****        S F N T   D R I V E R    C O N F I G U R A T I O N       ****/\r\n  /****                                                                 ****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Define TT_CONFIG_OPTION_EMBEDDED_BITMAPS if you want to support       */\r\n  /* embedded bitmaps in all formats using the SFNT module (namely         */\r\n  /* TrueType & OpenType).                                                 */\r\n  /*                                                                       */\r\n#define TT_CONFIG_OPTION_EMBEDDED_BITMAPS\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Define TT_CONFIG_OPTION_POSTSCRIPT_NAMES if you want to be able to    */\r\n  /* load and enumerate the glyph Postscript names in a TrueType or        */\r\n  /* OpenType file.                                                        */\r\n  /*                                                                       */\r\n  /* Note that when you do not compile the `PSNames' module by undefining  */\r\n  /* the above FT_CONFIG_OPTION_POSTSCRIPT_NAMES, the `sfnt' module will   */\r\n  /* contain additional code used to read the PS Names table from a font.  */\r\n  /*                                                                       */\r\n  /* (By default, the module uses `PSNames' to extract glyph names.)       */\r\n  /*                                                                       */\r\n#define TT_CONFIG_OPTION_POSTSCRIPT_NAMES\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Define TT_CONFIG_OPTION_SFNT_NAMES if your applications need to       */\r\n  /* access the internal name table in a SFNT-based format like TrueType   */\r\n  /* or OpenType.  The name table contains various strings used to         */\r\n  /* describe the font, like family name, copyright, version, etc.  It     */\r\n  /* does not contain any glyph name though.                               */\r\n  /*                                                                       */\r\n  /* Accessing SFNT names is done through the functions declared in        */\r\n  /* `freetype/ftsnames.h'.                                                */\r\n  /*                                                                       */\r\n#define TT_CONFIG_OPTION_SFNT_NAMES\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* TrueType CMap support                                                 */\r\n  /*                                                                       */\r\n  /*   Here you can fine-tune which TrueType CMap table format shall be    */\r\n  /*   supported.                                                          */\r\n#define TT_CONFIG_CMAP_FORMAT_0\r\n#define TT_CONFIG_CMAP_FORMAT_2\r\n#define TT_CONFIG_CMAP_FORMAT_4\r\n#define TT_CONFIG_CMAP_FORMAT_6\r\n#define TT_CONFIG_CMAP_FORMAT_8\r\n#define TT_CONFIG_CMAP_FORMAT_10\r\n#define TT_CONFIG_CMAP_FORMAT_12\r\n#define TT_CONFIG_CMAP_FORMAT_13\r\n#define TT_CONFIG_CMAP_FORMAT_14\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /****                                                                 ****/\r\n  /****    T R U E T Y P E   D R I V E R    C O N F I G U R A T I O N   ****/\r\n  /****                                                                 ****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Define TT_CONFIG_OPTION_BYTECODE_INTERPRETER if you want to compile   */\r\n  /* a bytecode interpreter in the TrueType driver.                        */\r\n  /*                                                                       */\r\n  /* By undefining this, you will only compile the code necessary to load  */\r\n  /* TrueType glyphs without hinting.                                      */\r\n  /*                                                                       */\r\n  /*   Do not #undef this macro here, since the build system might         */\r\n  /*   define it for certain configurations only.                          */\r\n  /*                                                                       */\r\n#define TT_CONFIG_OPTION_BYTECODE_INTERPRETER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* If you define TT_CONFIG_OPTION_UNPATENTED_HINTING, a special version  */\r\n  /* of the TrueType bytecode interpreter is used that doesn't implement   */\r\n  /* any of the patented opcodes and algorithms.  The patents related to   */\r\n  /* TrueType hinting have expired worldwide since May 2010; this option   */\r\n  /* is now deprecated.                                                    */\r\n  /*                                                                       */\r\n  /* Note that the TT_CONFIG_OPTION_UNPATENTED_HINTING macro is *ignored*  */\r\n  /* if you define TT_CONFIG_OPTION_BYTECODE_INTERPRETER; in other words,  */\r\n  /* either define TT_CONFIG_OPTION_BYTECODE_INTERPRETER or                */\r\n  /* TT_CONFIG_OPTION_UNPATENTED_HINTING but not both at the same time.    */\r\n  /*                                                                       */\r\n  /* This macro is only useful for a small number of font files (mostly    */\r\n  /* for Asian scripts) that require bytecode interpretation to properly   */\r\n  /* load glyphs.  For all other fonts, this produces unpleasant results,  */\r\n  /* thus the unpatented interpreter is never used to load glyphs from     */\r\n  /* TrueType fonts unless one of the following two options is used.       */\r\n  /*                                                                       */\r\n  /*   - The unpatented interpreter is explicitly activated by the user    */\r\n  /*     through the FT_PARAM_TAG_UNPATENTED_HINTING parameter tag         */\r\n  /*     when opening the FT_Face.                                         */\r\n  /*                                                                       */\r\n  /*   - FreeType detects that the FT_Face corresponds to one of the       */\r\n  /*     `trick' fonts (e.g., `Mingliu') it knows about.  The font engine  */\r\n  /*     contains a hard-coded list of font names and other matching       */\r\n  /*     parameters (see function `tt_face_init' in file                   */\r\n  /*     `src/truetype/ttobjs.c').                                         */\r\n  /*                                                                       */\r\n  /* Here a sample code snippet for using FT_PARAM_TAG_UNPATENTED_HINTING. */\r\n  /*                                                                       */\r\n  /*   {                                                                   */\r\n  /*     FT_Parameter  parameter;                                          */\r\n  /*     FT_Open_Args  open_args;                                          */\r\n  /*                                                                       */\r\n  /*                                                                       */\r\n  /*     parameter.tag = FT_PARAM_TAG_UNPATENTED_HINTING;                  */\r\n  /*                                                                       */\r\n  /*     open_args.flags      = FT_OPEN_PATHNAME | FT_OPEN_PARAMS;         */\r\n  /*     open_args.pathname   = my_font_pathname;                          */\r\n  /*     open_args.num_params = 1;                                         */\r\n  /*     open_args.params     = &parameter;                                */\r\n  /*                                                                       */\r\n  /*     error = FT_Open_Face( library, &open_args, index, &face );        */\r\n  /*     ...                                                               */\r\n  /*   }                                                                   */\r\n  /*                                                                       */\r\n/* #define TT_CONFIG_OPTION_UNPATENTED_HINTING */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Define TT_CONFIG_OPTION_INTERPRETER_SWITCH to compile the TrueType    */\r\n  /* bytecode interpreter with a huge switch statement, rather than a call */\r\n  /* table.  This results in smaller and faster code for a number of       */\r\n  /* architectures.                                                        */\r\n  /*                                                                       */\r\n  /* Note however that on some compiler/processor combinations, undefining */\r\n  /* this macro will generate faster, though larger, code.                 */\r\n  /*                                                                       */\r\n#define TT_CONFIG_OPTION_INTERPRETER_SWITCH\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Define TT_CONFIG_OPTION_COMPONENT_OFFSET_SCALED to compile the        */\r\n  /* TrueType glyph loader to use Apple's definition of how to handle      */\r\n  /* component offsets in composite glyphs.                                */\r\n  /*                                                                       */\r\n  /* Apple and MS disagree on the default behavior of component offsets    */\r\n  /* in composites.  Apple says that they should be scaled by the scaling  */\r\n  /* factors in the transformation matrix (roughly, it's more complex)     */\r\n  /* while MS says they should not.  OpenType defines two bits in the      */\r\n  /* composite flags array which can be used to disambiguate, but old      */\r\n  /* fonts will not have them.                                             */\r\n  /*                                                                       */\r\n  /*   http://www.microsoft.com/typography/otspec/glyf.htm                 */\r\n  /*   http://fonts.apple.com/TTRefMan/RM06/Chap6glyf.html                 */\r\n  /*                                                                       */\r\n#undef TT_CONFIG_OPTION_COMPONENT_OFFSET_SCALED\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Define TT_CONFIG_OPTION_GX_VAR_SUPPORT if you want to include         */\r\n  /* support for Apple's distortable font technology (fvar, gvar, cvar,    */\r\n  /* and avar tables).  This has many similarities to Type 1 Multiple      */\r\n  /* Masters support.                                                      */\r\n  /*                                                                       */\r\n#define TT_CONFIG_OPTION_GX_VAR_SUPPORT\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Define TT_CONFIG_OPTION_BDF if you want to include support for        */\r\n  /* an embedded `BDF ' table within SFNT-based bitmap formats.            */\r\n  /*                                                                       */\r\n#define TT_CONFIG_OPTION_BDF\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /****                                                                 ****/\r\n  /****      T Y P E 1   D R I V E R    C O N F I G U R A T I O N       ****/\r\n  /****                                                                 ****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* T1_MAX_DICT_DEPTH is the maximal depth of nest dictionaries and       */\r\n  /* arrays in the Type 1 stream (see t1load.c).  A minimum of 4 is        */\r\n  /* required.                                                             */\r\n  /*                                                                       */\r\n#define T1_MAX_DICT_DEPTH  5\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* T1_MAX_SUBRS_CALLS details the maximum number of nested sub-routine   */\r\n  /* calls during glyph loading.                                           */\r\n  /*                                                                       */\r\n#define T1_MAX_SUBRS_CALLS  16\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* T1_MAX_CHARSTRING_OPERANDS is the charstring stack's capacity.  A     */\r\n  /* minimum of 16 is required.                                            */\r\n  /*                                                                       */\r\n  /* The Chinese font MingTiEG-Medium (CNS 11643 character set) needs 256. */\r\n  /*                                                                       */\r\n#define T1_MAX_CHARSTRINGS_OPERANDS  256\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Define this configuration macro if you want to prevent the            */\r\n  /* compilation of `t1afm', which is in charge of reading Type 1 AFM      */\r\n  /* files into an existing face.  Note that if set, the T1 driver will be */\r\n  /* unable to produce kerning distances.                                  */\r\n  /*                                                                       */\r\n#undef T1_CONFIG_OPTION_NO_AFM\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Define this configuration macro if you want to prevent the            */\r\n  /* compilation of the Multiple Masters font support in the Type 1        */\r\n  /* driver.                                                               */\r\n  /*                                                                       */\r\n#undef T1_CONFIG_OPTION_NO_MM_SUPPORT\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /****                                                                 ****/\r\n  /****    A U T O F I T   M O D U L E    C O N F I G U R A T I O N     ****/\r\n  /****                                                                 ****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Compile autofit module with CJK (Chinese, Japanese, Korean) script    */\r\n  /* support.                                                              */\r\n  /*                                                                       */\r\n#define AF_CONFIG_OPTION_CJK\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Compile autofit module with Indic script support.                     */\r\n  /*                                                                       */\r\n#define AF_CONFIG_OPTION_INDIC\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Compile autofit module with warp hinting.  The idea of the warping    */\r\n  /* code is to slightly scale and shift a glyph within a single dimension */\r\n  /* so that as much of its segments are aligned (more or less) on the     */\r\n  /* grid.  To find out the optimal scaling and shifting value, various    */\r\n  /* parameter combinations are tried and scored.                          */\r\n  /*                                                                       */\r\n  /* This experimental option is only active if the render mode is         */\r\n  /* FT_RENDER_MODE_LIGHT.                                                 */\r\n  /*                                                                       */\r\n/* #define AF_CONFIG_OPTION_USE_WARPER */\r\n\r\n  /* */\r\n\r\n\r\n  /*\r\n   * Define this variable if you want to keep the layout of internal\r\n   * structures that was used prior to FreeType 2.2.  This also compiles in\r\n   * a few obsolete functions to avoid linking problems on typical Unix\r\n   * distributions.\r\n   *\r\n   * For embedded systems or building a new distribution from scratch, it\r\n   * is recommended to disable the macro since it reduces the library's code\r\n   * size and activates a few memory-saving optimizations as well.\r\n   */\r\n#define FT_CONFIG_OPTION_OLD_INTERNALS\r\n\r\n\r\n  /*\r\n   *  To detect legacy cache-lookup call from a rogue client (<= 2.1.7),\r\n   *  we restrict the number of charmaps in a font.  The current API of\r\n   *  FTC_CMapCache_Lookup() takes cmap_index & charcode, but old API\r\n   *  takes charcode only.  To determine the passed value is for cmap_index\r\n   *  or charcode, the possible cmap_index is restricted not to exceed\r\n   *  the minimum possible charcode by a rogue client.  It is also very\r\n   *  unlikely that a rogue client is interested in Unicode values 0 to 15.\r\n   *\r\n   *  NOTE: The original threshold was 4 deduced from popular number of\r\n   *        cmap subtables in UCS-4 TrueType fonts, but now it is not\r\n   *        irregular for OpenType fonts to have more than 4 subtables,\r\n   *        because variation selector subtables are available for Apple\r\n   *        and Microsoft platforms.\r\n   */\r\n\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n#define FT_MAX_CHARMAP_CACHEABLE 15\r\n#endif\r\n\r\n\r\n  /*\r\n   * This macro is defined if either unpatented or native TrueType\r\n   * hinting is requested by the definitions above.\r\n   */\r\n#ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER\r\n#define  TT_USE_BYTECODE_INTERPRETER\r\n#undef   TT_CONFIG_OPTION_UNPATENTED_HINTING\r\n#elif defined TT_CONFIG_OPTION_UNPATENTED_HINTING\r\n#define  TT_USE_BYTECODE_INTERPRETER\r\n#endif\r\n\r\nFT_END_HEADER\r\n\r\n\r\n#endif /* __FTOPTION_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/config/ftstdlib.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftstdlib.h                                                             */\r\n/*                                                                         */\r\n/*    ANSI-specific library and header configuration file (specification   */\r\n/*    only).                                                               */\r\n/*                                                                         */\r\n/*  Copyright 2002-2007, 2009, 2011 by                                     */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* This file is used to group all #includes to the ANSI C library that   */\r\n  /* FreeType normally requires.  It also defines macros to rename the     */\r\n  /* standard functions within the FreeType source code.                   */\r\n  /*                                                                       */\r\n  /* Load a file which defines __FTSTDLIB_H__ before this one to override  */\r\n  /* it.                                                                   */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n#ifndef __FTSTDLIB_H__\r\n#define __FTSTDLIB_H__\r\n\r\n\r\n#include <stddef.h>\r\n\r\n#define ft_ptrdiff_t  ptrdiff_t\r\n\r\n\r\n  /**********************************************************************/\r\n  /*                                                                    */\r\n  /*                           integer limits                           */\r\n  /*                                                                    */\r\n  /* UINT_MAX and ULONG_MAX are used to automatically compute the size  */\r\n  /* of `int' and `long' in bytes at compile-time.  So far, this works  */\r\n  /* for all platforms the library has been tested on.                  */\r\n  /*                                                                    */\r\n  /* Note that on the extremely rare platforms that do not provide      */\r\n  /* integer types that are _exactly_ 16 and 32 bits wide (e.g. some    */\r\n  /* old Crays where `int' is 36 bits), we do not make any guarantee    */\r\n  /* about the correct behaviour of FT2 with all fonts.                 */\r\n  /*                                                                    */\r\n  /* In these case, `ftconfig.h' will refuse to compile anyway with a   */\r\n  /* message like `couldn't find 32-bit type' or something similar.     */\r\n  /*                                                                    */\r\n  /**********************************************************************/\r\n\r\n\r\n#include <limits.h>\r\n\r\n#define FT_CHAR_BIT    CHAR_BIT\r\n#define FT_USHORT_MAX  USHRT_MAX\r\n#define FT_INT_MAX     INT_MAX\r\n#define FT_INT_MIN     INT_MIN\r\n#define FT_UINT_MAX    UINT_MAX\r\n#define FT_ULONG_MAX   ULONG_MAX\r\n\r\n\r\n  /**********************************************************************/\r\n  /*                                                                    */\r\n  /*                 character and string processing                    */\r\n  /*                                                                    */\r\n  /**********************************************************************/\r\n\r\n\r\n#include <string.h>\r\n\r\n#define ft_memchr   memchr\r\n#define ft_memcmp   memcmp\r\n#define ft_memcpy   memcpy\r\n#define ft_memmove  memmove\r\n#define ft_memset   memset\r\n#define ft_strcat   strcat\r\n#define ft_strcmp   strcmp\r\n#define ft_strcpy   strcpy\r\n#define ft_strlen   strlen\r\n#define ft_strncmp  strncmp\r\n#define ft_strncpy  strncpy\r\n#define ft_strrchr  strrchr\r\n#define ft_strstr   strstr\r\n\r\n\r\n  /**********************************************************************/\r\n  /*                                                                    */\r\n  /*                           file handling                            */\r\n  /*                                                                    */\r\n  /**********************************************************************/\r\n\r\n\r\n#include <stdio.h>\r\n\r\n#define FT_FILE     FILE\r\n#define ft_fclose   fclose\r\n#define ft_fopen    fopen\r\n#define ft_fread    fread\r\n#define ft_fseek    fseek\r\n#define ft_ftell    ftell\r\n#define ft_sprintf  sprintf\r\n\r\n\r\n  /**********************************************************************/\r\n  /*                                                                    */\r\n  /*                             sorting                                */\r\n  /*                                                                    */\r\n  /**********************************************************************/\r\n\r\n\r\n#include <stdlib.h>\r\n\r\n#define ft_qsort  qsort\r\n\r\n\r\n  /**********************************************************************/\r\n  /*                                                                    */\r\n  /*                        memory allocation                           */\r\n  /*                                                                    */\r\n  /**********************************************************************/\r\n\r\n\r\n#define ft_scalloc   calloc\r\n#define ft_sfree     free\r\n#define ft_smalloc   malloc\r\n#define ft_srealloc  realloc\r\n\r\n\r\n  /**********************************************************************/\r\n  /*                                                                    */\r\n  /*                          miscellaneous                             */\r\n  /*                                                                    */\r\n  /**********************************************************************/\r\n\r\n\r\n#define ft_atol   atol\r\n#define ft_labs   labs\r\n\r\n\r\n  /**********************************************************************/\r\n  /*                                                                    */\r\n  /*                         execution control                          */\r\n  /*                                                                    */\r\n  /**********************************************************************/\r\n\r\n\r\n#include <setjmp.h>\r\n\r\n#define ft_jmp_buf     jmp_buf  /* note: this cannot be a typedef since */\r\n                                /*       jmp_buf is defined as a macro  */\r\n                                /*       on certain platforms           */\r\n\r\n#define ft_longjmp     longjmp\r\n#define ft_setjmp( b ) setjmp( *(jmp_buf*) &(b) )    /* same thing here */\r\n\r\n\r\n  /* the following is only used for debugging purposes, i.e., if */\r\n  /* FT_DEBUG_LEVEL_ERROR or FT_DEBUG_LEVEL_TRACE are defined    */\r\n\r\n#include <stdarg.h>\r\n\r\n\r\n#endif /* __FTSTDLIB_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/freetype.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  freetype.h                                                             */\r\n/*                                                                         */\r\n/*    FreeType high-level API and common types (specification only).       */\r\n/*                                                                         */\r\n/*  Copyright 1996-2011 by                                                 */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef FT_FREETYPE_H\r\n#error \"`ft2build.h' hasn't been included yet!\"\r\n#error \"Please always use macros to include FreeType header files.\"\r\n#error \"Example:\"\r\n#error \"  #include <ft2build.h>\"\r\n#error \"  #include FT_FREETYPE_H\"\r\n#endif\r\n\r\n\r\n#ifndef __FREETYPE_H__\r\n#define __FREETYPE_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_CONFIG_CONFIG_H\r\n#include FT_ERRORS_H\r\n#include FT_TYPES_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    user_allocation                                                    */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    User allocation                                                    */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    How client applications should allocate FreeType data structures.  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    FreeType assumes that structures allocated by the user and passed  */\r\n  /*    as arguments are zeroed out except for the actual data.  In other  */\r\n  /*    words, it is recommended to use `calloc' (or variants of it)       */\r\n  /*    instead of `malloc' for allocation.                                */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /*                        B A S I C   T Y P E S                          */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    base_interface                                                     */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    Base Interface                                                     */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    The FreeType~2 base font interface.                                */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This section describes the public high-level API of FreeType~2.    */\r\n  /*                                                                       */\r\n  /* <Order>                                                               */\r\n  /*    FT_Library                                                         */\r\n  /*    FT_Face                                                            */\r\n  /*    FT_Size                                                            */\r\n  /*    FT_GlyphSlot                                                       */\r\n  /*    FT_CharMap                                                         */\r\n  /*    FT_Encoding                                                        */\r\n  /*                                                                       */\r\n  /*    FT_FaceRec                                                         */\r\n  /*                                                                       */\r\n  /*    FT_FACE_FLAG_SCALABLE                                              */\r\n  /*    FT_FACE_FLAG_FIXED_SIZES                                           */\r\n  /*    FT_FACE_FLAG_FIXED_WIDTH                                           */\r\n  /*    FT_FACE_FLAG_HORIZONTAL                                            */\r\n  /*    FT_FACE_FLAG_VERTICAL                                              */\r\n  /*    FT_FACE_FLAG_SFNT                                                  */\r\n  /*    FT_FACE_FLAG_KERNING                                               */\r\n  /*    FT_FACE_FLAG_MULTIPLE_MASTERS                                      */\r\n  /*    FT_FACE_FLAG_GLYPH_NAMES                                           */\r\n  /*    FT_FACE_FLAG_EXTERNAL_STREAM                                       */\r\n  /*    FT_FACE_FLAG_FAST_GLYPHS                                           */\r\n  /*    FT_FACE_FLAG_HINTER                                                */\r\n  /*                                                                       */\r\n  /*    FT_STYLE_FLAG_BOLD                                                 */\r\n  /*    FT_STYLE_FLAG_ITALIC                                               */\r\n  /*                                                                       */\r\n  /*    FT_SizeRec                                                         */\r\n  /*    FT_Size_Metrics                                                    */\r\n  /*                                                                       */\r\n  /*    FT_GlyphSlotRec                                                    */\r\n  /*    FT_Glyph_Metrics                                                   */\r\n  /*    FT_SubGlyph                                                        */\r\n  /*                                                                       */\r\n  /*    FT_Bitmap_Size                                                     */\r\n  /*                                                                       */\r\n  /*    FT_Init_FreeType                                                   */\r\n  /*    FT_Done_FreeType                                                   */\r\n  /*                                                                       */\r\n  /*    FT_New_Face                                                        */\r\n  /*    FT_Done_Face                                                       */\r\n  /*    FT_New_Memory_Face                                                 */\r\n  /*    FT_Open_Face                                                       */\r\n  /*    FT_Open_Args                                                       */\r\n  /*    FT_Parameter                                                       */\r\n  /*    FT_Attach_File                                                     */\r\n  /*    FT_Attach_Stream                                                   */\r\n  /*                                                                       */\r\n  /*    FT_Set_Char_Size                                                   */\r\n  /*    FT_Set_Pixel_Sizes                                                 */\r\n  /*    FT_Request_Size                                                    */\r\n  /*    FT_Select_Size                                                     */\r\n  /*    FT_Size_Request_Type                                               */\r\n  /*    FT_Size_Request                                                    */\r\n  /*    FT_Set_Transform                                                   */\r\n  /*    FT_Load_Glyph                                                      */\r\n  /*    FT_Get_Char_Index                                                  */\r\n  /*    FT_Get_Name_Index                                                  */\r\n  /*    FT_Load_Char                                                       */\r\n  /*                                                                       */\r\n  /*    FT_OPEN_MEMORY                                                     */\r\n  /*    FT_OPEN_STREAM                                                     */\r\n  /*    FT_OPEN_PATHNAME                                                   */\r\n  /*    FT_OPEN_DRIVER                                                     */\r\n  /*    FT_OPEN_PARAMS                                                     */\r\n  /*                                                                       */\r\n  /*    FT_LOAD_DEFAULT                                                    */\r\n  /*    FT_LOAD_RENDER                                                     */\r\n  /*    FT_LOAD_MONOCHROME                                                 */\r\n  /*    FT_LOAD_LINEAR_DESIGN                                              */\r\n  /*    FT_LOAD_NO_SCALE                                                   */\r\n  /*    FT_LOAD_NO_HINTING                                                 */\r\n  /*    FT_LOAD_NO_BITMAP                                                  */\r\n  /*    FT_LOAD_CROP_BITMAP                                                */\r\n  /*                                                                       */\r\n  /*    FT_LOAD_VERTICAL_LAYOUT                                            */\r\n  /*    FT_LOAD_IGNORE_TRANSFORM                                           */\r\n  /*    FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH                                */\r\n  /*    FT_LOAD_FORCE_AUTOHINT                                             */\r\n  /*    FT_LOAD_NO_RECURSE                                                 */\r\n  /*    FT_LOAD_PEDANTIC                                                   */\r\n  /*                                                                       */\r\n  /*    FT_LOAD_TARGET_NORMAL                                              */\r\n  /*    FT_LOAD_TARGET_LIGHT                                               */\r\n  /*    FT_LOAD_TARGET_MONO                                                */\r\n  /*    FT_LOAD_TARGET_LCD                                                 */\r\n  /*    FT_LOAD_TARGET_LCD_V                                               */\r\n  /*                                                                       */\r\n  /*    FT_Render_Glyph                                                    */\r\n  /*    FT_Render_Mode                                                     */\r\n  /*    FT_Get_Kerning                                                     */\r\n  /*    FT_Kerning_Mode                                                    */\r\n  /*    FT_Get_Track_Kerning                                               */\r\n  /*    FT_Get_Glyph_Name                                                  */\r\n  /*    FT_Get_Postscript_Name                                             */\r\n  /*                                                                       */\r\n  /*    FT_CharMapRec                                                      */\r\n  /*    FT_Select_Charmap                                                  */\r\n  /*    FT_Set_Charmap                                                     */\r\n  /*    FT_Get_Charmap_Index                                               */\r\n  /*                                                                       */\r\n  /*    FT_FSTYPE_INSTALLABLE_EMBEDDING                                    */\r\n  /*    FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING                             */\r\n  /*    FT_FSTYPE_PREVIEW_AND_PRINT_EMBEDDING                              */\r\n  /*    FT_FSTYPE_EDITABLE_EMBEDDING                                       */\r\n  /*    FT_FSTYPE_NO_SUBSETTING                                            */\r\n  /*    FT_FSTYPE_BITMAP_EMBEDDING_ONLY                                    */\r\n  /*                                                                       */\r\n  /*    FT_Get_FSType_Flags                                                */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Glyph_Metrics                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to model the metrics of a single glyph.  The      */\r\n  /*    values are expressed in 26.6 fractional pixel format; if the flag  */\r\n  /*    @FT_LOAD_NO_SCALE has been used while loading the glyph, values    */\r\n  /*    are expressed in font units instead.                               */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    width ::                                                           */\r\n  /*      The glyph's width.                                               */\r\n  /*                                                                       */\r\n  /*    height ::                                                          */\r\n  /*      The glyph's height.                                              */\r\n  /*                                                                       */\r\n  /*    horiBearingX ::                                                    */\r\n  /*      Left side bearing for horizontal layout.                         */\r\n  /*                                                                       */\r\n  /*    horiBearingY ::                                                    */\r\n  /*      Top side bearing for horizontal layout.                          */\r\n  /*                                                                       */\r\n  /*    horiAdvance ::                                                     */\r\n  /*      Advance width for horizontal layout.                             */\r\n  /*                                                                       */\r\n  /*    vertBearingX ::                                                    */\r\n  /*      Left side bearing for vertical layout.                           */\r\n  /*                                                                       */\r\n  /*    vertBearingY ::                                                    */\r\n  /*      Top side bearing for vertical layout.  Larger positive values    */\r\n  /*      mean further below the vertical glyph origin.                    */\r\n  /*                                                                       */\r\n  /*    vertAdvance ::                                                     */\r\n  /*      Advance height for vertical layout.  Positive values mean the    */\r\n  /*      glyph has a positive advance downward.                           */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    If not disabled with @FT_LOAD_NO_HINTING, the values represent     */\r\n  /*    dimensions of the hinted glyph (in case hinting is applicable).    */\r\n  /*                                                                       */\r\n  typedef struct  FT_Glyph_Metrics_\r\n  {\r\n    FT_Pos  width;\r\n    FT_Pos  height;\r\n\r\n    FT_Pos  horiBearingX;\r\n    FT_Pos  horiBearingY;\r\n    FT_Pos  horiAdvance;\r\n\r\n    FT_Pos  vertBearingX;\r\n    FT_Pos  vertBearingY;\r\n    FT_Pos  vertAdvance;\r\n\r\n  } FT_Glyph_Metrics;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Bitmap_Size                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This structure models the metrics of a bitmap strike (i.e., a set  */\r\n  /*    of glyphs for a given point size and resolution) in a bitmap font. */\r\n  /*    It is used for the `available_sizes' field of @FT_Face.            */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    height :: The vertical distance, in pixels, between two            */\r\n  /*              consecutive baselines.  It is always positive.           */\r\n  /*                                                                       */\r\n  /*    width  :: The average width, in pixels, of all glyphs in the       */\r\n  /*              strike.                                                  */\r\n  /*                                                                       */\r\n  /*    size   :: The nominal size of the strike in 26.6 fractional        */\r\n  /*              points.  This field is not very useful.                  */\r\n  /*                                                                       */\r\n  /*    x_ppem :: The horizontal ppem (nominal width) in 26.6 fractional   */\r\n  /*              pixels.                                                  */\r\n  /*                                                                       */\r\n  /*    y_ppem :: The vertical ppem (nominal height) in 26.6 fractional    */\r\n  /*              pixels.                                                  */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    Windows FNT:                                                       */\r\n  /*      The nominal size given in a FNT font is not reliable.  Thus when */\r\n  /*      the driver finds it incorrect, it sets `size' to some calculated */\r\n  /*      values and sets `x_ppem' and `y_ppem' to the pixel width and     */\r\n  /*      height given in the font, respectively.                          */\r\n  /*                                                                       */\r\n  /*    TrueType embedded bitmaps:                                         */\r\n  /*      `size', `width', and `height' values are not contained in the    */\r\n  /*      bitmap strike itself.  They are computed from the global font    */\r\n  /*      parameters.                                                      */\r\n  /*                                                                       */\r\n  typedef struct  FT_Bitmap_Size_\r\n  {\r\n    FT_Short  height;\r\n    FT_Short  width;\r\n\r\n    FT_Pos    size;\r\n\r\n    FT_Pos    x_ppem;\r\n    FT_Pos    y_ppem;\r\n\r\n  } FT_Bitmap_Size;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /*                     O B J E C T   C L A S S E S                       */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Library                                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle to a FreeType library instance.  Each `library' is        */\r\n  /*    completely independent from the others; it is the `root' of a set  */\r\n  /*    of objects like fonts, faces, sizes, etc.                          */\r\n  /*                                                                       */\r\n  /*    It also embeds a memory manager (see @FT_Memory), as well as a     */\r\n  /*    scan-line converter object (see @FT_Raster).                       */\r\n  /*                                                                       */\r\n  /*    For multi-threading applications each thread should have its own   */\r\n  /*    FT_Library object.                                                 */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    Library objects are normally created by @FT_Init_FreeType, and     */\r\n  /*    destroyed with @FT_Done_FreeType.                                  */\r\n  /*                                                                       */\r\n  typedef struct FT_LibraryRec_  *FT_Library;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Module                                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle to a given FreeType module object.  Each module can be a  */\r\n  /*    font driver, a renderer, or anything else that provides services   */\r\n  /*    to the formers.                                                    */\r\n  /*                                                                       */\r\n  typedef struct FT_ModuleRec_*  FT_Module;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Driver                                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle to a given FreeType font driver object.  Each font driver */\r\n  /*    is a special module capable of creating faces from font files.     */\r\n  /*                                                                       */\r\n  typedef struct FT_DriverRec_*  FT_Driver;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Renderer                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle to a given FreeType renderer.  A renderer is a special    */\r\n  /*    module in charge of converting a glyph image to a bitmap, when     */\r\n  /*    necessary.  Each renderer supports a given glyph image format, and */\r\n  /*    one or more target surface depths.                                 */\r\n  /*                                                                       */\r\n  typedef struct FT_RendererRec_*  FT_Renderer;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Face                                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle to a given typographic face object.  A face object models */\r\n  /*    a given typeface, in a given style.                                */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    Each face object also owns a single @FT_GlyphSlot object, as well  */\r\n  /*    as one or more @FT_Size objects.                                   */\r\n  /*                                                                       */\r\n  /*    Use @FT_New_Face or @FT_Open_Face to create a new face object from */\r\n  /*    a given filepathname or a custom input stream.                     */\r\n  /*                                                                       */\r\n  /*    Use @FT_Done_Face to destroy it (along with its slot and sizes).   */\r\n  /*                                                                       */\r\n  /* <Also>                                                                */\r\n  /*    See @FT_FaceRec for the publicly accessible fields of a given face */\r\n  /*    object.                                                            */\r\n  /*                                                                       */\r\n  typedef struct FT_FaceRec_*  FT_Face;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Size                                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle to an object used to model a face scaled to a given       */\r\n  /*    character size.                                                    */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    Each @FT_Face has an _active_ @FT_Size object that is used by      */\r\n  /*    functions like @FT_Load_Glyph to determine the scaling             */\r\n  /*    transformation which is used to load and hint glyphs and metrics.  */\r\n  /*                                                                       */\r\n  /*    You can use @FT_Set_Char_Size, @FT_Set_Pixel_Sizes,                */\r\n  /*    @FT_Request_Size or even @FT_Select_Size to change the content     */\r\n  /*    (i.e., the scaling values) of the active @FT_Size.                 */\r\n  /*                                                                       */\r\n  /*    You can use @FT_New_Size to create additional size objects for a   */\r\n  /*    given @FT_Face, but they won't be used by other functions until    */\r\n  /*    you activate it through @FT_Activate_Size.  Only one size can be   */\r\n  /*    activated at any given time per face.                              */\r\n  /*                                                                       */\r\n  /* <Also>                                                                */\r\n  /*    See @FT_SizeRec for the publicly accessible fields of a given size */\r\n  /*    object.                                                            */\r\n  /*                                                                       */\r\n  typedef struct FT_SizeRec_*  FT_Size;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_GlyphSlot                                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle to a given `glyph slot'.  A slot is a container where it  */\r\n  /*    is possible to load any of the glyphs contained in its parent      */\r\n  /*    face.                                                              */\r\n  /*                                                                       */\r\n  /*    In other words, each time you call @FT_Load_Glyph or               */\r\n  /*    @FT_Load_Char, the slot's content is erased by the new glyph data, */\r\n  /*    i.e., the glyph's metrics, its image (bitmap or outline), and      */\r\n  /*    other control information.                                         */\r\n  /*                                                                       */\r\n  /* <Also>                                                                */\r\n  /*    See @FT_GlyphSlotRec for the publicly accessible glyph fields.     */\r\n  /*                                                                       */\r\n  typedef struct FT_GlyphSlotRec_*  FT_GlyphSlot;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_CharMap                                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle to a given character map.  A charmap is used to translate */\r\n  /*    character codes in a given encoding into glyph indexes for its     */\r\n  /*    parent's face.  Some font formats may provide several charmaps per */\r\n  /*    font.                                                              */\r\n  /*                                                                       */\r\n  /*    Each face object owns zero or more charmaps, but only one of them  */\r\n  /*    can be `active' and used by @FT_Get_Char_Index or @FT_Load_Char.   */\r\n  /*                                                                       */\r\n  /*    The list of available charmaps in a face is available through the  */\r\n  /*    `face->num_charmaps' and `face->charmaps' fields of @FT_FaceRec.   */\r\n  /*                                                                       */\r\n  /*    The currently active charmap is available as `face->charmap'.      */\r\n  /*    You should call @FT_Set_Charmap to change it.                      */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    When a new face is created (either through @FT_New_Face or         */\r\n  /*    @FT_Open_Face), the library looks for a Unicode charmap within     */\r\n  /*    the list and automatically activates it.                           */\r\n  /*                                                                       */\r\n  /* <Also>                                                                */\r\n  /*    See @FT_CharMapRec for the publicly accessible fields of a given   */\r\n  /*    character map.                                                     */\r\n  /*                                                                       */\r\n  typedef struct FT_CharMapRec_*  FT_CharMap;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Macro>                                                               */\r\n  /*    FT_ENC_TAG                                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This macro converts four-letter tags into an unsigned long.  It is */\r\n  /*    used to define `encoding' identifiers (see @FT_Encoding).          */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    Since many 16-bit compilers don't like 32-bit enumerations, you    */\r\n  /*    should redefine this macro in case of problems to something like   */\r\n  /*    this:                                                              */\r\n  /*                                                                       */\r\n  /*    {                                                                  */\r\n  /*      #define FT_ENC_TAG( value, a, b, c, d )  value                   */\r\n  /*    }                                                                  */\r\n  /*                                                                       */\r\n  /*    to get a simple enumeration without assigning special numbers.     */\r\n  /*                                                                       */\r\n\r\n#ifndef FT_ENC_TAG\r\n#define FT_ENC_TAG( value, a, b, c, d )         \\\r\n          value = ( ( (FT_UInt32)(a) << 24 ) |  \\\r\n                    ( (FT_UInt32)(b) << 16 ) |  \\\r\n                    ( (FT_UInt32)(c) <<  8 ) |  \\\r\n                      (FT_UInt32)(d)         )\r\n\r\n#endif /* FT_ENC_TAG */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Enum>                                                                */\r\n  /*    FT_Encoding                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    An enumeration used to specify character sets supported by         */\r\n  /*    charmaps.  Used in the @FT_Select_Charmap API function.            */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    Despite the name, this enumeration lists specific character        */\r\n  /*    repertories (i.e., charsets), and not text encoding methods (e.g., */\r\n  /*    UTF-8, UTF-16, etc.).                                              */\r\n  /*                                                                       */\r\n  /*    Other encodings might be defined in the future.                    */\r\n  /*                                                                       */\r\n  /* <Values>                                                              */\r\n  /*    FT_ENCODING_NONE ::                                                */\r\n  /*      The encoding value~0 is reserved.                                */\r\n  /*                                                                       */\r\n  /*    FT_ENCODING_UNICODE ::                                             */\r\n  /*      Corresponds to the Unicode character set.  This value covers     */\r\n  /*      all versions of the Unicode repertoire, including ASCII and      */\r\n  /*      Latin-1.  Most fonts include a Unicode charmap, but not all      */\r\n  /*      of them.                                                         */\r\n  /*                                                                       */\r\n  /*      For example, if you want to access Unicode value U+1F028 (and    */\r\n  /*      the font contains it), use value 0x1F028 as the input value for  */\r\n  /*      @FT_Get_Char_Index.                                              */\r\n  /*                                                                       */\r\n  /*    FT_ENCODING_MS_SYMBOL ::                                           */\r\n  /*      Corresponds to the Microsoft Symbol encoding, used to encode     */\r\n  /*      mathematical symbols in the 32..255 character code range.  For   */\r\n  /*      more information, see `http://www.ceviz.net/symbol.htm'.         */\r\n  /*                                                                       */\r\n  /*    FT_ENCODING_SJIS ::                                                */\r\n  /*      Corresponds to Japanese SJIS encoding.  More info at             */\r\n  /*      at `http://langsupport.japanreference.com/encoding.shtml'.       */\r\n  /*      See note on multi-byte encodings below.                          */\r\n  /*                                                                       */\r\n  /*    FT_ENCODING_GB2312 ::                                              */\r\n  /*      Corresponds to an encoding system for Simplified Chinese as used */\r\n  /*      used in mainland China.                                          */\r\n  /*                                                                       */\r\n  /*    FT_ENCODING_BIG5 ::                                                */\r\n  /*      Corresponds to an encoding system for Traditional Chinese as     */\r\n  /*      used in Taiwan and Hong Kong.                                    */\r\n  /*                                                                       */\r\n  /*    FT_ENCODING_WANSUNG ::                                             */\r\n  /*      Corresponds to the Korean encoding system known as Wansung.      */\r\n  /*      For more information see                                         */\r\n  /*      `http://www.microsoft.com/typography/unicode/949.txt'.           */\r\n  /*                                                                       */\r\n  /*    FT_ENCODING_JOHAB ::                                               */\r\n  /*      The Korean standard character set (KS~C 5601-1992), which        */\r\n  /*      corresponds to MS Windows code page 1361.  This character set    */\r\n  /*      includes all possible Hangeul character combinations.            */\r\n  /*                                                                       */\r\n  /*    FT_ENCODING_ADOBE_LATIN_1 ::                                       */\r\n  /*      Corresponds to a Latin-1 encoding as defined in a Type~1         */\r\n  /*      PostScript font.  It is limited to 256 character codes.          */\r\n  /*                                                                       */\r\n  /*    FT_ENCODING_ADOBE_STANDARD ::                                      */\r\n  /*      Corresponds to the Adobe Standard encoding, as found in Type~1,  */\r\n  /*      CFF, and OpenType/CFF fonts.  It is limited to 256 character     */\r\n  /*      codes.                                                           */\r\n  /*                                                                       */\r\n  /*    FT_ENCODING_ADOBE_EXPERT ::                                        */\r\n  /*      Corresponds to the Adobe Expert encoding, as found in Type~1,    */\r\n  /*      CFF, and OpenType/CFF fonts.  It is limited to 256 character     */\r\n  /*      codes.                                                           */\r\n  /*                                                                       */\r\n  /*    FT_ENCODING_ADOBE_CUSTOM ::                                        */\r\n  /*      Corresponds to a custom encoding, as found in Type~1, CFF, and   */\r\n  /*      OpenType/CFF fonts.  It is limited to 256 character codes.       */\r\n  /*                                                                       */\r\n  /*    FT_ENCODING_APPLE_ROMAN ::                                         */\r\n  /*      Corresponds to the 8-bit Apple roman encoding.  Many TrueType    */\r\n  /*      and OpenType fonts contain a charmap for this encoding, since    */\r\n  /*      older versions of Mac OS are able to use it.                     */\r\n  /*                                                                       */\r\n  /*    FT_ENCODING_OLD_LATIN_2 ::                                         */\r\n  /*      This value is deprecated and was never used nor reported by      */\r\n  /*      FreeType.  Don't use or test for it.                             */\r\n  /*                                                                       */\r\n  /*    FT_ENCODING_MS_SJIS ::                                             */\r\n  /*      Same as FT_ENCODING_SJIS.  Deprecated.                           */\r\n  /*                                                                       */\r\n  /*    FT_ENCODING_MS_GB2312 ::                                           */\r\n  /*      Same as FT_ENCODING_GB2312.  Deprecated.                         */\r\n  /*                                                                       */\r\n  /*    FT_ENCODING_MS_BIG5 ::                                             */\r\n  /*      Same as FT_ENCODING_BIG5.  Deprecated.                           */\r\n  /*                                                                       */\r\n  /*    FT_ENCODING_MS_WANSUNG ::                                          */\r\n  /*      Same as FT_ENCODING_WANSUNG.  Deprecated.                        */\r\n  /*                                                                       */\r\n  /*    FT_ENCODING_MS_JOHAB ::                                            */\r\n  /*      Same as FT_ENCODING_JOHAB.  Deprecated.                          */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    By default, FreeType automatically synthesizes a Unicode charmap   */\r\n  /*    for PostScript fonts, using their glyph names dictionaries.        */\r\n  /*    However, it also reports the encodings defined explicitly in the   */\r\n  /*    font file, for the cases when they are needed, with the Adobe      */\r\n  /*    values as well.                                                    */\r\n  /*                                                                       */\r\n  /*    FT_ENCODING_NONE is set by the BDF and PCF drivers if the charmap  */\r\n  /*    is neither Unicode nor ISO-8859-1 (otherwise it is set to          */\r\n  /*    FT_ENCODING_UNICODE).  Use @FT_Get_BDF_Charset_ID to find out      */\r\n  /*    which encoding is really present.  If, for example, the            */\r\n  /*    `cs_registry' field is `KOI8' and the `cs_encoding' field is `R',  */\r\n  /*    the font is encoded in KOI8-R.                                     */\r\n  /*                                                                       */\r\n  /*    FT_ENCODING_NONE is always set (with a single exception) by the    */\r\n  /*    winfonts driver.  Use @FT_Get_WinFNT_Header and examine the        */\r\n  /*    `charset' field of the @FT_WinFNT_HeaderRec structure to find out  */\r\n  /*    which encoding is really present.  For example,                    */\r\n  /*    @FT_WinFNT_ID_CP1251 (204) means Windows code page 1251 (for       */\r\n  /*    Russian).                                                          */\r\n  /*                                                                       */\r\n  /*    FT_ENCODING_NONE is set if `platform_id' is @TT_PLATFORM_MACINTOSH */\r\n  /*    and `encoding_id' is not @TT_MAC_ID_ROMAN (otherwise it is set to  */\r\n  /*    FT_ENCODING_APPLE_ROMAN).                                          */\r\n  /*                                                                       */\r\n  /*    If `platform_id' is @TT_PLATFORM_MACINTOSH, use the function       */\r\n  /*    @FT_Get_CMap_Language_ID  to query the Mac language ID which may   */\r\n  /*    be needed to be able to distinguish Apple encoding variants.  See  */\r\n  /*                                                                       */\r\n  /*      http://www.unicode.org/Public/MAPPINGS/VENDORS/APPLE/README.TXT  */\r\n  /*                                                                       */\r\n  /*    to get an idea how to do that.  Basically, if the language ID      */\r\n  /*    is~0, don't use it, otherwise subtract 1 from the language ID.     */\r\n  /*    Then examine `encoding_id'.  If, for example, `encoding_id' is     */\r\n  /*    @TT_MAC_ID_ROMAN and the language ID (minus~1) is                  */\r\n  /*    `TT_MAC_LANGID_GREEK', it is the Greek encoding, not Roman.        */\r\n  /*    @TT_MAC_ID_ARABIC with `TT_MAC_LANGID_FARSI' means the Farsi       */\r\n  /*    variant the Arabic encoding.                                       */\r\n  /*                                                                       */\r\n  typedef enum  FT_Encoding_\r\n  {\r\n    FT_ENC_TAG( FT_ENCODING_NONE, 0, 0, 0, 0 ),\r\n\r\n    FT_ENC_TAG( FT_ENCODING_MS_SYMBOL, 's', 'y', 'm', 'b' ),\r\n    FT_ENC_TAG( FT_ENCODING_UNICODE,   'u', 'n', 'i', 'c' ),\r\n\r\n    FT_ENC_TAG( FT_ENCODING_SJIS,    's', 'j', 'i', 's' ),\r\n    FT_ENC_TAG( FT_ENCODING_GB2312,  'g', 'b', ' ', ' ' ),\r\n    FT_ENC_TAG( FT_ENCODING_BIG5,    'b', 'i', 'g', '5' ),\r\n    FT_ENC_TAG( FT_ENCODING_WANSUNG, 'w', 'a', 'n', 's' ),\r\n    FT_ENC_TAG( FT_ENCODING_JOHAB,   'j', 'o', 'h', 'a' ),\r\n\r\n    /* for backwards compatibility */\r\n    FT_ENCODING_MS_SJIS    = FT_ENCODING_SJIS,\r\n    FT_ENCODING_MS_GB2312  = FT_ENCODING_GB2312,\r\n    FT_ENCODING_MS_BIG5    = FT_ENCODING_BIG5,\r\n    FT_ENCODING_MS_WANSUNG = FT_ENCODING_WANSUNG,\r\n    FT_ENCODING_MS_JOHAB   = FT_ENCODING_JOHAB,\r\n\r\n    FT_ENC_TAG( FT_ENCODING_ADOBE_STANDARD, 'A', 'D', 'O', 'B' ),\r\n    FT_ENC_TAG( FT_ENCODING_ADOBE_EXPERT,   'A', 'D', 'B', 'E' ),\r\n    FT_ENC_TAG( FT_ENCODING_ADOBE_CUSTOM,   'A', 'D', 'B', 'C' ),\r\n    FT_ENC_TAG( FT_ENCODING_ADOBE_LATIN_1,  'l', 'a', 't', '1' ),\r\n\r\n    FT_ENC_TAG( FT_ENCODING_OLD_LATIN_2, 'l', 'a', 't', '2' ),\r\n\r\n    FT_ENC_TAG( FT_ENCODING_APPLE_ROMAN, 'a', 'r', 'm', 'n' )\r\n\r\n  } FT_Encoding;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Enum>                                                                */\r\n  /*    ft_encoding_xxx                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    These constants are deprecated; use the corresponding @FT_Encoding */\r\n  /*    values instead.                                                    */\r\n  /*                                                                       */\r\n#define ft_encoding_none            FT_ENCODING_NONE\r\n#define ft_encoding_unicode         FT_ENCODING_UNICODE\r\n#define ft_encoding_symbol          FT_ENCODING_MS_SYMBOL\r\n#define ft_encoding_latin_1         FT_ENCODING_ADOBE_LATIN_1\r\n#define ft_encoding_latin_2         FT_ENCODING_OLD_LATIN_2\r\n#define ft_encoding_sjis            FT_ENCODING_SJIS\r\n#define ft_encoding_gb2312          FT_ENCODING_GB2312\r\n#define ft_encoding_big5            FT_ENCODING_BIG5\r\n#define ft_encoding_wansung         FT_ENCODING_WANSUNG\r\n#define ft_encoding_johab           FT_ENCODING_JOHAB\r\n\r\n#define ft_encoding_adobe_standard  FT_ENCODING_ADOBE_STANDARD\r\n#define ft_encoding_adobe_expert    FT_ENCODING_ADOBE_EXPERT\r\n#define ft_encoding_adobe_custom    FT_ENCODING_ADOBE_CUSTOM\r\n#define ft_encoding_apple_roman     FT_ENCODING_APPLE_ROMAN\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_CharMapRec                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    The base charmap structure.                                        */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    face        :: A handle to the parent face object.                 */\r\n  /*                                                                       */\r\n  /*    encoding    :: An @FT_Encoding tag identifying the charmap.  Use   */\r\n  /*                   this with @FT_Select_Charmap.                       */\r\n  /*                                                                       */\r\n  /*    platform_id :: An ID number describing the platform for the        */\r\n  /*                   following encoding ID.  This comes directly from    */\r\n  /*                   the TrueType specification and should be emulated   */\r\n  /*                   for other formats.                                  */\r\n  /*                                                                       */\r\n  /*    encoding_id :: A platform specific encoding number.  This also     */\r\n  /*                   comes from the TrueType specification and should be */\r\n  /*                   emulated similarly.                                 */\r\n  /*                                                                       */\r\n  typedef struct  FT_CharMapRec_\r\n  {\r\n    FT_Face      face;\r\n    FT_Encoding  encoding;\r\n    FT_UShort    platform_id;\r\n    FT_UShort    encoding_id;\r\n\r\n  } FT_CharMapRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /*                 B A S E   O B J E C T   C L A S S E S                 */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Face_Internal                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    An opaque handle to an `FT_Face_InternalRec' structure, used to    */\r\n  /*    model private data of a given @FT_Face object.                     */\r\n  /*                                                                       */\r\n  /*    This structure might change between releases of FreeType~2 and is  */\r\n  /*    not generally available to client applications.                    */\r\n  /*                                                                       */\r\n  typedef struct FT_Face_InternalRec_*  FT_Face_Internal;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_FaceRec                                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    FreeType root face class structure.  A face object models a        */\r\n  /*    typeface in a font file.                                           */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    num_faces           :: The number of faces in the font file.  Some */\r\n  /*                           font formats can have multiple faces in     */\r\n  /*                           a font file.                                */\r\n  /*                                                                       */\r\n  /*    face_index          :: The index of the face in the font file.  It */\r\n  /*                           is set to~0 if there is only one face in    */\r\n  /*                           the font file.                              */\r\n  /*                                                                       */\r\n  /*    face_flags          :: A set of bit flags that give important      */\r\n  /*                           information about the face; see             */\r\n  /*                           @FT_FACE_FLAG_XXX for the details.          */\r\n  /*                                                                       */\r\n  /*    style_flags         :: A set of bit flags indicating the style of  */\r\n  /*                           the face; see @FT_STYLE_FLAG_XXX for the    */\r\n  /*                           details.                                    */\r\n  /*                                                                       */\r\n  /*    num_glyphs          :: The number of glyphs in the face.  If the   */\r\n  /*                           face is scalable and has sbits (see         */\r\n  /*                           `num_fixed_sizes'), it is set to the number */\r\n  /*                           of outline glyphs.                          */\r\n  /*                                                                       */\r\n  /*                           For CID-keyed fonts, this value gives the   */\r\n  /*                           highest CID used in the font.               */\r\n  /*                                                                       */\r\n  /*    family_name         :: The face's family name.  This is an ASCII   */\r\n  /*                           string, usually in English, which describes */\r\n  /*                           the typeface's family (like `Times New      */\r\n  /*                           Roman', `Bodoni', `Garamond', etc).  This   */\r\n  /*                           is a least common denominator used to list  */\r\n  /*                           fonts.  Some formats (TrueType & OpenType)  */\r\n  /*                           provide localized and Unicode versions of   */\r\n  /*                           this string.  Applications should use the   */\r\n  /*                           format specific interface to access them.   */\r\n  /*                           Can be NULL (e.g., in fonts embedded in a   */\r\n  /*                           PDF file).                                  */\r\n  /*                                                                       */\r\n  /*    style_name          :: The face's style name.  This is an ASCII    */\r\n  /*                           string, usually in English, which describes */\r\n  /*                           the typeface's style (like `Italic',        */\r\n  /*                           `Bold', `Condensed', etc).  Not all font    */\r\n  /*                           formats provide a style name, so this field */\r\n  /*                           is optional, and can be set to NULL.  As    */\r\n  /*                           for `family_name', some formats provide     */\r\n  /*                           localized and Unicode versions of this      */\r\n  /*                           string.  Applications should use the format */\r\n  /*                           specific interface to access them.          */\r\n  /*                                                                       */\r\n  /*    num_fixed_sizes     :: The number of bitmap strikes in the face.   */\r\n  /*                           Even if the face is scalable, there might   */\r\n  /*                           still be bitmap strikes, which are called   */\r\n  /*                           `sbits' in that case.                       */\r\n  /*                                                                       */\r\n  /*    available_sizes     :: An array of @FT_Bitmap_Size for all bitmap  */\r\n  /*                           strikes in the face.  It is set to NULL if  */\r\n  /*                           there is no bitmap strike.                  */\r\n  /*                                                                       */\r\n  /*    num_charmaps        :: The number of charmaps in the face.         */\r\n  /*                                                                       */\r\n  /*    charmaps            :: An array of the charmaps of the face.       */\r\n  /*                                                                       */\r\n  /*    generic             :: A field reserved for client uses.  See the  */\r\n  /*                           @FT_Generic type description.               */\r\n  /*                                                                       */\r\n  /*    bbox                :: The font bounding box.  Coordinates are     */\r\n  /*                           expressed in font units (see                */\r\n  /*                           `units_per_EM').  The box is large enough   */\r\n  /*                           to contain any glyph from the font.  Thus,  */\r\n  /*                           `bbox.yMax' can be seen as the `maximal     */\r\n  /*                           ascender', and `bbox.yMin' as the `minimal  */\r\n  /*                           descender'.  Only relevant for scalable     */\r\n  /*                           formats.                                    */\r\n  /*                                                                       */\r\n  /*                           Note that the bounding box might be off by  */\r\n  /*                           (at least) one pixel for hinted fonts.  See */\r\n  /*                           @FT_Size_Metrics for further discussion.    */\r\n  /*                                                                       */\r\n  /*    units_per_EM        :: The number of font units per EM square for  */\r\n  /*                           this face.  This is typically 2048 for      */\r\n  /*                           TrueType fonts, and 1000 for Type~1 fonts.  */\r\n  /*                           Only relevant for scalable formats.         */\r\n  /*                                                                       */\r\n  /*    ascender            :: The typographic ascender of the face,       */\r\n  /*                           expressed in font units.  For font formats  */\r\n  /*                           not having this information, it is set to   */\r\n  /*                           `bbox.yMax'.  Only relevant for scalable    */\r\n  /*                           formats.                                    */\r\n  /*                                                                       */\r\n  /*    descender           :: The typographic descender of the face,      */\r\n  /*                           expressed in font units.  For font formats  */\r\n  /*                           not having this information, it is set to   */\r\n  /*                           `bbox.yMin'.  Note that this field is       */\r\n  /*                           usually negative.  Only relevant for        */\r\n  /*                           scalable formats.                           */\r\n  /*                                                                       */\r\n  /*    height              :: The height is the vertical distance         */\r\n  /*                           between two consecutive baselines,          */\r\n  /*                           expressed in font units.  It is always      */\r\n  /*                           positive.  Only relevant for scalable       */\r\n  /*                           formats.                                    */\r\n  /*                                                                       */\r\n  /*    max_advance_width   :: The maximal advance width, in font units,   */\r\n  /*                           for all glyphs in this face.  This can be   */\r\n  /*                           used to make word wrapping computations     */\r\n  /*                           faster.  Only relevant for scalable         */\r\n  /*                           formats.                                    */\r\n  /*                                                                       */\r\n  /*    max_advance_height  :: The maximal advance height, in font units,  */\r\n  /*                           for all glyphs in this face.  This is only  */\r\n  /*                           relevant for vertical layouts, and is set   */\r\n  /*                           to `height' for fonts that do not provide   */\r\n  /*                           vertical metrics.  Only relevant for        */\r\n  /*                           scalable formats.                           */\r\n  /*                                                                       */\r\n  /*    underline_position  :: The position, in font units, of the         */\r\n  /*                           underline line for this face.  It is the    */\r\n  /*                           center of the underlining stem.  Only       */\r\n  /*                           relevant for scalable formats.              */\r\n  /*                                                                       */\r\n  /*    underline_thickness :: The thickness, in font units, of the        */\r\n  /*                           underline for this face.  Only relevant for */\r\n  /*                           scalable formats.                           */\r\n  /*                                                                       */\r\n  /*    glyph               :: The face's associated glyph slot(s).        */\r\n  /*                                                                       */\r\n  /*    size                :: The current active size for this face.      */\r\n  /*                                                                       */\r\n  /*    charmap             :: The current active charmap for this face.   */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    Fields may be changed after a call to @FT_Attach_File or           */\r\n  /*    @FT_Attach_Stream.                                                 */\r\n  /*                                                                       */\r\n  typedef struct  FT_FaceRec_\r\n  {\r\n    FT_Long           num_faces;\r\n    FT_Long           face_index;\r\n\r\n    FT_Long           face_flags;\r\n    FT_Long           style_flags;\r\n\r\n    FT_Long           num_glyphs;\r\n\r\n    FT_String*        family_name;\r\n    FT_String*        style_name;\r\n\r\n    FT_Int            num_fixed_sizes;\r\n    FT_Bitmap_Size*   available_sizes;\r\n\r\n    FT_Int            num_charmaps;\r\n    FT_CharMap*       charmaps;\r\n\r\n    FT_Generic        generic;\r\n\r\n    /*# The following member variables (down to `underline_thickness') */\r\n    /*# are only relevant to scalable outlines; cf. @FT_Bitmap_Size    */\r\n    /*# for bitmap fonts.                                              */\r\n    FT_BBox           bbox;\r\n\r\n    FT_UShort         units_per_EM;\r\n    FT_Short          ascender;\r\n    FT_Short          descender;\r\n    FT_Short          height;\r\n\r\n    FT_Short          max_advance_width;\r\n    FT_Short          max_advance_height;\r\n\r\n    FT_Short          underline_position;\r\n    FT_Short          underline_thickness;\r\n\r\n    FT_GlyphSlot      glyph;\r\n    FT_Size           size;\r\n    FT_CharMap        charmap;\r\n\r\n    /*@private begin */\r\n\r\n    FT_Driver         driver;\r\n    FT_Memory         memory;\r\n    FT_Stream         stream;\r\n\r\n    FT_ListRec        sizes_list;\r\n\r\n    FT_Generic        autohint;\r\n    void*             extensions;\r\n\r\n    FT_Face_Internal  internal;\r\n\r\n    /*@private end */\r\n\r\n  } FT_FaceRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Enum>                                                                */\r\n  /*    FT_FACE_FLAG_XXX                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A list of bit flags used in the `face_flags' field of the          */\r\n  /*    @FT_FaceRec structure.  They inform client applications of         */\r\n  /*    properties of the corresponding face.                              */\r\n  /*                                                                       */\r\n  /* <Values>                                                              */\r\n  /*    FT_FACE_FLAG_SCALABLE ::                                           */\r\n  /*      Indicates that the face contains outline glyphs.  This doesn't   */\r\n  /*      prevent bitmap strikes, i.e., a face can have both this and      */\r\n  /*      and @FT_FACE_FLAG_FIXED_SIZES set.                               */\r\n  /*                                                                       */\r\n  /*    FT_FACE_FLAG_FIXED_SIZES ::                                        */\r\n  /*      Indicates that the face contains bitmap strikes.  See also the   */\r\n  /*      `num_fixed_sizes' and `available_sizes' fields of @FT_FaceRec.   */\r\n  /*                                                                       */\r\n  /*    FT_FACE_FLAG_FIXED_WIDTH ::                                        */\r\n  /*      Indicates that the face contains fixed-width characters (like    */\r\n  /*      Courier, Lucido, MonoType, etc.).                                */\r\n  /*                                                                       */\r\n  /*    FT_FACE_FLAG_SFNT ::                                               */\r\n  /*      Indicates that the face uses the `sfnt' storage scheme.  For     */\r\n  /*      now, this means TrueType and OpenType.                           */\r\n  /*                                                                       */\r\n  /*    FT_FACE_FLAG_HORIZONTAL ::                                         */\r\n  /*      Indicates that the face contains horizontal glyph metrics.  This */\r\n  /*      should be set for all common formats.                            */\r\n  /*                                                                       */\r\n  /*    FT_FACE_FLAG_VERTICAL ::                                           */\r\n  /*      Indicates that the face contains vertical glyph metrics.  This   */\r\n  /*      is only available in some formats, not all of them.              */\r\n  /*                                                                       */\r\n  /*    FT_FACE_FLAG_KERNING ::                                            */\r\n  /*      Indicates that the face contains kerning information.  If set,   */\r\n  /*      the kerning distance can be retrieved through the function       */\r\n  /*      @FT_Get_Kerning.  Otherwise the function always return the       */\r\n  /*      vector (0,0).  Note that FreeType doesn't handle kerning data    */\r\n  /*      from the `GPOS' table (as present in some OpenType fonts).       */\r\n  /*                                                                       */\r\n  /*    FT_FACE_FLAG_FAST_GLYPHS ::                                        */\r\n  /*      THIS FLAG IS DEPRECATED.  DO NOT USE OR TEST IT.                 */\r\n  /*                                                                       */\r\n  /*    FT_FACE_FLAG_MULTIPLE_MASTERS ::                                   */\r\n  /*      Indicates that the font contains multiple masters and is capable */\r\n  /*      of interpolating between them.  See the multiple-masters         */\r\n  /*      specific API for details.                                        */\r\n  /*                                                                       */\r\n  /*    FT_FACE_FLAG_GLYPH_NAMES ::                                        */\r\n  /*      Indicates that the font contains glyph names that can be         */\r\n  /*      retrieved through @FT_Get_Glyph_Name.  Note that some TrueType   */\r\n  /*      fonts contain broken glyph name tables.  Use the function        */\r\n  /*      @FT_Has_PS_Glyph_Names when needed.                              */\r\n  /*                                                                       */\r\n  /*    FT_FACE_FLAG_EXTERNAL_STREAM ::                                    */\r\n  /*      Used internally by FreeType to indicate that a face's stream was */\r\n  /*      provided by the client application and should not be destroyed   */\r\n  /*      when @FT_Done_Face is called.  Don't read or test this flag.     */\r\n  /*                                                                       */\r\n  /*    FT_FACE_FLAG_HINTER ::                                             */\r\n  /*      Set if the font driver has a hinting machine of its own.  For    */\r\n  /*      example, with TrueType fonts, it makes sense to use data from    */\r\n  /*      the SFNT `gasp' table only if the native TrueType hinting engine */\r\n  /*      (with the bytecode interpreter) is available and active.         */\r\n  /*                                                                       */\r\n  /*    FT_FACE_FLAG_CID_KEYED ::                                          */\r\n  /*      Set if the font is CID-keyed.  In that case, the font is not     */\r\n  /*      accessed by glyph indices but by CID values.  For subsetted      */\r\n  /*      CID-keyed fonts this has the consequence that not all index      */\r\n  /*      values are a valid argument to FT_Load_Glyph.  Only the CID      */\r\n  /*      values for which corresponding glyphs in the subsetted font      */\r\n  /*      exist make FT_Load_Glyph return successfully; in all other cases */\r\n  /*      you get an `FT_Err_Invalid_Argument' error.                      */\r\n  /*                                                                       */\r\n  /*      Note that CID-keyed fonts which are in an SFNT wrapper don't     */\r\n  /*      have this flag set since the glyphs are accessed in the normal   */\r\n  /*      way (using contiguous indices); the `CID-ness' isn't visible to  */\r\n  /*      the application.                                                 */\r\n  /*                                                                       */\r\n  /*    FT_FACE_FLAG_TRICKY ::                                             */\r\n  /*      Set if the font is `tricky', this is, it always needs the        */\r\n  /*      font format's native hinting engine to get a reasonable result.  */\r\n  /*      A typical example is the Chinese font `mingli.ttf' which uses    */\r\n  /*      TrueType bytecode instructions to move and scale all of its      */\r\n  /*      subglyphs.                                                       */\r\n  /*                                                                       */\r\n  /*      It is not possible to autohint such fonts using                  */\r\n  /*      @FT_LOAD_FORCE_AUTOHINT; it will also ignore                     */\r\n  /*      @FT_LOAD_NO_HINTING.  You have to set both @FT_LOAD_NO_HINTING   */\r\n  /*      and @FT_LOAD_NO_AUTOHINT to really disable hinting; however, you */\r\n  /*      probably never want this except for demonstration purposes.      */\r\n  /*                                                                       */\r\n  /*      Currently, there are about a dozen TrueType fonts in the list of */\r\n  /*      tricky fonts; they are hard-coded in file `ttobjs.c'.            */\r\n  /*                                                                       */\r\n#define FT_FACE_FLAG_SCALABLE          ( 1L <<  0 )\r\n#define FT_FACE_FLAG_FIXED_SIZES       ( 1L <<  1 )\r\n#define FT_FACE_FLAG_FIXED_WIDTH       ( 1L <<  2 )\r\n#define FT_FACE_FLAG_SFNT              ( 1L <<  3 )\r\n#define FT_FACE_FLAG_HORIZONTAL        ( 1L <<  4 )\r\n#define FT_FACE_FLAG_VERTICAL          ( 1L <<  5 )\r\n#define FT_FACE_FLAG_KERNING           ( 1L <<  6 )\r\n#define FT_FACE_FLAG_FAST_GLYPHS       ( 1L <<  7 )\r\n#define FT_FACE_FLAG_MULTIPLE_MASTERS  ( 1L <<  8 )\r\n#define FT_FACE_FLAG_GLYPH_NAMES       ( 1L <<  9 )\r\n#define FT_FACE_FLAG_EXTERNAL_STREAM   ( 1L << 10 )\r\n#define FT_FACE_FLAG_HINTER            ( 1L << 11 )\r\n#define FT_FACE_FLAG_CID_KEYED         ( 1L << 12 )\r\n#define FT_FACE_FLAG_TRICKY            ( 1L << 13 )\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_HAS_HORIZONTAL( face )\r\n   *\r\n   * @description:\r\n   *   A macro that returns true whenever a face object contains\r\n   *   horizontal metrics (this is true for all font formats though).\r\n   *\r\n   * @also:\r\n   *   @FT_HAS_VERTICAL can be used to check for vertical metrics.\r\n   *\r\n   */\r\n#define FT_HAS_HORIZONTAL( face ) \\\r\n          ( face->face_flags & FT_FACE_FLAG_HORIZONTAL )\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_HAS_VERTICAL( face )\r\n   *\r\n   * @description:\r\n   *   A macro that returns true whenever a face object contains vertical\r\n   *   metrics.\r\n   *\r\n   */\r\n#define FT_HAS_VERTICAL( face ) \\\r\n          ( face->face_flags & FT_FACE_FLAG_VERTICAL )\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_HAS_KERNING( face )\r\n   *\r\n   * @description:\r\n   *   A macro that returns true whenever a face object contains kerning\r\n   *   data that can be accessed with @FT_Get_Kerning.\r\n   *\r\n   */\r\n#define FT_HAS_KERNING( face ) \\\r\n          ( face->face_flags & FT_FACE_FLAG_KERNING )\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_IS_SCALABLE( face )\r\n   *\r\n   * @description:\r\n   *   A macro that returns true whenever a face object contains a scalable\r\n   *   font face (true for TrueType, Type~1, Type~42, CID, OpenType/CFF,\r\n   *   and PFR font formats.\r\n   *\r\n   */\r\n#define FT_IS_SCALABLE( face ) \\\r\n          ( face->face_flags & FT_FACE_FLAG_SCALABLE )\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_IS_SFNT( face )\r\n   *\r\n   * @description:\r\n   *   A macro that returns true whenever a face object contains a font\r\n   *   whose format is based on the SFNT storage scheme.  This usually\r\n   *   means: TrueType fonts, OpenType fonts, as well as SFNT-based embedded\r\n   *   bitmap fonts.\r\n   *\r\n   *   If this macro is true, all functions defined in @FT_SFNT_NAMES_H and\r\n   *   @FT_TRUETYPE_TABLES_H are available.\r\n   *\r\n   */\r\n#define FT_IS_SFNT( face ) \\\r\n          ( face->face_flags & FT_FACE_FLAG_SFNT )\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_IS_FIXED_WIDTH( face )\r\n   *\r\n   * @description:\r\n   *   A macro that returns true whenever a face object contains a font face\r\n   *   that contains fixed-width (or `monospace', `fixed-pitch', etc.)\r\n   *   glyphs.\r\n   *\r\n   */\r\n#define FT_IS_FIXED_WIDTH( face ) \\\r\n          ( face->face_flags & FT_FACE_FLAG_FIXED_WIDTH )\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_HAS_FIXED_SIZES( face )\r\n   *\r\n   * @description:\r\n   *   A macro that returns true whenever a face object contains some\r\n   *   embedded bitmaps.  See the `available_sizes' field of the\r\n   *   @FT_FaceRec structure.\r\n   *\r\n   */\r\n#define FT_HAS_FIXED_SIZES( face ) \\\r\n          ( face->face_flags & FT_FACE_FLAG_FIXED_SIZES )\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_HAS_FAST_GLYPHS( face )\r\n   *\r\n   * @description:\r\n   *   Deprecated.\r\n   *\r\n   */\r\n#define FT_HAS_FAST_GLYPHS( face )  0\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_HAS_GLYPH_NAMES( face )\r\n   *\r\n   * @description:\r\n   *   A macro that returns true whenever a face object contains some glyph\r\n   *   names that can be accessed through @FT_Get_Glyph_Name.\r\n   *\r\n   */\r\n#define FT_HAS_GLYPH_NAMES( face ) \\\r\n          ( face->face_flags & FT_FACE_FLAG_GLYPH_NAMES )\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_HAS_MULTIPLE_MASTERS( face )\r\n   *\r\n   * @description:\r\n   *   A macro that returns true whenever a face object contains some\r\n   *   multiple masters.  The functions provided by @FT_MULTIPLE_MASTERS_H\r\n   *   are then available to choose the exact design you want.\r\n   *\r\n   */\r\n#define FT_HAS_MULTIPLE_MASTERS( face ) \\\r\n          ( face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS )\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_IS_CID_KEYED( face )\r\n   *\r\n   * @description:\r\n   *   A macro that returns true whenever a face object contains a CID-keyed\r\n   *   font.  See the discussion of @FT_FACE_FLAG_CID_KEYED for more\r\n   *   details.\r\n   *\r\n   *   If this macro is true, all functions defined in @FT_CID_H are\r\n   *   available.\r\n   *\r\n   */\r\n#define FT_IS_CID_KEYED( face ) \\\r\n          ( face->face_flags & FT_FACE_FLAG_CID_KEYED )\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_IS_TRICKY( face )\r\n   *\r\n   * @description:\r\n   *   A macro that returns true whenever a face represents a `tricky' font.\r\n   *   See the discussion of @FT_FACE_FLAG_TRICKY for more details.\r\n   *\r\n   */\r\n#define FT_IS_TRICKY( face ) \\\r\n          ( face->face_flags & FT_FACE_FLAG_TRICKY )\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Const>                                                               */\r\n  /*    FT_STYLE_FLAG_XXX                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A list of bit-flags used to indicate the style of a given face.    */\r\n  /*    These are used in the `style_flags' field of @FT_FaceRec.          */\r\n  /*                                                                       */\r\n  /* <Values>                                                              */\r\n  /*    FT_STYLE_FLAG_ITALIC ::                                            */\r\n  /*      Indicates that a given face style is italic or oblique.          */\r\n  /*                                                                       */\r\n  /*    FT_STYLE_FLAG_BOLD ::                                              */\r\n  /*      Indicates that a given face is bold.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The style information as provided by FreeType is very basic.  More */\r\n  /*    details are beyond the scope and should be done on a higher level  */\r\n  /*    (for example, by analyzing various fields of the `OS/2' table in   */\r\n  /*    SFNT based fonts).                                                 */\r\n  /*                                                                       */\r\n#define FT_STYLE_FLAG_ITALIC  ( 1 << 0 )\r\n#define FT_STYLE_FLAG_BOLD    ( 1 << 1 )\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Size_Internal                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    An opaque handle to an `FT_Size_InternalRec' structure, used to    */\r\n  /*    model private data of a given @FT_Size object.                     */\r\n  /*                                                                       */\r\n  typedef struct FT_Size_InternalRec_*  FT_Size_Internal;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Size_Metrics                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    The size metrics structure gives the metrics of a size object.     */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    x_ppem       :: The width of the scaled EM square in pixels, hence */\r\n  /*                    the term `ppem' (pixels per EM).  It is also       */\r\n  /*                    referred to as `nominal width'.                    */\r\n  /*                                                                       */\r\n  /*    y_ppem       :: The height of the scaled EM square in pixels,      */\r\n  /*                    hence the term `ppem' (pixels per EM).  It is also */\r\n  /*                    referred to as `nominal height'.                   */\r\n  /*                                                                       */\r\n  /*    x_scale      :: A 16.16 fractional scaling value used to convert   */\r\n  /*                    horizontal metrics from font units to 26.6         */\r\n  /*                    fractional pixels.  Only relevant for scalable     */\r\n  /*                    font formats.                                      */\r\n  /*                                                                       */\r\n  /*    y_scale      :: A 16.16 fractional scaling value used to convert   */\r\n  /*                    vertical metrics from font units to 26.6           */\r\n  /*                    fractional pixels.  Only relevant for scalable     */\r\n  /*                    font formats.                                      */\r\n  /*                                                                       */\r\n  /*    ascender     :: The ascender in 26.6 fractional pixels.  See       */\r\n  /*                    @FT_FaceRec for the details.                       */\r\n  /*                                                                       */\r\n  /*    descender    :: The descender in 26.6 fractional pixels.  See      */\r\n  /*                    @FT_FaceRec for the details.                       */\r\n  /*                                                                       */\r\n  /*    height       :: The height in 26.6 fractional pixels.  See         */\r\n  /*                    @FT_FaceRec for the details.                       */\r\n  /*                                                                       */\r\n  /*    max_advance  :: The maximal advance width in 26.6 fractional       */\r\n  /*                    pixels.  See @FT_FaceRec for the details.          */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The scaling values, if relevant, are determined first during a     */\r\n  /*    size changing operation.  The remaining fields are then set by the */\r\n  /*    driver.  For scalable formats, they are usually set to scaled      */\r\n  /*    values of the corresponding fields in @FT_FaceRec.                 */\r\n  /*                                                                       */\r\n  /*    Note that due to glyph hinting, these values might not be exact    */\r\n  /*    for certain fonts.  Thus they must be treated as unreliable        */\r\n  /*    with an error margin of at least one pixel!                        */\r\n  /*                                                                       */\r\n  /*    Indeed, the only way to get the exact metrics is to render _all_   */\r\n  /*    glyphs.  As this would be a definite performance hit, it is up to  */\r\n  /*    client applications to perform such computations.                  */\r\n  /*                                                                       */\r\n  /*    The FT_Size_Metrics structure is valid for bitmap fonts also.      */\r\n  /*                                                                       */\r\n  typedef struct  FT_Size_Metrics_\r\n  {\r\n    FT_UShort  x_ppem;      /* horizontal pixels per EM               */\r\n    FT_UShort  y_ppem;      /* vertical pixels per EM                 */\r\n\r\n    FT_Fixed   x_scale;     /* scaling values used to convert font    */\r\n    FT_Fixed   y_scale;     /* units to 26.6 fractional pixels        */\r\n\r\n    FT_Pos     ascender;    /* ascender in 26.6 frac. pixels          */\r\n    FT_Pos     descender;   /* descender in 26.6 frac. pixels         */\r\n    FT_Pos     height;      /* text height in 26.6 frac. pixels       */\r\n    FT_Pos     max_advance; /* max horizontal advance, in 26.6 pixels */\r\n\r\n  } FT_Size_Metrics;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_SizeRec                                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    FreeType root size class structure.  A size object models a face   */\r\n  /*    object at a given size.                                            */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    face    :: Handle to the parent face object.                       */\r\n  /*                                                                       */\r\n  /*    generic :: A typeless pointer, which is unused by the FreeType     */\r\n  /*               library or any of its drivers.  It can be used by       */\r\n  /*               client applications to link their own data to each size */\r\n  /*               object.                                                 */\r\n  /*                                                                       */\r\n  /*    metrics :: Metrics for this size object.  This field is read-only. */\r\n  /*                                                                       */\r\n  typedef struct  FT_SizeRec_\r\n  {\r\n    FT_Face           face;      /* parent face object              */\r\n    FT_Generic        generic;   /* generic pointer for client uses */\r\n    FT_Size_Metrics   metrics;   /* size metrics                    */\r\n    FT_Size_Internal  internal;\r\n\r\n  } FT_SizeRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_SubGlyph                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    The subglyph structure is an internal object used to describe      */\r\n  /*    subglyphs (for example, in the case of composites).                */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The subglyph implementation is not part of the high-level API,     */\r\n  /*    hence the forward structure declaration.                           */\r\n  /*                                                                       */\r\n  /*    You can however retrieve subglyph information with                 */\r\n  /*    @FT_Get_SubGlyph_Info.                                             */\r\n  /*                                                                       */\r\n  typedef struct FT_SubGlyphRec_*  FT_SubGlyph;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Slot_Internal                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    An opaque handle to an `FT_Slot_InternalRec' structure, used to    */\r\n  /*    model private data of a given @FT_GlyphSlot object.                */\r\n  /*                                                                       */\r\n  typedef struct FT_Slot_InternalRec_*  FT_Slot_Internal;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_GlyphSlotRec                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    FreeType root glyph slot class structure.  A glyph slot is a       */\r\n  /*    container where individual glyphs can be loaded, be they in        */\r\n  /*    outline or bitmap format.                                          */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    library           :: A handle to the FreeType library instance     */\r\n  /*                         this slot belongs to.                         */\r\n  /*                                                                       */\r\n  /*    face              :: A handle to the parent face object.           */\r\n  /*                                                                       */\r\n  /*    next              :: In some cases (like some font tools), several */\r\n  /*                         glyph slots per face object can be a good     */\r\n  /*                         thing.  As this is rare, the glyph slots are  */\r\n  /*                         listed through a direct, single-linked list   */\r\n  /*                         using its `next' field.                       */\r\n  /*                                                                       */\r\n  /*    generic           :: A typeless pointer which is unused by the     */\r\n  /*                         FreeType library or any of its drivers.  It   */\r\n  /*                         can be used by client applications to link    */\r\n  /*                         their own data to each glyph slot object.     */\r\n  /*                                                                       */\r\n  /*    metrics           :: The metrics of the last loaded glyph in the   */\r\n  /*                         slot.  The returned values depend on the last */\r\n  /*                         load flags (see the @FT_Load_Glyph API        */\r\n  /*                         function) and can be expressed either in 26.6 */\r\n  /*                         fractional pixels or font units.              */\r\n  /*                                                                       */\r\n  /*                         Note that even when the glyph image is        */\r\n  /*                         transformed, the metrics are not.             */\r\n  /*                                                                       */\r\n  /*    linearHoriAdvance :: The advance width of the unhinted glyph.      */\r\n  /*                         Its value is expressed in 16.16 fractional    */\r\n  /*                         pixels, unless @FT_LOAD_LINEAR_DESIGN is set  */\r\n  /*                         when loading the glyph.  This field can be    */\r\n  /*                         important to perform correct WYSIWYG layout.  */\r\n  /*                         Only relevant for outline glyphs.             */\r\n  /*                                                                       */\r\n  /*    linearVertAdvance :: The advance height of the unhinted glyph.     */\r\n  /*                         Its value is expressed in 16.16 fractional    */\r\n  /*                         pixels, unless @FT_LOAD_LINEAR_DESIGN is set  */\r\n  /*                         when loading the glyph.  This field can be    */\r\n  /*                         important to perform correct WYSIWYG layout.  */\r\n  /*                         Only relevant for outline glyphs.             */\r\n  /*                                                                       */\r\n  /*    advance           :: This shorthand is, depending on               */\r\n  /*                         @FT_LOAD_IGNORE_TRANSFORM, the transformed    */\r\n  /*                         advance width for the glyph (in 26.6          */\r\n  /*                         fractional pixel format).  As specified with  */\r\n  /*                         @FT_LOAD_VERTICAL_LAYOUT, it uses either the  */\r\n  /*                         `horiAdvance' or the `vertAdvance' value of   */\r\n  /*                         `metrics' field.                              */\r\n  /*                                                                       */\r\n  /*    format            :: This field indicates the format of the image  */\r\n  /*                         contained in the glyph slot.  Typically       */\r\n  /*                         @FT_GLYPH_FORMAT_BITMAP,                      */\r\n  /*                         @FT_GLYPH_FORMAT_OUTLINE, or                  */\r\n  /*                         @FT_GLYPH_FORMAT_COMPOSITE, but others are    */\r\n  /*                         possible.                                     */\r\n  /*                                                                       */\r\n  /*    bitmap            :: This field is used as a bitmap descriptor     */\r\n  /*                         when the slot format is                       */\r\n  /*                         @FT_GLYPH_FORMAT_BITMAP.  Note that the       */\r\n  /*                         address and content of the bitmap buffer can  */\r\n  /*                         change between calls of @FT_Load_Glyph and a  */\r\n  /*                         few other functions.                          */\r\n  /*                                                                       */\r\n  /*    bitmap_left       :: This is the bitmap's left bearing expressed   */\r\n  /*                         in integer pixels.  Of course, this is only   */\r\n  /*                         valid if the format is                        */\r\n  /*                         @FT_GLYPH_FORMAT_BITMAP.                      */\r\n  /*                                                                       */\r\n  /*    bitmap_top        :: This is the bitmap's top bearing expressed in */\r\n  /*                         integer pixels.  Remember that this is the    */\r\n  /*                         distance from the baseline to the top-most    */\r\n  /*                         glyph scanline, upwards y~coordinates being   */\r\n  /*                         *positive*.                                   */\r\n  /*                                                                       */\r\n  /*    outline           :: The outline descriptor for the current glyph  */\r\n  /*                         image if its format is                        */\r\n  /*                         @FT_GLYPH_FORMAT_OUTLINE.  Once a glyph is    */\r\n  /*                         loaded, `outline' can be transformed,         */\r\n  /*                         distorted, embolded, etc.  However, it must   */\r\n  /*                         not be freed.                                 */\r\n  /*                                                                       */\r\n  /*    num_subglyphs     :: The number of subglyphs in a composite glyph. */\r\n  /*                         This field is only valid for the composite    */\r\n  /*                         glyph format that should normally only be     */\r\n  /*                         loaded with the @FT_LOAD_NO_RECURSE flag.     */\r\n  /*                         For now this is internal to FreeType.         */\r\n  /*                                                                       */\r\n  /*    subglyphs         :: An array of subglyph descriptors for          */\r\n  /*                         composite glyphs.  There are `num_subglyphs'  */\r\n  /*                         elements in there.  Currently internal to     */\r\n  /*                         FreeType.                                     */\r\n  /*                                                                       */\r\n  /*    control_data      :: Certain font drivers can also return the      */\r\n  /*                         control data for a given glyph image (e.g.    */\r\n  /*                         TrueType bytecode, Type~1 charstrings, etc.). */\r\n  /*                         This field is a pointer to such data.         */\r\n  /*                                                                       */\r\n  /*    control_len       :: This is the length in bytes of the control    */\r\n  /*                         data.                                         */\r\n  /*                                                                       */\r\n  /*    other             :: Really wicked formats can use this pointer to */\r\n  /*                         present their own glyph image to client       */\r\n  /*                         applications.  Note that the application      */\r\n  /*                         needs to know about the image format.         */\r\n  /*                                                                       */\r\n  /*    lsb_delta         :: The difference between hinted and unhinted    */\r\n  /*                         left side bearing while autohinting is        */\r\n  /*                         active.  Zero otherwise.                      */\r\n  /*                                                                       */\r\n  /*    rsb_delta         :: The difference between hinted and unhinted    */\r\n  /*                         right side bearing while autohinting is       */\r\n  /*                         active.  Zero otherwise.                      */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    If @FT_Load_Glyph is called with default flags (see                */\r\n  /*    @FT_LOAD_DEFAULT) the glyph image is loaded in the glyph slot in   */\r\n  /*    its native format (e.g., an outline glyph for TrueType and Type~1  */\r\n  /*    formats).                                                          */\r\n  /*                                                                       */\r\n  /*    This image can later be converted into a bitmap by calling         */\r\n  /*    @FT_Render_Glyph.  This function finds the current renderer for    */\r\n  /*    the native image's format, then invokes it.                        */\r\n  /*                                                                       */\r\n  /*    The renderer is in charge of transforming the native image through */\r\n  /*    the slot's face transformation fields, then converting it into a   */\r\n  /*    bitmap that is returned in `slot->bitmap'.                         */\r\n  /*                                                                       */\r\n  /*    Note that `slot->bitmap_left' and `slot->bitmap_top' are also used */\r\n  /*    to specify the position of the bitmap relative to the current pen  */\r\n  /*    position (e.g., coordinates (0,0) on the baseline).  Of course,    */\r\n  /*    `slot->format' is also changed to @FT_GLYPH_FORMAT_BITMAP.         */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    Here a small pseudo code fragment which shows how to use           */\r\n  /*    `lsb_delta' and `rsb_delta':                                       */\r\n  /*                                                                       */\r\n  /*    {                                                                  */\r\n  /*      FT_Pos  origin_x       = 0;                                      */\r\n  /*      FT_Pos  prev_rsb_delta = 0;                                      */\r\n  /*                                                                       */\r\n  /*                                                                       */\r\n  /*      for all glyphs do                                                */\r\n  /*        <compute kern between current and previous glyph and add it to */\r\n  /*         `origin_x'>                                                   */\r\n  /*                                                                       */\r\n  /*        <load glyph with `FT_Load_Glyph'>                              */\r\n  /*                                                                       */\r\n  /*        if ( prev_rsb_delta - face->glyph->lsb_delta >= 32 )           */\r\n  /*          origin_x -= 64;                                              */\r\n  /*        else if ( prev_rsb_delta - face->glyph->lsb_delta < -32 )      */\r\n  /*          origin_x += 64;                                              */\r\n  /*                                                                       */\r\n  /*        prev_rsb_delta = face->glyph->rsb_delta;                       */\r\n  /*                                                                       */\r\n  /*        <save glyph image, or render glyph, or ...>                    */\r\n  /*                                                                       */\r\n  /*        origin_x += face->glyph->advance.x;                            */\r\n  /*      endfor                                                           */\r\n  /*    }                                                                  */\r\n  /*                                                                       */\r\n  typedef struct  FT_GlyphSlotRec_\r\n  {\r\n    FT_Library        library;\r\n    FT_Face           face;\r\n    FT_GlyphSlot      next;\r\n    FT_UInt           reserved;       /* retained for binary compatibility */\r\n    FT_Generic        generic;\r\n\r\n    FT_Glyph_Metrics  metrics;\r\n    FT_Fixed          linearHoriAdvance;\r\n    FT_Fixed          linearVertAdvance;\r\n    FT_Vector         advance;\r\n\r\n    FT_Glyph_Format   format;\r\n\r\n    FT_Bitmap         bitmap;\r\n    FT_Int            bitmap_left;\r\n    FT_Int            bitmap_top;\r\n\r\n    FT_Outline        outline;\r\n\r\n    FT_UInt           num_subglyphs;\r\n    FT_SubGlyph       subglyphs;\r\n\r\n    void*             control_data;\r\n    long              control_len;\r\n\r\n    FT_Pos            lsb_delta;\r\n    FT_Pos            rsb_delta;\r\n\r\n    void*             other;\r\n\r\n    FT_Slot_Internal  internal;\r\n\r\n  } FT_GlyphSlotRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /*                         F U N C T I O N S                             */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Init_FreeType                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Initialize a new FreeType library object.  The set of modules      */\r\n  /*    that are registered by this function is determined at build time.  */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    alibrary :: A handle to a new library object.                      */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    In case you want to provide your own memory allocating routines,   */\r\n  /*    use @FT_New_Library instead, followed by a call to                 */\r\n  /*    @FT_Add_Default_Modules (or a series of calls to @FT_Add_Module).  */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Init_FreeType( FT_Library  *alibrary );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Done_FreeType                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Destroy a given FreeType library object and all of its children,   */\r\n  /*    including resources, drivers, faces, sizes, etc.                   */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    library :: A handle to the target library object.                  */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Done_FreeType( FT_Library  library );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Enum>                                                                */\r\n  /*    FT_OPEN_XXX                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A list of bit-field constants used within the `flags' field of the */\r\n  /*    @FT_Open_Args structure.                                           */\r\n  /*                                                                       */\r\n  /* <Values>                                                              */\r\n  /*    FT_OPEN_MEMORY   :: This is a memory-based stream.                 */\r\n  /*                                                                       */\r\n  /*    FT_OPEN_STREAM   :: Copy the stream from the `stream' field.       */\r\n  /*                                                                       */\r\n  /*    FT_OPEN_PATHNAME :: Create a new input stream from a C~path        */\r\n  /*                        name.                                          */\r\n  /*                                                                       */\r\n  /*    FT_OPEN_DRIVER   :: Use the `driver' field.                        */\r\n  /*                                                                       */\r\n  /*    FT_OPEN_PARAMS   :: Use the `num_params' and `params' fields.      */\r\n  /*                                                                       */\r\n  /*    ft_open_memory   :: Deprecated; use @FT_OPEN_MEMORY instead.       */\r\n  /*                                                                       */\r\n  /*    ft_open_stream   :: Deprecated; use @FT_OPEN_STREAM instead.       */\r\n  /*                                                                       */\r\n  /*    ft_open_pathname :: Deprecated; use @FT_OPEN_PATHNAME instead.     */\r\n  /*                                                                       */\r\n  /*    ft_open_driver   :: Deprecated; use @FT_OPEN_DRIVER instead.       */\r\n  /*                                                                       */\r\n  /*    ft_open_params   :: Deprecated; use @FT_OPEN_PARAMS instead.       */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The `FT_OPEN_MEMORY', `FT_OPEN_STREAM', and `FT_OPEN_PATHNAME'     */\r\n  /*    flags are mutually exclusive.                                      */\r\n  /*                                                                       */\r\n#define FT_OPEN_MEMORY    0x1\r\n#define FT_OPEN_STREAM    0x2\r\n#define FT_OPEN_PATHNAME  0x4\r\n#define FT_OPEN_DRIVER    0x8\r\n#define FT_OPEN_PARAMS    0x10\r\n\r\n#define ft_open_memory    FT_OPEN_MEMORY     /* deprecated */\r\n#define ft_open_stream    FT_OPEN_STREAM     /* deprecated */\r\n#define ft_open_pathname  FT_OPEN_PATHNAME   /* deprecated */\r\n#define ft_open_driver    FT_OPEN_DRIVER     /* deprecated */\r\n#define ft_open_params    FT_OPEN_PARAMS     /* deprecated */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Parameter                                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A simple structure used to pass more or less generic parameters to */\r\n  /*    @FT_Open_Face.                                                     */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    tag  :: A four-byte identification tag.                            */\r\n  /*                                                                       */\r\n  /*    data :: A pointer to the parameter data.                           */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The ID and function of parameters are driver-specific.  See the    */\r\n  /*    various FT_PARAM_TAG_XXX flags for more information.               */\r\n  /*                                                                       */\r\n  typedef struct  FT_Parameter_\r\n  {\r\n    FT_ULong    tag;\r\n    FT_Pointer  data;\r\n\r\n  } FT_Parameter;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Open_Args                                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to indicate how to open a new font file or        */\r\n  /*    stream.  A pointer to such a structure can be used as a parameter  */\r\n  /*    for the functions @FT_Open_Face and @FT_Attach_Stream.             */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    flags       :: A set of bit flags indicating how to use the        */\r\n  /*                   structure.                                          */\r\n  /*                                                                       */\r\n  /*    memory_base :: The first byte of the file in memory.               */\r\n  /*                                                                       */\r\n  /*    memory_size :: The size in bytes of the file in memory.            */\r\n  /*                                                                       */\r\n  /*    pathname    :: A pointer to an 8-bit file pathname.                */\r\n  /*                                                                       */\r\n  /*    stream      :: A handle to a source stream object.                 */\r\n  /*                                                                       */\r\n  /*    driver      :: This field is exclusively used by @FT_Open_Face;    */\r\n  /*                   it simply specifies the font driver to use to open  */\r\n  /*                   the face.  If set to~0, FreeType tries to load the  */\r\n  /*                   face with each one of the drivers in its list.      */\r\n  /*                                                                       */\r\n  /*    num_params  :: The number of extra parameters.                     */\r\n  /*                                                                       */\r\n  /*    params      :: Extra parameters passed to the font driver when     */\r\n  /*                   opening a new face.                                 */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The stream type is determined by the contents of `flags' which     */\r\n  /*    are tested in the following order by @FT_Open_Face:                */\r\n  /*                                                                       */\r\n  /*    If the `FT_OPEN_MEMORY' bit is set, assume that this is a          */\r\n  /*    memory file of `memory_size' bytes, located at `memory_address'.   */\r\n  /*    The data are are not copied, and the client is responsible for     */\r\n  /*    releasing and destroying them _after_ the corresponding call to    */\r\n  /*    @FT_Done_Face.                                                     */\r\n  /*                                                                       */\r\n  /*    Otherwise, if the `FT_OPEN_STREAM' bit is set, assume that a       */\r\n  /*    custom input stream `stream' is used.                              */\r\n  /*                                                                       */\r\n  /*    Otherwise, if the `FT_OPEN_PATHNAME' bit is set, assume that this  */\r\n  /*    is a normal file and use `pathname' to open it.                    */\r\n  /*                                                                       */\r\n  /*    If the `FT_OPEN_DRIVER' bit is set, @FT_Open_Face only tries to    */\r\n  /*    open the file with the driver whose handler is in `driver'.        */\r\n  /*                                                                       */\r\n  /*    If the `FT_OPEN_PARAMS' bit is set, the parameters given by        */\r\n  /*    `num_params' and `params' is used.  They are ignored otherwise.    */\r\n  /*                                                                       */\r\n  /*    Ideally, both the `pathname' and `params' fields should be tagged  */\r\n  /*    as `const'; this is missing for API backwards compatibility.  In   */\r\n  /*    other words, applications should treat them as read-only.          */\r\n  /*                                                                       */\r\n  typedef struct  FT_Open_Args_\r\n  {\r\n    FT_UInt         flags;\r\n    const FT_Byte*  memory_base;\r\n    FT_Long         memory_size;\r\n    FT_String*      pathname;\r\n    FT_Stream       stream;\r\n    FT_Module       driver;\r\n    FT_Int          num_params;\r\n    FT_Parameter*   params;\r\n\r\n  } FT_Open_Args;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_New_Face                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This function calls @FT_Open_Face to open a font by its pathname.  */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    library    :: A handle to the library resource.                    */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    pathname   :: A path to the font file.                             */\r\n  /*                                                                       */\r\n  /*    face_index :: The index of the face within the font.  The first    */\r\n  /*                  face has index~0.                                    */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    aface      :: A handle to a new face object.  If `face_index' is   */\r\n  /*                  greater than or equal to zero, it must be non-NULL.  */\r\n  /*                  See @FT_Open_Face for more details.                  */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_New_Face( FT_Library   library,\r\n               const char*  filepathname,\r\n               FT_Long      face_index,\r\n               FT_Face     *aface );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_New_Memory_Face                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This function calls @FT_Open_Face to open a font which has been    */\r\n  /*    loaded into memory.                                                */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    library    :: A handle to the library resource.                    */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    file_base  :: A pointer to the beginning of the font data.         */\r\n  /*                                                                       */\r\n  /*    file_size  :: The size of the memory chunk used by the font data.  */\r\n  /*                                                                       */\r\n  /*    face_index :: The index of the face within the font.  The first    */\r\n  /*                  face has index~0.                                    */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    aface      :: A handle to a new face object.  If `face_index' is   */\r\n  /*                  greater than or equal to zero, it must be non-NULL.  */\r\n  /*                  See @FT_Open_Face for more details.                  */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    You must not deallocate the memory before calling @FT_Done_Face.   */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_New_Memory_Face( FT_Library      library,\r\n                      const FT_Byte*  file_base,\r\n                      FT_Long         file_size,\r\n                      FT_Long         face_index,\r\n                      FT_Face        *aface );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Open_Face                                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Create a face object from a given resource described by            */\r\n  /*    @FT_Open_Args.                                                     */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    library    :: A handle to the library resource.                    */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    args       :: A pointer to an `FT_Open_Args' structure which must  */\r\n  /*                  be filled by the caller.                             */\r\n  /*                                                                       */\r\n  /*    face_index :: The index of the face within the font.  The first    */\r\n  /*                  face has index~0.                                    */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    aface      :: A handle to a new face object.  If `face_index' is   */\r\n  /*                  greater than or equal to zero, it must be non-NULL.  */\r\n  /*                  See note below.                                      */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    Unlike FreeType 1.x, this function automatically creates a glyph   */\r\n  /*    slot for the face object which can be accessed directly through    */\r\n  /*    `face->glyph'.                                                     */\r\n  /*                                                                       */\r\n  /*    FT_Open_Face can be used to quickly check whether the font         */\r\n  /*    format of a given font resource is supported by FreeType.  If the  */\r\n  /*    `face_index' field is negative, the function's return value is~0   */\r\n  /*    if the font format is recognized, or non-zero otherwise;           */\r\n  /*    the function returns a more or less empty face handle in `*aface'  */\r\n  /*    (if `aface' isn't NULL).  The only useful field in this special    */\r\n  /*    case is `face->num_faces' which gives the number of faces within   */\r\n  /*    the font file.  After examination, the returned @FT_Face structure */\r\n  /*    should be deallocated with a call to @FT_Done_Face.                */\r\n  /*                                                                       */\r\n  /*    Each new face object created with this function also owns a        */\r\n  /*    default @FT_Size object, accessible as `face->size'.               */\r\n  /*                                                                       */\r\n  /*    See the discussion of reference counters in the description of     */\r\n  /*    @FT_Reference_Face.                                                */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Open_Face( FT_Library           library,\r\n                const FT_Open_Args*  args,\r\n                FT_Long              face_index,\r\n                FT_Face             *aface );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Attach_File                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This function calls @FT_Attach_Stream to attach a file.            */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    face         :: The target face object.                            */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    filepathname :: The pathname.                                      */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Attach_File( FT_Face      face,\r\n                  const char*  filepathname );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Attach_Stream                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    `Attach' data to a face object.  Normally, this is used to read    */\r\n  /*    additional information for the face object.  For example, you can  */\r\n  /*    attach an AFM file that comes with a Type~1 font to get the        */\r\n  /*    kerning values and other metrics.                                  */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    face       :: The target face object.                              */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    parameters :: A pointer to @FT_Open_Args which must be filled by   */\r\n  /*                  the caller.                                          */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The meaning of the `attach' (i.e., what really happens when the    */\r\n  /*    new file is read) is not fixed by FreeType itself.  It really      */\r\n  /*    depends on the font format (and thus the font driver).             */\r\n  /*                                                                       */\r\n  /*    Client applications are expected to know what they are doing       */\r\n  /*    when invoking this function.  Most drivers simply do not implement */\r\n  /*    file attachments.                                                  */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Attach_Stream( FT_Face        face,\r\n                    FT_Open_Args*  parameters );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Reference_Face                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A counter gets initialized to~1 at the time an @FT_Face structure  */\r\n  /*    is created.  This function increments the counter.  @FT_Done_Face  */\r\n  /*    then only destroys a face if the counter is~1, otherwise it simply */\r\n  /*    decrements the counter.                                            */\r\n  /*                                                                       */\r\n  /*    This function helps in managing life-cycles of structures which    */\r\n  /*    reference @FT_Face objects.                                        */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face :: A handle to a target face object.                          */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Since>                                                               */\r\n  /*    2.4.2                                                              */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Reference_Face( FT_Face  face );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Done_Face                                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Discard a given face object, as well as all of its child slots and */\r\n  /*    sizes.                                                             */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face :: A handle to a target face object.                          */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    See the discussion of reference counters in the description of     */\r\n  /*    @FT_Reference_Face.                                                */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Done_Face( FT_Face  face );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Select_Size                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Select a bitmap strike.                                            */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    face         :: A handle to a target face object.                  */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    strike_index :: The index of the bitmap strike in the              */\r\n  /*                    `available_sizes' field of @FT_FaceRec structure.  */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Select_Size( FT_Face  face,\r\n                  FT_Int   strike_index );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Enum>                                                                */\r\n  /*    FT_Size_Request_Type                                               */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    An enumeration type that lists the supported size request types.   */\r\n  /*                                                                       */\r\n  /* <Values>                                                              */\r\n  /*    FT_SIZE_REQUEST_TYPE_NOMINAL ::                                    */\r\n  /*      The nominal size.  The `units_per_EM' field of @FT_FaceRec is    */\r\n  /*      used to determine both scaling values.                           */\r\n  /*                                                                       */\r\n  /*    FT_SIZE_REQUEST_TYPE_REAL_DIM ::                                   */\r\n  /*      The real dimension.  The sum of the the `ascender' and (minus    */\r\n  /*      of) the `descender' fields of @FT_FaceRec are used to determine  */\r\n  /*      both scaling values.                                             */\r\n  /*                                                                       */\r\n  /*    FT_SIZE_REQUEST_TYPE_BBOX ::                                       */\r\n  /*      The font bounding box.  The width and height of the `bbox' field */\r\n  /*      of @FT_FaceRec are used to determine the horizontal and vertical */\r\n  /*      scaling value, respectively.                                     */\r\n  /*                                                                       */\r\n  /*    FT_SIZE_REQUEST_TYPE_CELL ::                                       */\r\n  /*      The `max_advance_width' field of @FT_FaceRec is used to          */\r\n  /*      determine the horizontal scaling value; the vertical scaling     */\r\n  /*      value is determined the same way as                              */\r\n  /*      @FT_SIZE_REQUEST_TYPE_REAL_DIM does.  Finally, both scaling      */\r\n  /*      values are set to the smaller one.  This type is useful if you   */\r\n  /*      want to specify the font size for, say, a window of a given      */\r\n  /*      dimension and 80x24 cells.                                       */\r\n  /*                                                                       */\r\n  /*    FT_SIZE_REQUEST_TYPE_SCALES ::                                     */\r\n  /*      Specify the scaling values directly.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The above descriptions only apply to scalable formats.  For bitmap */\r\n  /*    formats, the behaviour is up to the driver.                        */\r\n  /*                                                                       */\r\n  /*    See the note section of @FT_Size_Metrics if you wonder how size    */\r\n  /*    requesting relates to scaling values.                              */\r\n  /*                                                                       */\r\n  typedef enum  FT_Size_Request_Type_\r\n  {\r\n    FT_SIZE_REQUEST_TYPE_NOMINAL,\r\n    FT_SIZE_REQUEST_TYPE_REAL_DIM,\r\n    FT_SIZE_REQUEST_TYPE_BBOX,\r\n    FT_SIZE_REQUEST_TYPE_CELL,\r\n    FT_SIZE_REQUEST_TYPE_SCALES,\r\n\r\n    FT_SIZE_REQUEST_TYPE_MAX\r\n\r\n  } FT_Size_Request_Type;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Size_RequestRec                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to model a size request.                          */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    type           :: See @FT_Size_Request_Type.                       */\r\n  /*                                                                       */\r\n  /*    width          :: The desired width.                               */\r\n  /*                                                                       */\r\n  /*    height         :: The desired height.                              */\r\n  /*                                                                       */\r\n  /*    horiResolution :: The horizontal resolution.  If set to zero,      */\r\n  /*                      `width' is treated as a 26.6 fractional pixel    */\r\n  /*                      value.                                           */\r\n  /*                                                                       */\r\n  /*    vertResolution :: The vertical resolution.  If set to zero,        */\r\n  /*                      `height' is treated as a 26.6 fractional pixel   */\r\n  /*                      value.                                           */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    If `width' is zero, then the horizontal scaling value is set equal */\r\n  /*    to the vertical scaling value, and vice versa.                     */\r\n  /*                                                                       */\r\n  typedef struct  FT_Size_RequestRec_\r\n  {\r\n    FT_Size_Request_Type  type;\r\n    FT_Long               width;\r\n    FT_Long               height;\r\n    FT_UInt               horiResolution;\r\n    FT_UInt               vertResolution;\r\n\r\n  } FT_Size_RequestRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Size_Request                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle to a size request structure.                              */\r\n  /*                                                                       */\r\n  typedef struct FT_Size_RequestRec_  *FT_Size_Request;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Request_Size                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Resize the scale of the active @FT_Size object in a face.          */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    face :: A handle to a target face object.                          */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    req  :: A pointer to a @FT_Size_RequestRec.                        */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    Although drivers may select the bitmap strike matching the         */\r\n  /*    request, you should not rely on this if you intend to select a     */\r\n  /*    particular bitmap strike.  Use @FT_Select_Size instead in that     */\r\n  /*    case.                                                              */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Request_Size( FT_Face          face,\r\n                   FT_Size_Request  req );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Set_Char_Size                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This function calls @FT_Request_Size to request the nominal size   */\r\n  /*    (in points).                                                       */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    face            :: A handle to a target face object.               */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    char_width      :: The nominal width, in 26.6 fractional points.   */\r\n  /*                                                                       */\r\n  /*    char_height     :: The nominal height, in 26.6 fractional points.  */\r\n  /*                                                                       */\r\n  /*    horz_resolution :: The horizontal resolution in dpi.               */\r\n  /*                                                                       */\r\n  /*    vert_resolution :: The vertical resolution in dpi.                 */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    If either the character width or height is zero, it is set equal   */\r\n  /*    to the other value.                                                */\r\n  /*                                                                       */\r\n  /*    If either the horizontal or vertical resolution is zero, it is set */\r\n  /*    equal to the other value.                                          */\r\n  /*                                                                       */\r\n  /*    A character width or height smaller than 1pt is set to 1pt; if     */\r\n  /*    both resolution values are zero, they are set to 72dpi.            */\r\n  /*                                                                       */\r\n  /*    Don't use this function if you are using the FreeType cache API.   */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Set_Char_Size( FT_Face     face,\r\n                    FT_F26Dot6  char_width,\r\n                    FT_F26Dot6  char_height,\r\n                    FT_UInt     horz_resolution,\r\n                    FT_UInt     vert_resolution );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Set_Pixel_Sizes                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This function calls @FT_Request_Size to request the nominal size   */\r\n  /*    (in pixels).                                                       */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    face         :: A handle to the target face object.                */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    pixel_width  :: The nominal width, in pixels.                      */\r\n  /*                                                                       */\r\n  /*    pixel_height :: The nominal height, in pixels.                     */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Set_Pixel_Sizes( FT_Face  face,\r\n                      FT_UInt  pixel_width,\r\n                      FT_UInt  pixel_height );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Load_Glyph                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A function used to load a single glyph into the glyph slot of a    */\r\n  /*    face object.                                                       */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    face        :: A handle to the target face object where the glyph  */\r\n  /*                   is loaded.                                          */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    glyph_index :: The index of the glyph in the font file.  For       */\r\n  /*                   CID-keyed fonts (either in PS or in CFF format)     */\r\n  /*                   this argument specifies the CID value.              */\r\n  /*                                                                       */\r\n  /*    load_flags  :: A flag indicating what to load for this glyph.  The */\r\n  /*                   @FT_LOAD_XXX constants can be used to control the   */\r\n  /*                   glyph loading process (e.g., whether the outline    */\r\n  /*                   should be scaled, whether to load bitmaps or not,   */\r\n  /*                   whether to hint the outline, etc).                  */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The loaded glyph may be transformed.  See @FT_Set_Transform for    */\r\n  /*    the details.                                                       */\r\n  /*                                                                       */\r\n  /*    For subsetted CID-keyed fonts, `FT_Err_Invalid_Argument' is        */\r\n  /*    returned for invalid CID values (this is, for CID values which     */\r\n  /*    don't have a corresponding glyph in the font).  See the discussion */\r\n  /*    of the @FT_FACE_FLAG_CID_KEYED flag for more details.              */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Load_Glyph( FT_Face   face,\r\n                 FT_UInt   glyph_index,\r\n                 FT_Int32  load_flags );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Load_Char                                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A function used to load a single glyph into the glyph slot of a    */\r\n  /*    face object, according to its character code.                      */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    face        :: A handle to a target face object where the glyph    */\r\n  /*                   is loaded.                                          */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    char_code   :: The glyph's character code, according to the        */\r\n  /*                   current charmap used in the face.                   */\r\n  /*                                                                       */\r\n  /*    load_flags  :: A flag indicating what to load for this glyph.  The */\r\n  /*                   @FT_LOAD_XXX constants can be used to control the   */\r\n  /*                   glyph loading process (e.g., whether the outline    */\r\n  /*                   should be scaled, whether to load bitmaps or not,   */\r\n  /*                   whether to hint the outline, etc).                  */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    This function simply calls @FT_Get_Char_Index and @FT_Load_Glyph.  */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Load_Char( FT_Face   face,\r\n                FT_ULong  char_code,\r\n                FT_Int32  load_flags );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @enum:\r\n   *   FT_LOAD_XXX\r\n   *\r\n   * @description:\r\n   *   A list of bit-field constants used with @FT_Load_Glyph to indicate\r\n   *   what kind of operations to perform during glyph loading.\r\n   *\r\n   * @values:\r\n   *   FT_LOAD_DEFAULT ::\r\n   *     Corresponding to~0, this value is used as the default glyph load\r\n   *     operation.  In this case, the following happens:\r\n   *\r\n   *     1. FreeType looks for a bitmap for the glyph corresponding to the\r\n   *        face's current size.  If one is found, the function returns.\r\n   *        The bitmap data can be accessed from the glyph slot (see note\r\n   *        below).\r\n   *\r\n   *     2. If no embedded bitmap is searched or found, FreeType looks for a\r\n   *        scalable outline.  If one is found, it is loaded from the font\r\n   *        file, scaled to device pixels, then `hinted' to the pixel grid\r\n   *        in order to optimize it.  The outline data can be accessed from\r\n   *        the glyph slot (see note below).\r\n   *\r\n   *     Note that by default, the glyph loader doesn't render outlines into\r\n   *     bitmaps.  The following flags are used to modify this default\r\n   *     behaviour to more specific and useful cases.\r\n   *\r\n   *   FT_LOAD_NO_SCALE ::\r\n   *     Don't scale the outline glyph loaded, but keep it in font units.\r\n   *\r\n   *     This flag implies @FT_LOAD_NO_HINTING and @FT_LOAD_NO_BITMAP, and\r\n   *     unsets @FT_LOAD_RENDER.\r\n   *\r\n   *   FT_LOAD_NO_HINTING ::\r\n   *     Disable hinting.  This generally generates `blurrier' bitmap glyph\r\n   *     when the glyph is rendered in any of the anti-aliased modes.  See\r\n   *     also the note below.\r\n   *\r\n   *     This flag is implied by @FT_LOAD_NO_SCALE.\r\n   *\r\n   *   FT_LOAD_RENDER ::\r\n   *     Call @FT_Render_Glyph after the glyph is loaded.  By default, the\r\n   *     glyph is rendered in @FT_RENDER_MODE_NORMAL mode.  This can be\r\n   *     overridden by @FT_LOAD_TARGET_XXX or @FT_LOAD_MONOCHROME.\r\n   *\r\n   *     This flag is unset by @FT_LOAD_NO_SCALE.\r\n   *\r\n   *   FT_LOAD_NO_BITMAP ::\r\n   *     Ignore bitmap strikes when loading.  Bitmap-only fonts ignore this\r\n   *     flag.\r\n   *\r\n   *     @FT_LOAD_NO_SCALE always sets this flag.\r\n   *\r\n   *   FT_LOAD_VERTICAL_LAYOUT ::\r\n   *     Load the glyph for vertical text layout.  _Don't_ use it as it is\r\n   *     problematic currently.\r\n   *\r\n   *   FT_LOAD_FORCE_AUTOHINT ::\r\n   *     Indicates that the auto-hinter is preferred over the font's native\r\n   *     hinter.  See also the note below.\r\n   *\r\n   *   FT_LOAD_CROP_BITMAP ::\r\n   *     Indicates that the font driver should crop the loaded bitmap glyph\r\n   *     (i.e., remove all space around its black bits).  Not all drivers\r\n   *     implement this.\r\n   *\r\n   *   FT_LOAD_PEDANTIC ::\r\n   *     Indicates that the font driver should perform pedantic verifications\r\n   *     during glyph loading.  This is mostly used to detect broken glyphs\r\n   *     in fonts.  By default, FreeType tries to handle broken fonts also.\r\n   *\r\n   *   FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH ::\r\n   *     Ignored.  Deprecated.\r\n   *\r\n   *   FT_LOAD_NO_RECURSE ::\r\n   *     This flag is only used internally.  It merely indicates that the\r\n   *     font driver should not load composite glyphs recursively.  Instead,\r\n   *     it should set the `num_subglyph' and `subglyphs' values of the\r\n   *     glyph slot accordingly, and set `glyph->format' to\r\n   *     @FT_GLYPH_FORMAT_COMPOSITE.\r\n   *\r\n   *     The description of sub-glyphs is not available to client\r\n   *     applications for now.\r\n   *\r\n   *     This flag implies @FT_LOAD_NO_SCALE and @FT_LOAD_IGNORE_TRANSFORM.\r\n   *\r\n   *   FT_LOAD_IGNORE_TRANSFORM ::\r\n   *     Indicates that the transform matrix set by @FT_Set_Transform should\r\n   *     be ignored.\r\n   *\r\n   *   FT_LOAD_MONOCHROME ::\r\n   *     This flag is used with @FT_LOAD_RENDER to indicate that you want to\r\n   *     render an outline glyph to a 1-bit monochrome bitmap glyph, with\r\n   *     8~pixels packed into each byte of the bitmap data.\r\n   *\r\n   *     Note that this has no effect on the hinting algorithm used.  You\r\n   *     should rather use @FT_LOAD_TARGET_MONO so that the\r\n   *     monochrome-optimized hinting algorithm is used.\r\n   *\r\n   *   FT_LOAD_LINEAR_DESIGN ::\r\n   *     Indicates that the `linearHoriAdvance' and `linearVertAdvance'\r\n   *     fields of @FT_GlyphSlotRec should be kept in font units.  See\r\n   *     @FT_GlyphSlotRec for details.\r\n   *\r\n   *   FT_LOAD_NO_AUTOHINT ::\r\n   *     Disable auto-hinter.  See also the note below.\r\n   *\r\n   * @note:\r\n   *   By default, hinting is enabled and the font's native hinter (see\r\n   *   @FT_FACE_FLAG_HINTER) is preferred over the auto-hinter.  You can\r\n   *   disable hinting by setting @FT_LOAD_NO_HINTING or change the\r\n   *   precedence by setting @FT_LOAD_FORCE_AUTOHINT.  You can also set\r\n   *   @FT_LOAD_NO_AUTOHINT in case you don't want the auto-hinter to be\r\n   *   used at all.\r\n   *\r\n   *   See the description of @FT_FACE_FLAG_TRICKY for a special exception\r\n   *   (affecting only a handful of Asian fonts).\r\n   *\r\n   *   Besides deciding which hinter to use, you can also decide which\r\n   *   hinting algorithm to use.  See @FT_LOAD_TARGET_XXX for details.\r\n   *\r\n   */\r\n#define FT_LOAD_DEFAULT                      0x0\r\n#define FT_LOAD_NO_SCALE                     0x1\r\n#define FT_LOAD_NO_HINTING                   0x2\r\n#define FT_LOAD_RENDER                       0x4\r\n#define FT_LOAD_NO_BITMAP                    0x8\r\n#define FT_LOAD_VERTICAL_LAYOUT              0x10\r\n#define FT_LOAD_FORCE_AUTOHINT               0x20\r\n#define FT_LOAD_CROP_BITMAP                  0x40\r\n#define FT_LOAD_PEDANTIC                     0x80\r\n#define FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH  0x200\r\n#define FT_LOAD_NO_RECURSE                   0x400\r\n#define FT_LOAD_IGNORE_TRANSFORM             0x800\r\n#define FT_LOAD_MONOCHROME                   0x1000\r\n#define FT_LOAD_LINEAR_DESIGN                0x2000\r\n#define FT_LOAD_NO_AUTOHINT                  0x8000U\r\n\r\n  /* */\r\n\r\n  /* used internally only by certain font drivers! */\r\n#define FT_LOAD_ADVANCE_ONLY                 0x100\r\n#define FT_LOAD_SBITS_ONLY                   0x4000\r\n\r\n\r\n  /**************************************************************************\r\n   *\r\n   * @enum:\r\n   *   FT_LOAD_TARGET_XXX\r\n   *\r\n   * @description:\r\n   *   A list of values that are used to select a specific hinting algorithm\r\n   *   to use by the hinter.  You should OR one of these values to your\r\n   *   `load_flags' when calling @FT_Load_Glyph.\r\n   *\r\n   *   Note that font's native hinters may ignore the hinting algorithm you\r\n   *   have specified (e.g., the TrueType bytecode interpreter).  You can set\r\n   *   @FT_LOAD_FORCE_AUTOHINT to ensure that the auto-hinter is used.\r\n   *\r\n   *   Also note that @FT_LOAD_TARGET_LIGHT is an exception, in that it\r\n   *   always implies @FT_LOAD_FORCE_AUTOHINT.\r\n   *\r\n   * @values:\r\n   *   FT_LOAD_TARGET_NORMAL ::\r\n   *     This corresponds to the default hinting algorithm, optimized for\r\n   *     standard gray-level rendering.  For monochrome output, use\r\n   *     @FT_LOAD_TARGET_MONO instead.\r\n   *\r\n   *   FT_LOAD_TARGET_LIGHT ::\r\n   *     A lighter hinting algorithm for non-monochrome modes.  Many\r\n   *     generated glyphs are more fuzzy but better resemble its original\r\n   *     shape.  A bit like rendering on Mac OS~X.\r\n   *\r\n   *     As a special exception, this target implies @FT_LOAD_FORCE_AUTOHINT.\r\n   *\r\n   *   FT_LOAD_TARGET_MONO ::\r\n   *     Strong hinting algorithm that should only be used for monochrome\r\n   *     output.  The result is probably unpleasant if the glyph is rendered\r\n   *     in non-monochrome modes.\r\n   *\r\n   *   FT_LOAD_TARGET_LCD ::\r\n   *     A variant of @FT_LOAD_TARGET_NORMAL optimized for horizontally\r\n   *     decimated LCD displays.\r\n   *\r\n   *   FT_LOAD_TARGET_LCD_V ::\r\n   *     A variant of @FT_LOAD_TARGET_NORMAL optimized for vertically\r\n   *     decimated LCD displays.\r\n   *\r\n   * @note:\r\n   *   You should use only _one_ of the FT_LOAD_TARGET_XXX values in your\r\n   *   `load_flags'.  They can't be ORed.\r\n   *\r\n   *   If @FT_LOAD_RENDER is also set, the glyph is rendered in the\r\n   *   corresponding mode (i.e., the mode which matches the used algorithm\r\n   *   best) unless @FT_LOAD_MONOCHROME is set.\r\n   *\r\n   *   You can use a hinting algorithm that doesn't correspond to the same\r\n   *   rendering mode.  As an example, it is possible to use the `light'\r\n   *   hinting algorithm and have the results rendered in horizontal LCD\r\n   *   pixel mode, with code like\r\n   *\r\n   *     {\r\n   *       FT_Load_Glyph( face, glyph_index,\r\n   *                      load_flags | FT_LOAD_TARGET_LIGHT );\r\n   *\r\n   *       FT_Render_Glyph( face->glyph, FT_RENDER_MODE_LCD );\r\n   *     }\r\n   *\r\n   */\r\n#define FT_LOAD_TARGET_( x )   ( (FT_Int32)( (x) & 15 ) << 16 )\r\n\r\n#define FT_LOAD_TARGET_NORMAL  FT_LOAD_TARGET_( FT_RENDER_MODE_NORMAL )\r\n#define FT_LOAD_TARGET_LIGHT   FT_LOAD_TARGET_( FT_RENDER_MODE_LIGHT  )\r\n#define FT_LOAD_TARGET_MONO    FT_LOAD_TARGET_( FT_RENDER_MODE_MONO   )\r\n#define FT_LOAD_TARGET_LCD     FT_LOAD_TARGET_( FT_RENDER_MODE_LCD    )\r\n#define FT_LOAD_TARGET_LCD_V   FT_LOAD_TARGET_( FT_RENDER_MODE_LCD_V  )\r\n\r\n\r\n  /**************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_LOAD_TARGET_MODE\r\n   *\r\n   * @description:\r\n   *   Return the @FT_Render_Mode corresponding to a given\r\n   *   @FT_LOAD_TARGET_XXX value.\r\n   *\r\n   */\r\n#define FT_LOAD_TARGET_MODE( x )  ( (FT_Render_Mode)( ( (x) >> 16 ) & 15 ) )\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Set_Transform                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A function used to set the transformation that is applied to glyph */\r\n  /*    images when they are loaded into a glyph slot through              */\r\n  /*    @FT_Load_Glyph.                                                    */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    face   :: A handle to the source face object.                      */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    matrix :: A pointer to the transformation's 2x2 matrix.  Use~0 for */\r\n  /*              the identity matrix.                                     */\r\n  /*    delta  :: A pointer to the translation vector.  Use~0 for the null */\r\n  /*              vector.                                                  */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The transformation is only applied to scalable image formats after */\r\n  /*    the glyph has been loaded.  It means that hinting is unaltered by  */\r\n  /*    the transformation and is performed on the character size given in */\r\n  /*    the last call to @FT_Set_Char_Size or @FT_Set_Pixel_Sizes.         */\r\n  /*                                                                       */\r\n  /*    Note that this also transforms the `face.glyph.advance' field, but */\r\n  /*    *not* the values in `face.glyph.metrics'.                          */\r\n  /*                                                                       */\r\n  FT_EXPORT( void )\r\n  FT_Set_Transform( FT_Face     face,\r\n                    FT_Matrix*  matrix,\r\n                    FT_Vector*  delta );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Enum>                                                                */\r\n  /*    FT_Render_Mode                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    An enumeration type that lists the render modes supported by       */\r\n  /*    FreeType~2.  Each mode corresponds to a specific type of scanline  */\r\n  /*    conversion performed on the outline.                               */\r\n  /*                                                                       */\r\n  /*    For bitmap fonts and embedded bitmaps the `bitmap->pixel_mode'     */\r\n  /*    field in the @FT_GlyphSlotRec structure gives the format of the    */\r\n  /*    returned bitmap.                                                   */\r\n  /*                                                                       */\r\n  /*    All modes except @FT_RENDER_MODE_MONO use 256 levels of opacity.   */\r\n  /*                                                                       */\r\n  /* <Values>                                                              */\r\n  /*    FT_RENDER_MODE_NORMAL ::                                           */\r\n  /*      This is the default render mode; it corresponds to 8-bit         */\r\n  /*      anti-aliased bitmaps.                                            */\r\n  /*                                                                       */\r\n  /*    FT_RENDER_MODE_LIGHT ::                                            */\r\n  /*      This is equivalent to @FT_RENDER_MODE_NORMAL.  It is only        */\r\n  /*      defined as a separate value because render modes are also used   */\r\n  /*      indirectly to define hinting algorithm selectors.  See           */\r\n  /*      @FT_LOAD_TARGET_XXX for details.                                 */\r\n  /*                                                                       */\r\n  /*    FT_RENDER_MODE_MONO ::                                             */\r\n  /*      This mode corresponds to 1-bit bitmaps (with 2~levels of         */\r\n  /*      opacity).                                                        */\r\n  /*                                                                       */\r\n  /*    FT_RENDER_MODE_LCD ::                                              */\r\n  /*      This mode corresponds to horizontal RGB and BGR sub-pixel        */\r\n  /*      displays like LCD screens.  It produces 8-bit bitmaps that are   */\r\n  /*      3~times the width of the original glyph outline in pixels, and   */\r\n  /*      which use the @FT_PIXEL_MODE_LCD mode.                           */\r\n  /*                                                                       */\r\n  /*    FT_RENDER_MODE_LCD_V ::                                            */\r\n  /*      This mode corresponds to vertical RGB and BGR sub-pixel displays */\r\n  /*      (like PDA screens, rotated LCD displays, etc.).  It produces     */\r\n  /*      8-bit bitmaps that are 3~times the height of the original        */\r\n  /*      glyph outline in pixels and use the @FT_PIXEL_MODE_LCD_V mode.   */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The LCD-optimized glyph bitmaps produced by FT_Render_Glyph can be */\r\n  /*    filtered to reduce color-fringes by using @FT_Library_SetLcdFilter */\r\n  /*    (not active in the default builds).  It is up to the caller to     */\r\n  /*    either call @FT_Library_SetLcdFilter (if available) or do the      */\r\n  /*    filtering itself.                                                  */\r\n  /*                                                                       */\r\n  /*    The selected render mode only affects vector glyphs of a font.     */\r\n  /*    Embedded bitmaps often have a different pixel mode like            */\r\n  /*    @FT_PIXEL_MODE_MONO.  You can use @FT_Bitmap_Convert to transform  */\r\n  /*    them into 8-bit pixmaps.                                           */\r\n  /*                                                                       */\r\n  typedef enum  FT_Render_Mode_\r\n  {\r\n    FT_RENDER_MODE_NORMAL = 0,\r\n    FT_RENDER_MODE_LIGHT,\r\n    FT_RENDER_MODE_MONO,\r\n    FT_RENDER_MODE_LCD,\r\n    FT_RENDER_MODE_LCD_V,\r\n\r\n    FT_RENDER_MODE_MAX\r\n\r\n  } FT_Render_Mode;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Enum>                                                                */\r\n  /*    ft_render_mode_xxx                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    These constants are deprecated.  Use the corresponding             */\r\n  /*    @FT_Render_Mode values instead.                                    */\r\n  /*                                                                       */\r\n  /* <Values>                                                              */\r\n  /*    ft_render_mode_normal :: see @FT_RENDER_MODE_NORMAL                */\r\n  /*    ft_render_mode_mono   :: see @FT_RENDER_MODE_MONO                  */\r\n  /*                                                                       */\r\n#define ft_render_mode_normal  FT_RENDER_MODE_NORMAL\r\n#define ft_render_mode_mono    FT_RENDER_MODE_MONO\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Render_Glyph                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Convert a given glyph image to a bitmap.  It does so by inspecting */\r\n  /*    the glyph image format, finding the relevant renderer, and         */\r\n  /*    invoking it.                                                       */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    slot        :: A handle to the glyph slot containing the image to  */\r\n  /*                   convert.                                            */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    render_mode :: This is the render mode used to render the glyph    */\r\n  /*                   image into a bitmap.  See @FT_Render_Mode for a     */\r\n  /*                   list of possible values.                            */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Render_Glyph( FT_GlyphSlot    slot,\r\n                   FT_Render_Mode  render_mode );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Enum>                                                                */\r\n  /*    FT_Kerning_Mode                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    An enumeration used to specify which kerning values to return in   */\r\n  /*    @FT_Get_Kerning.                                                   */\r\n  /*                                                                       */\r\n  /* <Values>                                                              */\r\n  /*    FT_KERNING_DEFAULT  :: Return scaled and grid-fitted kerning       */\r\n  /*                           distances (value is~0).                     */\r\n  /*                                                                       */\r\n  /*    FT_KERNING_UNFITTED :: Return scaled but un-grid-fitted kerning    */\r\n  /*                           distances.                                  */\r\n  /*                                                                       */\r\n  /*    FT_KERNING_UNSCALED :: Return the kerning vector in original font  */\r\n  /*                           units.                                      */\r\n  /*                                                                       */\r\n  typedef enum  FT_Kerning_Mode_\r\n  {\r\n    FT_KERNING_DEFAULT  = 0,\r\n    FT_KERNING_UNFITTED,\r\n    FT_KERNING_UNSCALED\r\n\r\n  } FT_Kerning_Mode;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Const>                                                               */\r\n  /*    ft_kerning_default                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This constant is deprecated.  Please use @FT_KERNING_DEFAULT       */\r\n  /*    instead.                                                           */\r\n  /*                                                                       */\r\n#define ft_kerning_default   FT_KERNING_DEFAULT\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Const>                                                               */\r\n  /*    ft_kerning_unfitted                                                */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This constant is deprecated.  Please use @FT_KERNING_UNFITTED      */\r\n  /*    instead.                                                           */\r\n  /*                                                                       */\r\n#define ft_kerning_unfitted  FT_KERNING_UNFITTED\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Const>                                                               */\r\n  /*    ft_kerning_unscaled                                                */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This constant is deprecated.  Please use @FT_KERNING_UNSCALED      */\r\n  /*    instead.                                                           */\r\n  /*                                                                       */\r\n#define ft_kerning_unscaled  FT_KERNING_UNSCALED\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Get_Kerning                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Return the kerning vector between two glyphs of a same face.       */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face        :: A handle to a source face object.                   */\r\n  /*                                                                       */\r\n  /*    left_glyph  :: The index of the left glyph in the kern pair.       */\r\n  /*                                                                       */\r\n  /*    right_glyph :: The index of the right glyph in the kern pair.      */\r\n  /*                                                                       */\r\n  /*    kern_mode   :: See @FT_Kerning_Mode for more information.          */\r\n  /*                   Determines the scale and dimension of the returned  */\r\n  /*                   kerning vector.                                     */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    akerning    :: The kerning vector.  This is either in font units   */\r\n  /*                   or in pixels (26.6 format) for scalable formats,    */\r\n  /*                   and in pixels for fixed-sizes formats.              */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    Only horizontal layouts (left-to-right & right-to-left) are        */\r\n  /*    supported by this method.  Other layouts, or more sophisticated    */\r\n  /*    kernings, are out of the scope of this API function -- they can be */\r\n  /*    implemented through format-specific interfaces.                    */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Get_Kerning( FT_Face     face,\r\n                  FT_UInt     left_glyph,\r\n                  FT_UInt     right_glyph,\r\n                  FT_UInt     kern_mode,\r\n                  FT_Vector  *akerning );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Get_Track_Kerning                                               */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Return the track kerning for a given face object at a given size.  */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face       :: A handle to a source face object.                    */\r\n  /*                                                                       */\r\n  /*    point_size :: The point size in 16.16 fractional points.           */\r\n  /*                                                                       */\r\n  /*    degree     :: The degree of tightness.                             */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    akerning   :: The kerning in 16.16 fractional points.              */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Get_Track_Kerning( FT_Face    face,\r\n                        FT_Fixed   point_size,\r\n                        FT_Int     degree,\r\n                        FT_Fixed*  akerning );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Get_Glyph_Name                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Retrieve the ASCII name of a given glyph in a face.  This only     */\r\n  /*    works for those faces where @FT_HAS_GLYPH_NAMES(face) returns~1.   */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face        :: A handle to a source face object.                   */\r\n  /*                                                                       */\r\n  /*    glyph_index :: The glyph index.                                    */\r\n  /*                                                                       */\r\n  /*    buffer_max  :: The maximal number of bytes available in the        */\r\n  /*                   buffer.                                             */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    buffer      :: A pointer to a target buffer where the name is      */\r\n  /*                   copied to.                                          */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    An error is returned if the face doesn't provide glyph names or if */\r\n  /*    the glyph index is invalid.  In all cases of failure, the first    */\r\n  /*    byte of `buffer' is set to~0 to indicate an empty name.            */\r\n  /*                                                                       */\r\n  /*    The glyph name is truncated to fit within the buffer if it is too  */\r\n  /*    long.  The returned string is always zero-terminated.              */\r\n  /*                                                                       */\r\n  /*    Be aware that FreeType reorders glyph indices internally so that   */\r\n  /*    glyph index~0 always corresponds to the `missing glyph' (called    */\r\n  /*    `.notdef').                                                        */\r\n  /*                                                                       */\r\n  /*    This function is not compiled within the library if the config     */\r\n  /*    macro `FT_CONFIG_OPTION_NO_GLYPH_NAMES' is defined in              */\r\n  /*    `include/freetype/config/ftoptions.h'.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Get_Glyph_Name( FT_Face     face,\r\n                     FT_UInt     glyph_index,\r\n                     FT_Pointer  buffer,\r\n                     FT_UInt     buffer_max );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Get_Postscript_Name                                             */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Retrieve the ASCII PostScript name of a given face, if available.  */\r\n  /*    This only works with PostScript and TrueType fonts.                */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face :: A handle to the source face object.                        */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    A pointer to the face's PostScript name.  NULL if unavailable.     */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The returned pointer is owned by the face and is destroyed with    */\r\n  /*    it.                                                                */\r\n  /*                                                                       */\r\n  FT_EXPORT( const char* )\r\n  FT_Get_Postscript_Name( FT_Face  face );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Select_Charmap                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Select a given charmap by its encoding tag (as listed in           */\r\n  /*    `freetype.h').                                                     */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    face     :: A handle to the source face object.                    */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    encoding :: A handle to the selected encoding.                     */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    This function returns an error if no charmap in the face           */\r\n  /*    corresponds to the encoding queried here.                          */\r\n  /*                                                                       */\r\n  /*    Because many fonts contain more than a single cmap for Unicode     */\r\n  /*    encoding, this function has some special code to select the one    */\r\n  /*    which covers Unicode best (`best' in the sense that a UCS-4 cmap   */\r\n  /*    is preferred to a UCS-2 cmap).  It is thus preferable to           */\r\n  /*    @FT_Set_Charmap in this case.                                      */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Select_Charmap( FT_Face      face,\r\n                     FT_Encoding  encoding );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Set_Charmap                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Select a given charmap for character code to glyph index mapping.  */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    face    :: A handle to the source face object.                     */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    charmap :: A handle to the selected charmap.                       */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    This function returns an error if the charmap is not part of       */\r\n  /*    the face (i.e., if it is not listed in the `face->charmaps'        */\r\n  /*    table).                                                            */\r\n  /*                                                                       */\r\n  /*    It also fails if a type~14 charmap is selected.                    */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Set_Charmap( FT_Face     face,\r\n                  FT_CharMap  charmap );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Get_Charmap_Index\r\n   *\r\n   * @description:\r\n   *   Retrieve index of a given charmap.\r\n   *\r\n   * @input:\r\n   *   charmap ::\r\n   *     A handle to a charmap.\r\n   *\r\n   * @return:\r\n   *   The index into the array of character maps within the face to which\r\n   *   `charmap' belongs.  If an error occurs, -1 is returned.\r\n   *\r\n   */\r\n  FT_EXPORT( FT_Int )\r\n  FT_Get_Charmap_Index( FT_CharMap  charmap );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Get_Char_Index                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Return the glyph index of a given character code.  This function   */\r\n  /*    uses a charmap object to do the mapping.                           */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face     :: A handle to the source face object.                    */\r\n  /*                                                                       */\r\n  /*    charcode :: The character code.                                    */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    The glyph index.  0~means `undefined character code'.              */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    If you use FreeType to manipulate the contents of font files       */\r\n  /*    directly, be aware that the glyph index returned by this function  */\r\n  /*    doesn't always correspond to the internal indices used within      */\r\n  /*    the file.  This is done to ensure that value~0 always corresponds  */\r\n  /*    to the `missing glyph'.                                            */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_UInt )\r\n  FT_Get_Char_Index( FT_Face   face,\r\n                     FT_ULong  charcode );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Get_First_Char                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This function is used to return the first character code in the    */\r\n  /*    current charmap of a given face.  It also returns the              */\r\n  /*    corresponding glyph index.                                         */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face    :: A handle to the source face object.                     */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    agindex :: Glyph index of first character code.  0~if charmap is   */\r\n  /*               empty.                                                  */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    The charmap's first character code.                                */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    You should use this function with @FT_Get_Next_Char to be able to  */\r\n  /*    parse all character codes available in a given charmap.  The code  */\r\n  /*    should look like this:                                             */\r\n  /*                                                                       */\r\n  /*    {                                                                  */\r\n  /*      FT_ULong  charcode;                                              */\r\n  /*      FT_UInt   gindex;                                                */\r\n  /*                                                                       */\r\n  /*                                                                       */\r\n  /*      charcode = FT_Get_First_Char( face, &gindex );                   */\r\n  /*      while ( gindex != 0 )                                            */\r\n  /*      {                                                                */\r\n  /*        ... do something with (charcode,gindex) pair ...               */\r\n  /*                                                                       */\r\n  /*        charcode = FT_Get_Next_Char( face, charcode, &gindex );        */\r\n  /*      }                                                                */\r\n  /*    }                                                                  */\r\n  /*                                                                       */\r\n  /*    Note that `*agindex' is set to~0 if the charmap is empty.  The     */\r\n  /*    result itself can be~0 in two cases: if the charmap is empty or    */\r\n  /*    if the value~0 is the first valid character code.                  */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_ULong )\r\n  FT_Get_First_Char( FT_Face   face,\r\n                     FT_UInt  *agindex );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Get_Next_Char                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This function is used to return the next character code in the     */\r\n  /*    current charmap of a given face following the value `char_code',   */\r\n  /*    as well as the corresponding glyph index.                          */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face      :: A handle to the source face object.                   */\r\n  /*    char_code :: The starting character code.                          */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    agindex   :: Glyph index of next character code.  0~if charmap     */\r\n  /*                 is empty.                                             */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    The charmap's next character code.                                 */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    You should use this function with @FT_Get_First_Char to walk       */\r\n  /*    over all character codes available in a given charmap.  See the    */\r\n  /*    note for this function for a simple code example.                  */\r\n  /*                                                                       */\r\n  /*    Note that `*agindex' is set to~0 when there are no more codes in   */\r\n  /*    the charmap.                                                       */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_ULong )\r\n  FT_Get_Next_Char( FT_Face    face,\r\n                    FT_ULong   char_code,\r\n                    FT_UInt   *agindex );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Get_Name_Index                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Return the glyph index of a given glyph name.  This function uses  */\r\n  /*    driver specific objects to do the translation.                     */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face       :: A handle to the source face object.                  */\r\n  /*                                                                       */\r\n  /*    glyph_name :: The glyph name.                                      */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    The glyph index.  0~means `undefined character code'.              */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_UInt )\r\n  FT_Get_Name_Index( FT_Face     face,\r\n                     FT_String*  glyph_name );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_SUBGLYPH_FLAG_XXX\r\n   *\r\n   * @description:\r\n   *   A list of constants used to describe subglyphs.  Please refer to the\r\n   *   TrueType specification for the meaning of the various flags.\r\n   *\r\n   * @values:\r\n   *   FT_SUBGLYPH_FLAG_ARGS_ARE_WORDS ::\r\n   *   FT_SUBGLYPH_FLAG_ARGS_ARE_XY_VALUES ::\r\n   *   FT_SUBGLYPH_FLAG_ROUND_XY_TO_GRID ::\r\n   *   FT_SUBGLYPH_FLAG_SCALE ::\r\n   *   FT_SUBGLYPH_FLAG_XY_SCALE ::\r\n   *   FT_SUBGLYPH_FLAG_2X2 ::\r\n   *   FT_SUBGLYPH_FLAG_USE_MY_METRICS ::\r\n   *\r\n   */\r\n#define FT_SUBGLYPH_FLAG_ARGS_ARE_WORDS          1\r\n#define FT_SUBGLYPH_FLAG_ARGS_ARE_XY_VALUES      2\r\n#define FT_SUBGLYPH_FLAG_ROUND_XY_TO_GRID        4\r\n#define FT_SUBGLYPH_FLAG_SCALE                   8\r\n#define FT_SUBGLYPH_FLAG_XY_SCALE             0x40\r\n#define FT_SUBGLYPH_FLAG_2X2                  0x80\r\n#define FT_SUBGLYPH_FLAG_USE_MY_METRICS      0x200\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @func:\r\n   *   FT_Get_SubGlyph_Info\r\n   *\r\n   * @description:\r\n   *   Retrieve a description of a given subglyph.  Only use it if\r\n   *   `glyph->format' is @FT_GLYPH_FORMAT_COMPOSITE; an error is\r\n   *   returned otherwise.\r\n   *\r\n   * @input:\r\n   *   glyph ::\r\n   *     The source glyph slot.\r\n   *\r\n   *   sub_index ::\r\n   *     The index of the subglyph.  Must be less than\r\n   *     `glyph->num_subglyphs'.\r\n   *\r\n   * @output:\r\n   *   p_index ::\r\n   *     The glyph index of the subglyph.\r\n   *\r\n   *   p_flags ::\r\n   *     The subglyph flags, see @FT_SUBGLYPH_FLAG_XXX.\r\n   *\r\n   *   p_arg1 ::\r\n   *     The subglyph's first argument (if any).\r\n   *\r\n   *   p_arg2 ::\r\n   *     The subglyph's second argument (if any).\r\n   *\r\n   *   p_transform ::\r\n   *     The subglyph transformation (if any).\r\n   *\r\n   * @return:\r\n   *   FreeType error code.  0~means success.\r\n   *\r\n   * @note:\r\n   *   The values of `*p_arg1', `*p_arg2', and `*p_transform' must be\r\n   *   interpreted depending on the flags returned in `*p_flags'.  See the\r\n   *   TrueType specification for details.\r\n   *\r\n   */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Get_SubGlyph_Info( FT_GlyphSlot  glyph,\r\n                        FT_UInt       sub_index,\r\n                        FT_Int       *p_index,\r\n                        FT_UInt      *p_flags,\r\n                        FT_Int       *p_arg1,\r\n                        FT_Int       *p_arg2,\r\n                        FT_Matrix    *p_transform );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Enum>                                                                */\r\n  /*    FT_FSTYPE_XXX                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A list of bit flags used in the `fsType' field of the OS/2 table   */\r\n  /*    in a TrueType or OpenType font and the `FSType' entry in a         */\r\n  /*    PostScript font.  These bit flags are returned by                  */\r\n  /*    @FT_Get_FSType_Flags; they inform client applications of embedding */\r\n  /*    and subsetting restrictions associated with a font.                */\r\n  /*                                                                       */\r\n  /*    See http://www.adobe.com/devnet/acrobat/pdfs/FontPolicies.pdf for  */\r\n  /*    more details.                                                      */\r\n  /*                                                                       */\r\n  /* <Values>                                                              */\r\n  /*    FT_FSTYPE_INSTALLABLE_EMBEDDING ::                                 */\r\n  /*      Fonts with no fsType bit set may be embedded and permanently     */\r\n  /*      installed on the remote system by an application.                */\r\n  /*                                                                       */\r\n  /*    FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING ::                          */\r\n  /*      Fonts that have only this bit set must not be modified, embedded */\r\n  /*      or exchanged in any manner without first obtaining permission of */\r\n  /*      the font software copyright owner.                               */\r\n  /*                                                                       */\r\n  /*    FT_FSTYPE_PREVIEW_AND_PRINT_EMBEDDING ::                           */\r\n  /*      If this bit is set, the font may be embedded and temporarily     */\r\n  /*      loaded on the remote system.  Documents containing Preview &     */\r\n  /*      Print fonts must be opened `read-only'; no edits can be applied  */\r\n  /*      to the document.                                                 */\r\n  /*                                                                       */\r\n  /*    FT_FSTYPE_EDITABLE_EMBEDDING ::                                    */\r\n  /*      If this bit is set, the font may be embedded but must only be    */\r\n  /*      installed temporarily on other systems.  In contrast to Preview  */\r\n  /*      & Print fonts, documents containing editable fonts may be opened */\r\n  /*      for reading, editing is permitted, and changes may be saved.     */\r\n  /*                                                                       */\r\n  /*    FT_FSTYPE_NO_SUBSETTING ::                                         */\r\n  /*      If this bit is set, the font may not be subsetted prior to       */\r\n  /*      embedding.                                                       */\r\n  /*                                                                       */\r\n  /*    FT_FSTYPE_BITMAP_EMBEDDING_ONLY ::                                 */\r\n  /*      If this bit is set, only bitmaps contained in the font may be    */\r\n  /*      embedded; no outline data may be embedded.  If there are no      */\r\n  /*      bitmaps available in the font, then the font is unembeddable.    */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    While the fsType flags can indicate that a font may be embedded, a */\r\n  /*    license with the font vendor may be separately required to use the */\r\n  /*    font in this way.                                                  */\r\n  /*                                                                       */\r\n#define FT_FSTYPE_INSTALLABLE_EMBEDDING         0x0000\r\n#define FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING  0x0002\r\n#define FT_FSTYPE_PREVIEW_AND_PRINT_EMBEDDING   0x0004\r\n#define FT_FSTYPE_EDITABLE_EMBEDDING            0x0008\r\n#define FT_FSTYPE_NO_SUBSETTING                 0x0100\r\n#define FT_FSTYPE_BITMAP_EMBEDDING_ONLY         0x0200\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Get_FSType_Flags                                                */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Return the fsType flags for a font.                                */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face :: A handle to the source face object.                        */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    The fsType flags, @FT_FSTYPE_XXX.                                  */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    Use this function rather than directly reading the `fs_type' field */\r\n  /*    in the @PS_FontInfoRec structure which is only guaranteed to       */\r\n  /*    return the correct results for Type~1 fonts.                       */\r\n  /*                                                                       */\r\n  /* <Since>                                                               */\r\n  /*    2.3.8                                                              */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_UShort )\r\n  FT_Get_FSType_Flags( FT_Face  face );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    glyph_variants                                                     */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    Glyph Variants                                                     */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    The FreeType~2 interface to Unicode Ideographic Variation          */\r\n  /*    Sequences (IVS), using the SFNT cmap format~14.                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Many CJK characters have variant forms.  They are a sort of grey   */\r\n  /*    area somewhere between being totally irrelevant and semantically   */\r\n  /*    distinct; for this reason, the Unicode consortium decided to       */\r\n  /*    introduce Ideographic Variation Sequences (IVS), consisting of a   */\r\n  /*    Unicode base character and one of 240 variant selectors            */\r\n  /*    (U+E0100-U+E01EF), instead of further extending the already huge   */\r\n  /*    code range for CJK characters.                                     */\r\n  /*                                                                       */\r\n  /*    An IVS is registered and unique; for further details please refer  */\r\n  /*    to Unicode Technical Report #37, the Ideographic Variation         */\r\n  /*    Database.  To date (October 2007), the character with the most     */\r\n  /*    variants is U+908A, having 8~such IVS.                             */\r\n  /*                                                                       */\r\n  /*    Adobe and MS decided to support IVS with a new cmap subtable       */\r\n  /*    (format~14).  It is an odd subtable because it is not a mapping of */\r\n  /*    input code points to glyphs, but contains lists of all variants    */\r\n  /*    supported by the font.                                             */\r\n  /*                                                                       */\r\n  /*    A variant may be either `default' or `non-default'.  A default     */\r\n  /*    variant is the one you will get for that code point if you look it */\r\n  /*    up in the standard Unicode cmap.  A non-default variant is a       */\r\n  /*    different glyph.                                                   */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Face_GetCharVariantIndex                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Return the glyph index of a given character code as modified by    */\r\n  /*    the variation selector.                                            */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face ::                                                            */\r\n  /*      A handle to the source face object.                              */\r\n  /*                                                                       */\r\n  /*    charcode ::                                                        */\r\n  /*      The character code point in Unicode.                             */\r\n  /*                                                                       */\r\n  /*    variantSelector ::                                                 */\r\n  /*      The Unicode code point of the variation selector.                */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    The glyph index.  0~means either `undefined character code', or    */\r\n  /*    `undefined selector code', or `no variation selector cmap          */\r\n  /*    subtable', or `current CharMap is not Unicode'.                    */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    If you use FreeType to manipulate the contents of font files       */\r\n  /*    directly, be aware that the glyph index returned by this function  */\r\n  /*    doesn't always correspond to the internal indices used within      */\r\n  /*    the file.  This is done to ensure that value~0 always corresponds  */\r\n  /*    to the `missing glyph'.                                            */\r\n  /*                                                                       */\r\n  /*    This function is only meaningful if                                */\r\n  /*      a) the font has a variation selector cmap sub table,             */\r\n  /*    and                                                                */\r\n  /*      b) the current charmap has a Unicode encoding.                   */\r\n  /*                                                                       */\r\n  /* <Since>                                                               */\r\n  /*    2.3.6                                                              */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_UInt )\r\n  FT_Face_GetCharVariantIndex( FT_Face   face,\r\n                               FT_ULong  charcode,\r\n                               FT_ULong  variantSelector );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Face_GetCharVariantIsDefault                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Check whether this variant of this Unicode character is the one to */\r\n  /*    be found in the `cmap'.                                            */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face ::                                                            */\r\n  /*      A handle to the source face object.                              */\r\n  /*                                                                       */\r\n  /*    charcode ::                                                        */\r\n  /*      The character codepoint in Unicode.                              */\r\n  /*                                                                       */\r\n  /*    variantSelector ::                                                 */\r\n  /*      The Unicode codepoint of the variation selector.                 */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    1~if found in the standard (Unicode) cmap, 0~if found in the       */\r\n  /*    variation selector cmap, or -1 if it is not a variant.             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    This function is only meaningful if the font has a variation       */\r\n  /*    selector cmap subtable.                                            */\r\n  /*                                                                       */\r\n  /* <Since>                                                               */\r\n  /*    2.3.6                                                              */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Int )\r\n  FT_Face_GetCharVariantIsDefault( FT_Face   face,\r\n                                   FT_ULong  charcode,\r\n                                   FT_ULong  variantSelector );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Face_GetVariantSelectors                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Return a zero-terminated list of Unicode variant selectors found   */\r\n  /*    in the font.                                                       */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face ::                                                            */\r\n  /*      A handle to the source face object.                              */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    A pointer to an array of selector code points, or NULL if there is */\r\n  /*    no valid variant selector cmap subtable.                           */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The last item in the array is~0; the array is owned by the         */\r\n  /*    @FT_Face object but can be overwritten or released on the next     */\r\n  /*    call to a FreeType function.                                       */\r\n  /*                                                                       */\r\n  /* <Since>                                                               */\r\n  /*    2.3.6                                                              */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_UInt32* )\r\n  FT_Face_GetVariantSelectors( FT_Face  face );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Face_GetVariantsOfChar                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Return a zero-terminated list of Unicode variant selectors found   */\r\n  /*    for the specified character code.                                  */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face ::                                                            */\r\n  /*      A handle to the source face object.                              */\r\n  /*                                                                       */\r\n  /*    charcode ::                                                        */\r\n  /*      The character codepoint in Unicode.                              */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    A pointer to an array of variant selector code points which are    */\r\n  /*    active for the given character, or NULL if the corresponding list  */\r\n  /*    is empty.                                                          */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The last item in the array is~0; the array is owned by the         */\r\n  /*    @FT_Face object but can be overwritten or released on the next     */\r\n  /*    call to a FreeType function.                                       */\r\n  /*                                                                       */\r\n  /* <Since>                                                               */\r\n  /*    2.3.6                                                              */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_UInt32* )\r\n  FT_Face_GetVariantsOfChar( FT_Face   face,\r\n                             FT_ULong  charcode );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Face_GetCharsOfVariant                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Return a zero-terminated list of Unicode character codes found for */\r\n  /*    the specified variant selector.                                    */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face ::                                                            */\r\n  /*      A handle to the source face object.                              */\r\n  /*                                                                       */\r\n  /*    variantSelector ::                                                 */\r\n  /*      The variant selector code point in Unicode.                      */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    A list of all the code points which are specified by this selector */\r\n  /*    (both default and non-default codes are returned) or NULL if there */\r\n  /*    is no valid cmap or the variant selector is invalid.               */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The last item in the array is~0; the array is owned by the         */\r\n  /*    @FT_Face object but can be overwritten or released on the next     */\r\n  /*    call to a FreeType function.                                       */\r\n  /*                                                                       */\r\n  /* <Since>                                                               */\r\n  /*    2.3.6                                                              */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_UInt32* )\r\n  FT_Face_GetCharsOfVariant( FT_Face   face,\r\n                             FT_ULong  variantSelector );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    computations                                                       */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    Computations                                                       */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    Crunching fixed numbers and vectors.                               */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This section contains various functions used to perform            */\r\n  /*    computations on 16.16 fixed-float numbers or 2d vectors.           */\r\n  /*                                                                       */\r\n  /* <Order>                                                               */\r\n  /*    FT_MulDiv                                                          */\r\n  /*    FT_MulFix                                                          */\r\n  /*    FT_DivFix                                                          */\r\n  /*    FT_RoundFix                                                        */\r\n  /*    FT_CeilFix                                                         */\r\n  /*    FT_FloorFix                                                        */\r\n  /*    FT_Vector_Transform                                                */\r\n  /*    FT_Matrix_Multiply                                                 */\r\n  /*    FT_Matrix_Invert                                                   */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_MulDiv                                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A very simple function used to perform the computation `(a*b)/c'   */\r\n  /*    with maximal accuracy (it uses a 64-bit intermediate integer       */\r\n  /*    whenever necessary).                                               */\r\n  /*                                                                       */\r\n  /*    This function isn't necessarily as fast as some processor specific */\r\n  /*    operations, but is at least completely portable.                   */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    a :: The first multiplier.                                         */\r\n  /*    b :: The second multiplier.                                        */\r\n  /*    c :: The divisor.                                                  */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    The result of `(a*b)/c'.  This function never traps when trying to */\r\n  /*    divide by zero; it simply returns `MaxInt' or `MinInt' depending   */\r\n  /*    on the signs of `a' and `b'.                                       */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Long )\r\n  FT_MulDiv( FT_Long  a,\r\n             FT_Long  b,\r\n             FT_Long  c );\r\n\r\n\r\n  /* */\r\n\r\n  /* The following #if 0 ... #endif is for the documentation formatter, */\r\n  /* hiding the internal `FT_MULFIX_INLINED' macro.                     */\r\n\r\n#if 0\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_MulFix                                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A very simple function used to perform the computation             */\r\n  /*    `(a*b)/0x10000' with maximal accuracy.  Most of the time this is   */\r\n  /*    used to multiply a given value by a 16.16 fixed float factor.      */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    a :: The first multiplier.                                         */\r\n  /*    b :: The second multiplier.  Use a 16.16 factor here whenever      */\r\n  /*         possible (see note below).                                    */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    The result of `(a*b)/0x10000'.                                     */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    This function has been optimized for the case where the absolute   */\r\n  /*    value of `a' is less than 2048, and `b' is a 16.16 scaling factor. */\r\n  /*    As this happens mainly when scaling from notional units to         */\r\n  /*    fractional pixels in FreeType, it resulted in noticeable speed     */\r\n  /*    improvements between versions 2.x and 1.x.                         */\r\n  /*                                                                       */\r\n  /*    As a conclusion, always try to place a 16.16 factor as the         */\r\n  /*    _second_ argument of this function; this can make a great          */\r\n  /*    difference.                                                        */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Long )\r\n  FT_MulFix( FT_Long  a,\r\n             FT_Long  b );\r\n\r\n  /* */\r\n#endif\r\n\r\n#ifdef FT_MULFIX_INLINED\r\n#define FT_MulFix( a, b )  FT_MULFIX_INLINED( a, b )\r\n#else\r\n  FT_EXPORT( FT_Long )\r\n  FT_MulFix( FT_Long  a,\r\n             FT_Long  b );\r\n#endif\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_DivFix                                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A very simple function used to perform the computation             */\r\n  /*    `(a*0x10000)/b' with maximal accuracy.  Most of the time, this is  */\r\n  /*    used to divide a given value by a 16.16 fixed float factor.        */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    a :: The first multiplier.                                         */\r\n  /*    b :: The second multiplier.  Use a 16.16 factor here whenever      */\r\n  /*         possible (see note below).                                    */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    The result of `(a*0x10000)/b'.                                     */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The optimization for FT_DivFix() is simple: If (a~<<~16) fits in   */\r\n  /*    32~bits, then the division is computed directly.  Otherwise, we    */\r\n  /*    use a specialized version of @FT_MulDiv.                           */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Long )\r\n  FT_DivFix( FT_Long  a,\r\n             FT_Long  b );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_RoundFix                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A very simple function used to round a 16.16 fixed number.         */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    a :: The number to be rounded.                                     */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    The result of `(a + 0x8000) & -0x10000'.                           */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Fixed )\r\n  FT_RoundFix( FT_Fixed  a );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_CeilFix                                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A very simple function used to compute the ceiling function of a   */\r\n  /*    16.16 fixed number.                                                */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    a :: The number for which the ceiling function is to be computed.  */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    The result of `(a + 0x10000 - 1) & -0x10000'.                      */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Fixed )\r\n  FT_CeilFix( FT_Fixed  a );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_FloorFix                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A very simple function used to compute the floor function of a     */\r\n  /*    16.16 fixed number.                                                */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    a :: The number for which the floor function is to be computed.    */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    The result of `a & -0x10000'.                                      */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Fixed )\r\n  FT_FloorFix( FT_Fixed  a );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Vector_Transform                                                */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Transform a single vector through a 2x2 matrix.                    */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    vector :: The target vector to transform.                          */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    matrix :: A pointer to the source 2x2 matrix.                      */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The result is undefined if either `vector' or `matrix' is invalid. */\r\n  /*                                                                       */\r\n  FT_EXPORT( void )\r\n  FT_Vector_Transform( FT_Vector*        vec,\r\n                       const FT_Matrix*  matrix );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    version                                                            */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    FreeType Version                                                   */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    Functions and macros related to FreeType versions.                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Note that those functions and macros are of limited use because    */\r\n  /*    even a new release of FreeType with only documentation changes     */\r\n  /*    increases the version number.                                      */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @enum:\r\n   *   FREETYPE_XXX\r\n   *\r\n   * @description:\r\n   *   These three macros identify the FreeType source code version.\r\n   *   Use @FT_Library_Version to access them at runtime.\r\n   *\r\n   * @values:\r\n   *   FREETYPE_MAJOR :: The major version number.\r\n   *   FREETYPE_MINOR :: The minor version number.\r\n   *   FREETYPE_PATCH :: The patch level.\r\n   *\r\n   * @note:\r\n   *   The version number of FreeType if built as a dynamic link library\r\n   *   with the `libtool' package is _not_ controlled by these three\r\n   *   macros.\r\n   *\r\n   */\r\n#define FREETYPE_MAJOR  2\r\n#define FREETYPE_MINOR  4\r\n#define FREETYPE_PATCH  8\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Library_Version                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Return the version of the FreeType library being used.  This is    */\r\n  /*    useful when dynamically linking to the library, since one cannot   */\r\n  /*    use the macros @FREETYPE_MAJOR, @FREETYPE_MINOR, and               */\r\n  /*    @FREETYPE_PATCH.                                                   */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    library :: A source library handle.                                */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    amajor  :: The major version number.                               */\r\n  /*                                                                       */\r\n  /*    aminor  :: The minor version number.                               */\r\n  /*                                                                       */\r\n  /*    apatch  :: The patch version number.                               */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The reason why this function takes a `library' argument is because */\r\n  /*    certain programs implement library initialization in a custom way  */\r\n  /*    that doesn't use @FT_Init_FreeType.                                */\r\n  /*                                                                       */\r\n  /*    In such cases, the library version might not be available before   */\r\n  /*    the library object has been created.                               */\r\n  /*                                                                       */\r\n  FT_EXPORT( void )\r\n  FT_Library_Version( FT_Library   library,\r\n                      FT_Int      *amajor,\r\n                      FT_Int      *aminor,\r\n                      FT_Int      *apatch );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Face_CheckTrueTypePatents                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Parse all bytecode instructions of a TrueType font file to check   */\r\n  /*    whether any of the patented opcodes are used.  This is only useful */\r\n  /*    if you want to be able to use the unpatented hinter with           */\r\n  /*    fonts that do *not* use these opcodes.                             */\r\n  /*                                                                       */\r\n  /*    Note that this function parses *all* glyph instructions in the     */\r\n  /*    font file, which may be slow.                                      */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face :: A face handle.                                             */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    1~if this is a TrueType font that uses one of the patented         */\r\n  /*    opcodes, 0~otherwise.                                              */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    Since May 2010, TrueType hinting is no longer patented.            */\r\n  /*                                                                       */\r\n  /* <Since>                                                               */\r\n  /*    2.3.5                                                              */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Bool )\r\n  FT_Face_CheckTrueTypePatents( FT_Face  face );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Face_SetUnpatentedHinting                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Enable or disable the unpatented hinter for a given face.          */\r\n  /*    Only enable it if you have determined that the face doesn't        */\r\n  /*    use any patented opcodes (see @FT_Face_CheckTrueTypePatents).      */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face  :: A face handle.                                            */\r\n  /*                                                                       */\r\n  /*    value :: New boolean setting.                                      */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    The old setting value.  This will always be false if this is not   */\r\n  /*    an SFNT font, or if the unpatented hinter is not compiled in this  */\r\n  /*    instance of the library.                                           */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    Since May 2010, TrueType hinting is no longer patented.            */\r\n  /*                                                                       */\r\n  /* <Since>                                                               */\r\n  /*    2.3.5                                                              */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Bool )\r\n  FT_Face_SetUnpatentedHinting( FT_Face  face,\r\n                                FT_Bool  value );\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FREETYPE_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftadvanc.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftadvanc.h                                                             */\r\n/*                                                                         */\r\n/*    Quick computation of advance widths (specification only).            */\r\n/*                                                                         */\r\n/*  Copyright 2008 by                                                      */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTADVANC_H__\r\n#define __FTADVANC_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /**************************************************************************\r\n   *\r\n   * @section:\r\n   *   quick_advance\r\n   *\r\n   * @title:\r\n   *   Quick retrieval of advance values\r\n   *\r\n   * @abstract:\r\n   *   Retrieve horizontal and vertical advance values without processing\r\n   *   glyph outlines, if possible.\r\n   *\r\n   * @description:\r\n   *   This section contains functions to quickly extract advance values\r\n   *   without handling glyph outlines, if possible.\r\n   */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Const>                                                               */\r\n  /*    FT_ADVANCE_FLAG_FAST_ONLY                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A bit-flag to be OR-ed with the `flags' parameter of the           */\r\n  /*    @FT_Get_Advance and @FT_Get_Advances functions.                    */\r\n  /*                                                                       */\r\n  /*    If set, it indicates that you want these functions to fail if the  */\r\n  /*    corresponding hinting mode or font driver doesn't allow for very   */\r\n  /*    quick advance computation.                                         */\r\n  /*                                                                       */\r\n  /*    Typically, glyphs which are either unscaled, unhinted, bitmapped,  */\r\n  /*    or light-hinted can have their advance width computed very         */\r\n  /*    quickly.                                                           */\r\n  /*                                                                       */\r\n  /*    Normal and bytecode hinted modes, which require loading, scaling,  */\r\n  /*    and hinting of the glyph outline, are extremely slow by            */\r\n  /*    comparison.                                                        */\r\n  /*                                                                       */\r\n#define FT_ADVANCE_FLAG_FAST_ONLY  0x20000000UL\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Get_Advance                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Retrieve the advance value of a given glyph outline in an          */\r\n  /*    @FT_Face.  By default, the unhinted advance is returned in font    */\r\n  /*    units.                                                             */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face       :: The source @FT_Face handle.                          */\r\n  /*                                                                       */\r\n  /*    gindex     :: The glyph index.                                     */\r\n  /*                                                                       */\r\n  /*    load_flags :: A set of bit flags similar to those used when        */\r\n  /*                  calling @FT_Load_Glyph, used to determine what kind  */\r\n  /*                  of advances you need.                                */\r\n  /* <Output>                                                              */\r\n  /*    padvance :: The advance value, in either font units or 16.16       */\r\n  /*                format.                                                */\r\n  /*                                                                       */\r\n  /*                If @FT_LOAD_VERTICAL_LAYOUT is set, this is the        */\r\n  /*                vertical advance corresponding to a vertical layout.   */\r\n  /*                Otherwise, it is the horizontal advance in a           */\r\n  /*                horizontal layout.                                     */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0 means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    This function may fail if you use @FT_ADVANCE_FLAG_FAST_ONLY and   */\r\n  /*    if the corresponding font backend doesn't have a quick way to      */\r\n  /*    retrieve the advances.                                             */\r\n  /*                                                                       */\r\n  /*    A scaled advance is returned in 16.16 format but isn't transformed */\r\n  /*    by the affine transformation specified by @FT_Set_Transform.       */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Get_Advance( FT_Face    face,\r\n                  FT_UInt    gindex,\r\n                  FT_Int32   load_flags,\r\n                  FT_Fixed  *padvance );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Get_Advances                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Retrieve the advance values of several glyph outlines in an        */\r\n  /*    @FT_Face.  By default, the unhinted advances are returned in font  */\r\n  /*    units.                                                             */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face        :: The source @FT_Face handle.                         */\r\n  /*                                                                       */\r\n  /*    start       :: The first glyph index.                              */\r\n  /*                                                                       */\r\n  /*    count       :: The number of advance values you want to retrieve.  */\r\n  /*                                                                       */\r\n  /*    load_flags  :: A set of bit flags similar to those used when       */\r\n  /*                   calling @FT_Load_Glyph.                             */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    padvance :: The advances, in either font units or 16.16 format.    */\r\n  /*                This array must contain at least `count' elements.     */\r\n  /*                                                                       */\r\n  /*                If @FT_LOAD_VERTICAL_LAYOUT is set, these are the      */\r\n  /*                vertical advances corresponding to a vertical layout.  */\r\n  /*                Otherwise, they are the horizontal advances in a       */\r\n  /*                horizontal layout.                                     */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0 means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    This function may fail if you use @FT_ADVANCE_FLAG_FAST_ONLY and   */\r\n  /*    if the corresponding font backend doesn't have a quick way to      */\r\n  /*    retrieve the advances.                                             */\r\n  /*                                                                       */\r\n  /*    Scaled advances are returned in 16.16 format but aren't            */\r\n  /*    transformed by the affine transformation specified by              */\r\n  /*    @FT_Set_Transform.                                                 */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Get_Advances( FT_Face    face,\r\n                   FT_UInt    start,\r\n                   FT_UInt    count,\r\n                   FT_Int32   load_flags,\r\n                   FT_Fixed  *padvances );\r\n\r\n/* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTADVANC_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftbbox.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftbbox.h                                                               */\r\n/*                                                                         */\r\n/*    FreeType exact bbox computation (specification).                     */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2003, 2007, 2011 by                               */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* This component has a _single_ role: to compute exact outline bounding */\r\n  /* boxes.                                                                */\r\n  /*                                                                       */\r\n  /* It is separated from the rest of the engine for various technical     */\r\n  /* reasons.  It may well be integrated in `ftoutln' later.               */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n#ifndef __FTBBOX_H__\r\n#define __FTBBOX_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    outline_processing                                                 */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Outline_Get_BBox                                                */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Compute the exact bounding box of an outline.  This is slower      */\r\n  /*    than computing the control box.  However, it uses an advanced      */\r\n  /*    algorithm which returns _very_ quickly when the two boxes          */\r\n  /*    coincide.  Otherwise, the outline Bézier arcs are traversed to     */\r\n  /*    extract their extrema.                                             */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    outline :: A pointer to the source outline.                        */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    abbox   :: The outline's exact bounding box.                       */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    If the font is tricky and the glyph has been loaded with           */\r\n  /*    @FT_LOAD_NO_SCALE, the resulting BBox is meaningless.  To get      */\r\n  /*    reasonable values for the BBox it is necessary to load the glyph   */\r\n  /*    at a large ppem value (so that the hinting instructions can        */\r\n  /*    properly shift and scale the subglyphs), then extracting the BBox  */\r\n  /*    which can be eventually converted back to font units.              */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Outline_Get_BBox( FT_Outline*  outline,\r\n                       FT_BBox     *abbox );\r\n\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTBBOX_H__ */\r\n\r\n\r\n/* END */\r\n\r\n\r\n/* Local Variables: */\r\n/* coding: utf-8    */\r\n/* End:             */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftbdf.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftbdf.h                                                                */\r\n/*                                                                         */\r\n/*    FreeType API for accessing BDF-specific strings (specification).     */\r\n/*                                                                         */\r\n/*  Copyright 2002, 2003, 2004, 2006, 2009 by                              */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTBDF_H__\r\n#define __FTBDF_H__\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    bdf_fonts                                                          */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    BDF and PCF Files                                                  */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    BDF and PCF specific API.                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This section contains the declaration of functions specific to BDF */\r\n  /*    and PCF fonts.                                                     */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /**********************************************************************\r\n   *\r\n   * @enum:\r\n   *    FT_PropertyType\r\n   *\r\n   * @description:\r\n   *    A list of BDF property types.\r\n   *\r\n   * @values:\r\n   *    BDF_PROPERTY_TYPE_NONE ::\r\n   *      Value~0 is used to indicate a missing property.\r\n   *\r\n   *    BDF_PROPERTY_TYPE_ATOM ::\r\n   *      Property is a string atom.\r\n   *\r\n   *    BDF_PROPERTY_TYPE_INTEGER ::\r\n   *      Property is a 32-bit signed integer.\r\n   *\r\n   *    BDF_PROPERTY_TYPE_CARDINAL ::\r\n   *      Property is a 32-bit unsigned integer.\r\n   */\r\n  typedef enum  BDF_PropertyType_\r\n  {\r\n    BDF_PROPERTY_TYPE_NONE     = 0,\r\n    BDF_PROPERTY_TYPE_ATOM     = 1,\r\n    BDF_PROPERTY_TYPE_INTEGER  = 2,\r\n    BDF_PROPERTY_TYPE_CARDINAL = 3\r\n\r\n  } BDF_PropertyType;\r\n\r\n\r\n  /**********************************************************************\r\n   *\r\n   * @type:\r\n   *    BDF_Property\r\n   *\r\n   * @description:\r\n   *    A handle to a @BDF_PropertyRec structure to model a given\r\n   *    BDF/PCF property.\r\n   */\r\n  typedef struct BDF_PropertyRec_*  BDF_Property;\r\n\r\n\r\n /**********************************************************************\r\n  *\r\n  * @struct:\r\n  *    BDF_PropertyRec\r\n  *\r\n  * @description:\r\n  *    This structure models a given BDF/PCF property.\r\n  *\r\n  * @fields:\r\n  *    type ::\r\n  *      The property type.\r\n  *\r\n  *    u.atom ::\r\n  *      The atom string, if type is @BDF_PROPERTY_TYPE_ATOM.\r\n  *\r\n  *    u.integer ::\r\n  *      A signed integer, if type is @BDF_PROPERTY_TYPE_INTEGER.\r\n  *\r\n  *    u.cardinal ::\r\n  *      An unsigned integer, if type is @BDF_PROPERTY_TYPE_CARDINAL.\r\n  */\r\n  typedef struct  BDF_PropertyRec_\r\n  {\r\n    BDF_PropertyType  type;\r\n    union {\r\n      const char*     atom;\r\n      FT_Int32        integer;\r\n      FT_UInt32       cardinal;\r\n\r\n    } u;\r\n\r\n  } BDF_PropertyRec;\r\n\r\n\r\n /**********************************************************************\r\n  *\r\n  * @function:\r\n  *    FT_Get_BDF_Charset_ID\r\n  *\r\n  * @description:\r\n  *    Retrieve a BDF font character set identity, according to\r\n  *    the BDF specification.\r\n  *\r\n  * @input:\r\n  *    face ::\r\n  *       A handle to the input face.\r\n  *\r\n  * @output:\r\n  *    acharset_encoding ::\r\n  *       Charset encoding, as a C~string, owned by the face.\r\n  *\r\n  *    acharset_registry ::\r\n  *       Charset registry, as a C~string, owned by the face.\r\n  *\r\n  * @return:\r\n  *   FreeType error code.  0~means success.\r\n  *\r\n  * @note:\r\n  *   This function only works with BDF faces, returning an error otherwise.\r\n  */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Get_BDF_Charset_ID( FT_Face       face,\r\n                         const char*  *acharset_encoding,\r\n                         const char*  *acharset_registry );\r\n\r\n\r\n /**********************************************************************\r\n  *\r\n  * @function:\r\n  *    FT_Get_BDF_Property\r\n  *\r\n  * @description:\r\n  *    Retrieve a BDF property from a BDF or PCF font file.\r\n  *\r\n  * @input:\r\n  *    face :: A handle to the input face.\r\n  *\r\n  *    name :: The property name.\r\n  *\r\n  * @output:\r\n  *    aproperty :: The property.\r\n  *\r\n  * @return:\r\n  *   FreeType error code.  0~means success.\r\n  *\r\n  * @note:\r\n  *   This function works with BDF _and_ PCF fonts.  It returns an error\r\n  *   otherwise.  It also returns an error if the property is not in the\r\n  *   font.\r\n  *\r\n  *   A `property' is a either key-value pair within the STARTPROPERTIES\r\n  *   ... ENDPROPERTIES block of a BDF font or a key-value pair from the\r\n  *   `info->props' array within a `FontRec' structure of a PCF font.\r\n  *\r\n  *   Integer properties are always stored as `signed' within PCF fonts;\r\n  *   consequently, @BDF_PROPERTY_TYPE_CARDINAL is a possible return value\r\n  *   for BDF fonts only.\r\n  *\r\n  *   In case of error, `aproperty->type' is always set to\r\n  *   @BDF_PROPERTY_TYPE_NONE.\r\n  */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Get_BDF_Property( FT_Face           face,\r\n                       const char*       prop_name,\r\n                       BDF_PropertyRec  *aproperty );\r\n\r\n /* */\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTBDF_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftbitmap.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftbitmap.h                                                             */\r\n/*                                                                         */\r\n/*    FreeType utility functions for bitmaps (specification).              */\r\n/*                                                                         */\r\n/*  Copyright 2004, 2005, 2006, 2008 by                                    */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTBITMAP_H__\r\n#define __FTBITMAP_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    bitmap_handling                                                    */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    Bitmap Handling                                                    */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    Handling FT_Bitmap objects.                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This section contains functions for converting FT_Bitmap objects.  */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Bitmap_New                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Initialize a pointer to an @FT_Bitmap structure.                   */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    abitmap :: A pointer to the bitmap structure.                      */\r\n  /*                                                                       */\r\n  FT_EXPORT( void )\r\n  FT_Bitmap_New( FT_Bitmap  *abitmap );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Bitmap_Copy                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Copy a bitmap into another one.                                    */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    library :: A handle to a library object.                           */\r\n  /*                                                                       */\r\n  /*    source  :: A handle to the source bitmap.                          */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    target  :: A handle to the target bitmap.                          */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Bitmap_Copy( FT_Library        library,\r\n                  const FT_Bitmap  *source,\r\n                  FT_Bitmap        *target);\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Bitmap_Embolden                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Embolden a bitmap.  The new bitmap will be about `xStrength'       */\r\n  /*    pixels wider and `yStrength' pixels higher.  The left and bottom   */\r\n  /*    borders are kept unchanged.                                        */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    library   :: A handle to a library object.                         */\r\n  /*                                                                       */\r\n  /*    xStrength :: How strong the glyph is emboldened horizontally.      */\r\n  /*                 Expressed in 26.6 pixel format.                       */\r\n  /*                                                                       */\r\n  /*    yStrength :: How strong the glyph is emboldened vertically.        */\r\n  /*                 Expressed in 26.6 pixel format.                       */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    bitmap    :: A handle to the target bitmap.                        */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The current implementation restricts `xStrength' to be less than   */\r\n  /*    or equal to~8 if bitmap is of pixel_mode @FT_PIXEL_MODE_MONO.      */\r\n  /*                                                                       */\r\n  /*    If you want to embolden the bitmap owned by a @FT_GlyphSlotRec,    */\r\n  /*    you should call @FT_GlyphSlot_Own_Bitmap on the slot first.        */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Bitmap_Embolden( FT_Library  library,\r\n                      FT_Bitmap*  bitmap,\r\n                      FT_Pos      xStrength,\r\n                      FT_Pos      yStrength );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Bitmap_Convert                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Convert a bitmap object with depth 1bpp, 2bpp, 4bpp, or 8bpp to a  */\r\n  /*    bitmap object with depth 8bpp, making the number of used bytes per */\r\n  /*    line (a.k.a. the `pitch') a multiple of `alignment'.               */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    library   :: A handle to a library object.                         */\r\n  /*                                                                       */\r\n  /*    source    :: The source bitmap.                                    */\r\n  /*                                                                       */\r\n  /*    alignment :: The pitch of the bitmap is a multiple of this         */\r\n  /*                 parameter.  Common values are 1, 2, or 4.             */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    target    :: The target bitmap.                                    */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    It is possible to call @FT_Bitmap_Convert multiple times without   */\r\n  /*    calling @FT_Bitmap_Done (the memory is simply reallocated).        */\r\n  /*                                                                       */\r\n  /*    Use @FT_Bitmap_Done to finally remove the bitmap object.           */\r\n  /*                                                                       */\r\n  /*    The `library' argument is taken to have access to FreeType's       */\r\n  /*    memory handling functions.                                         */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Bitmap_Convert( FT_Library        library,\r\n                     const FT_Bitmap  *source,\r\n                     FT_Bitmap        *target,\r\n                     FT_Int            alignment );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_GlyphSlot_Own_Bitmap                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Make sure that a glyph slot owns `slot->bitmap'.                   */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    slot :: The glyph slot.                                            */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    This function is to be used in combination with                    */\r\n  /*    @FT_Bitmap_Embolden.                                               */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_GlyphSlot_Own_Bitmap( FT_GlyphSlot  slot );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Bitmap_Done                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Destroy a bitmap object created with @FT_Bitmap_New.               */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    library :: A handle to a library object.                           */\r\n  /*                                                                       */\r\n  /*    bitmap  :: The bitmap object to be freed.                          */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The `library' argument is taken to have access to FreeType's       */\r\n  /*    memory handling functions.                                         */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Bitmap_Done( FT_Library  library,\r\n                  FT_Bitmap  *bitmap );\r\n\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTBITMAP_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftbzip2.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftbzip2.h                                                              */\r\n/*                                                                         */\r\n/*    Bzip2-compressed stream support.                                     */\r\n/*                                                                         */\r\n/*  Copyright 2010 by                                                      */\r\n/*  Joel Klinghed.                                                         */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTBZIP2_H__\r\n#define __FTBZIP2_H__\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    bzip2                                                              */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    BZIP2 Streams                                                      */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    Using bzip2-compressed font files.                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This section contains the declaration of Bzip2-specific functions. */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n /************************************************************************\r\n  *\r\n  * @function:\r\n  *   FT_Stream_OpenBzip2\r\n  *\r\n  * @description:\r\n  *   Open a new stream to parse bzip2-compressed font files.  This is\r\n  *   mainly used to support the compressed `*.pcf.bz2' fonts that come\r\n  *   with XFree86.\r\n  *\r\n  * @input:\r\n  *   stream ::\r\n  *     The target embedding stream.\r\n  *\r\n  *   source ::\r\n  *     The source stream.\r\n  *\r\n  * @return:\r\n  *   FreeType error code.  0~means success.\r\n  *\r\n  * @note:\r\n  *   The source stream must be opened _before_ calling this function.\r\n  *\r\n  *   Calling the internal function `FT_Stream_Close' on the new stream will\r\n  *   *not* call `FT_Stream_Close' on the source stream.  None of the stream\r\n  *   objects will be released to the heap.\r\n  *\r\n  *   The stream implementation is very basic and resets the decompression\r\n  *   process each time seeking backwards is needed within the stream.\r\n  *\r\n  *   In certain builds of the library, bzip2 compression recognition is\r\n  *   automatically handled when calling @FT_New_Face or @FT_Open_Face.\r\n  *   This means that if no font driver is capable of handling the raw\r\n  *   compressed file, the library will try to open a bzip2 compressed stream\r\n  *   from it and re-open the face with it.\r\n  *\r\n  *   This function may return `FT_Err_Unimplemented_Feature' if your build\r\n  *   of FreeType was not compiled with bzip2 support.\r\n  */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Stream_OpenBzip2( FT_Stream  stream,\r\n                       FT_Stream  source );\r\n\r\n /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTBZIP2_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftcache.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftcache.h                                                              */\r\n/*                                                                         */\r\n/*    FreeType Cache subsystem (specification).                            */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2010 by */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTCACHE_H__\r\n#define __FTCACHE_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_GLYPH_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * <Section>\r\n   *    cache_subsystem\r\n   *\r\n   * <Title>\r\n   *    Cache Sub-System\r\n   *\r\n   * <Abstract>\r\n   *    How to cache face, size, and glyph data with FreeType~2.\r\n   *\r\n   * <Description>\r\n   *   This section describes the FreeType~2 cache sub-system, which is used\r\n   *   to limit the number of concurrently opened @FT_Face and @FT_Size\r\n   *   objects, as well as caching information like character maps and glyph\r\n   *   images while limiting their maximum memory usage.\r\n   *\r\n   *   Note that all types and functions begin with the `FTC_' prefix.\r\n   *\r\n   *   The cache is highly portable and thus doesn't know anything about the\r\n   *   fonts installed on your system, or how to access them.  This implies\r\n   *   the following scheme:\r\n   *\r\n   *   First, available or installed font faces are uniquely identified by\r\n   *   @FTC_FaceID values, provided to the cache by the client.  Note that\r\n   *   the cache only stores and compares these values, and doesn't try to\r\n   *   interpret them in any way.\r\n   *\r\n   *   Second, the cache calls, only when needed, a client-provided function\r\n   *   to convert an @FTC_FaceID into a new @FT_Face object.  The latter is\r\n   *   then completely managed by the cache, including its termination\r\n   *   through @FT_Done_Face.  To monitor termination of face objects, the\r\n   *   finalizer callback in the `generic' field of the @FT_Face object can\r\n   *   be used, which might also be used to store the @FTC_FaceID of the\r\n   *   face.\r\n   *\r\n   *   Clients are free to map face IDs to anything else.  The most simple\r\n   *   usage is to associate them to a (pathname,face_index) pair that is\r\n   *   used to call @FT_New_Face.  However, more complex schemes are also\r\n   *   possible.\r\n   *\r\n   *   Note that for the cache to work correctly, the face ID values must be\r\n   *   *persistent*, which means that the contents they point to should not\r\n   *   change at runtime, or that their value should not become invalid.\r\n   *\r\n   *   If this is unavoidable (e.g., when a font is uninstalled at runtime),\r\n   *   you should call @FTC_Manager_RemoveFaceID as soon as possible, to let\r\n   *   the cache get rid of any references to the old @FTC_FaceID it may\r\n   *   keep internally.  Failure to do so will lead to incorrect behaviour\r\n   *   or even crashes.\r\n   *\r\n   *   To use the cache, start with calling @FTC_Manager_New to create a new\r\n   *   @FTC_Manager object, which models a single cache instance.  You can\r\n   *   then look up @FT_Face and @FT_Size objects with\r\n   *   @FTC_Manager_LookupFace and @FTC_Manager_LookupSize, respectively.\r\n   *\r\n   *   If you want to use the charmap caching, call @FTC_CMapCache_New, then\r\n   *   later use @FTC_CMapCache_Lookup to perform the equivalent of\r\n   *   @FT_Get_Char_Index, only much faster.\r\n   *\r\n   *   If you want to use the @FT_Glyph caching, call @FTC_ImageCache, then\r\n   *   later use @FTC_ImageCache_Lookup to retrieve the corresponding\r\n   *   @FT_Glyph objects from the cache.\r\n   *\r\n   *   If you need lots of small bitmaps, it is much more memory efficient\r\n   *   to call @FTC_SBitCache_New followed by @FTC_SBitCache_Lookup.  This\r\n   *   returns @FTC_SBitRec structures, which are used to store small\r\n   *   bitmaps directly.  (A small bitmap is one whose metrics and\r\n   *   dimensions all fit into 8-bit integers).\r\n   *\r\n   *   We hope to also provide a kerning cache in the near future.\r\n   *\r\n   *\r\n   * <Order>\r\n   *   FTC_Manager\r\n   *   FTC_FaceID\r\n   *   FTC_Face_Requester\r\n   *\r\n   *   FTC_Manager_New\r\n   *   FTC_Manager_Reset\r\n   *   FTC_Manager_Done\r\n   *   FTC_Manager_LookupFace\r\n   *   FTC_Manager_LookupSize\r\n   *   FTC_Manager_RemoveFaceID\r\n   *\r\n   *   FTC_Node\r\n   *   FTC_Node_Unref\r\n   *\r\n   *   FTC_ImageCache\r\n   *   FTC_ImageCache_New\r\n   *   FTC_ImageCache_Lookup\r\n   *\r\n   *   FTC_SBit\r\n   *   FTC_SBitCache\r\n   *   FTC_SBitCache_New\r\n   *   FTC_SBitCache_Lookup\r\n   *\r\n   *   FTC_CMapCache\r\n   *   FTC_CMapCache_New\r\n   *   FTC_CMapCache_Lookup\r\n   *\r\n   *************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*****                                                               *****/\r\n  /*****                    BASIC TYPE DEFINITIONS                     *****/\r\n  /*****                                                               *****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @type: FTC_FaceID\r\n   *\r\n   * @description:\r\n   *   An opaque pointer type that is used to identity face objects.  The\r\n   *   contents of such objects is application-dependent.\r\n   *\r\n   *   These pointers are typically used to point to a user-defined\r\n   *   structure containing a font file path, and face index.\r\n   *\r\n   * @note:\r\n   *   Never use NULL as a valid @FTC_FaceID.\r\n   *\r\n   *   Face IDs are passed by the client to the cache manager, which calls,\r\n   *   when needed, the @FTC_Face_Requester to translate them into new\r\n   *   @FT_Face objects.\r\n   *\r\n   *   If the content of a given face ID changes at runtime, or if the value\r\n   *   becomes invalid (e.g., when uninstalling a font), you should\r\n   *   immediately call @FTC_Manager_RemoveFaceID before any other cache\r\n   *   function.\r\n   *\r\n   *   Failure to do so will result in incorrect behaviour or even\r\n   *   memory leaks and crashes.\r\n   */\r\n  typedef FT_Pointer  FTC_FaceID;\r\n\r\n\r\n  /************************************************************************\r\n   *\r\n   * @functype:\r\n   *   FTC_Face_Requester\r\n   *\r\n   * @description:\r\n   *   A callback function provided by client applications.  It is used by\r\n   *   the cache manager to translate a given @FTC_FaceID into a new valid\r\n   *   @FT_Face object, on demand.\r\n   *\r\n   * <Input>\r\n   *   face_id ::\r\n   *     The face ID to resolve.\r\n   *\r\n   *   library ::\r\n   *     A handle to a FreeType library object.\r\n   *\r\n   *   req_data ::\r\n   *     Application-provided request data (see note below).\r\n   *\r\n   * <Output>\r\n   *   aface ::\r\n   *     A new @FT_Face handle.\r\n   *\r\n   * <Return>\r\n   *   FreeType error code.  0~means success.\r\n   *\r\n   * <Note>\r\n   *   The third parameter `req_data' is the same as the one passed by the\r\n   *   client when @FTC_Manager_New is called.\r\n   *\r\n   *   The face requester should not perform funny things on the returned\r\n   *   face object, like creating a new @FT_Size for it, or setting a\r\n   *   transformation through @FT_Set_Transform!\r\n   */\r\n  typedef FT_Error\r\n  (*FTC_Face_Requester)( FTC_FaceID  face_id,\r\n                         FT_Library  library,\r\n                         FT_Pointer  request_data,\r\n                         FT_Face*    aface );\r\n\r\n /* */\r\n\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n\r\n  /* these macros are incompatible with LLP64, should not be used */\r\n\r\n#define FT_POINTER_TO_ULONG( p )  ( (FT_ULong)(FT_Pointer)(p) )\r\n\r\n#define FTC_FACE_ID_HASH( i )                                \\\r\n          ((FT_UInt32)(( FT_POINTER_TO_ULONG( i ) >> 3 ) ^   \\\r\n                       ( FT_POINTER_TO_ULONG( i ) << 7 ) ) )\r\n\r\n#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*****                                                               *****/\r\n  /*****                      CACHE MANAGER OBJECT                     *****/\r\n  /*****                                                               *****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FTC_Manager                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This object corresponds to one instance of the cache-subsystem.    */\r\n  /*    It is used to cache one or more @FT_Face objects, along with       */\r\n  /*    corresponding @FT_Size objects.                                    */\r\n  /*                                                                       */\r\n  /*    The manager intentionally limits the total number of opened        */\r\n  /*    @FT_Face and @FT_Size objects to control memory usage.  See the    */\r\n  /*    `max_faces' and `max_sizes' parameters of @FTC_Manager_New.        */\r\n  /*                                                                       */\r\n  /*    The manager is also used to cache `nodes' of various types while   */\r\n  /*    limiting their total memory usage.                                 */\r\n  /*                                                                       */\r\n  /*    All limitations are enforced by keeping lists of managed objects   */\r\n  /*    in most-recently-used order, and flushing old nodes to make room   */\r\n  /*    for new ones.                                                      */\r\n  /*                                                                       */\r\n  typedef struct FTC_ManagerRec_*  FTC_Manager;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FTC_Node                                                           */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    An opaque handle to a cache node object.  Each cache node is       */\r\n  /*    reference-counted.  A node with a count of~0 might be flushed      */\r\n  /*    out of a full cache whenever a lookup request is performed.        */\r\n  /*                                                                       */\r\n  /*    If you look up nodes, you have the ability to `acquire' them,      */\r\n  /*    i.e., to increment their reference count.  This will prevent the   */\r\n  /*    node from being flushed out of the cache until you explicitly      */\r\n  /*    `release' it (see @FTC_Node_Unref).                                */\r\n  /*                                                                       */\r\n  /*    See also @FTC_SBitCache_Lookup and @FTC_ImageCache_Lookup.         */\r\n  /*                                                                       */\r\n  typedef struct FTC_NodeRec_*  FTC_Node;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FTC_Manager_New                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Create a new cache manager.                                        */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    library   :: The parent FreeType library handle to use.            */\r\n  /*                                                                       */\r\n  /*    max_faces :: Maximum number of opened @FT_Face objects managed by  */\r\n  /*                 this cache instance.  Use~0 for defaults.             */\r\n  /*                                                                       */\r\n  /*    max_sizes :: Maximum number of opened @FT_Size objects managed by  */\r\n  /*                 this cache instance.  Use~0 for defaults.             */\r\n  /*                                                                       */\r\n  /*    max_bytes :: Maximum number of bytes to use for cached data nodes. */\r\n  /*                 Use~0 for defaults.  Note that this value does not    */\r\n  /*                 account for managed @FT_Face and @FT_Size objects.    */\r\n  /*                                                                       */\r\n  /*    requester :: An application-provided callback used to translate    */\r\n  /*                 face IDs into real @FT_Face objects.                  */\r\n  /*                                                                       */\r\n  /*    req_data  :: A generic pointer that is passed to the requester     */\r\n  /*                 each time it is called (see @FTC_Face_Requester).     */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    amanager  :: A handle to a new manager object.  0~in case of       */\r\n  /*                 failure.                                              */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FTC_Manager_New( FT_Library          library,\r\n                   FT_UInt             max_faces,\r\n                   FT_UInt             max_sizes,\r\n                   FT_ULong            max_bytes,\r\n                   FTC_Face_Requester  requester,\r\n                   FT_Pointer          req_data,\r\n                   FTC_Manager        *amanager );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FTC_Manager_Reset                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Empty a given cache manager.  This simply gets rid of all the      */\r\n  /*    currently cached @FT_Face and @FT_Size objects within the manager. */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    manager :: A handle to the manager.                                */\r\n  /*                                                                       */\r\n  FT_EXPORT( void )\r\n  FTC_Manager_Reset( FTC_Manager  manager );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FTC_Manager_Done                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Destroy a given manager after emptying it.                         */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    manager :: A handle to the target cache manager object.            */\r\n  /*                                                                       */\r\n  FT_EXPORT( void )\r\n  FTC_Manager_Done( FTC_Manager  manager );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FTC_Manager_LookupFace                                             */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Retrieve the @FT_Face object that corresponds to a given face ID   */\r\n  /*    through a cache manager.                                           */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    manager :: A handle to the cache manager.                          */\r\n  /*                                                                       */\r\n  /*    face_id :: The ID of the face object.                              */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    aface   :: A handle to the face object.                            */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The returned @FT_Face object is always owned by the manager.  You  */\r\n  /*    should never try to discard it yourself.                           */\r\n  /*                                                                       */\r\n  /*    The @FT_Face object doesn't necessarily have a current size object */\r\n  /*    (i.e., face->size can be 0).  If you need a specific `font size',  */\r\n  /*    use @FTC_Manager_LookupSize instead.                               */\r\n  /*                                                                       */\r\n  /*    Never change the face's transformation matrix (i.e., never call    */\r\n  /*    the @FT_Set_Transform function) on a returned face!  If you need   */\r\n  /*    to transform glyphs, do it yourself after glyph loading.           */\r\n  /*                                                                       */\r\n  /*    When you perform a lookup, out-of-memory errors are detected       */\r\n  /*    _within_ the lookup and force incremental flushes of the cache     */\r\n  /*    until enough memory is released for the lookup to succeed.         */\r\n  /*                                                                       */\r\n  /*    If a lookup fails with `FT_Err_Out_Of_Memory' the cache has        */\r\n  /*    already been completely flushed, and still no memory was available */\r\n  /*    for the operation.                                                 */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FTC_Manager_LookupFace( FTC_Manager  manager,\r\n                          FTC_FaceID   face_id,\r\n                          FT_Face     *aface );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FTC_ScalerRec                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to describe a given character size in either      */\r\n  /*    pixels or points to the cache manager.  See                        */\r\n  /*    @FTC_Manager_LookupSize.                                           */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    face_id :: The source face ID.                                     */\r\n  /*                                                                       */\r\n  /*    width   :: The character width.                                    */\r\n  /*                                                                       */\r\n  /*    height  :: The character height.                                   */\r\n  /*                                                                       */\r\n  /*    pixel   :: A Boolean.  If 1, the `width' and `height' fields are   */\r\n  /*               interpreted as integer pixel character sizes.           */\r\n  /*               Otherwise, they are expressed as 1/64th of points.      */\r\n  /*                                                                       */\r\n  /*    x_res   :: Only used when `pixel' is value~0 to indicate the       */\r\n  /*               horizontal resolution in dpi.                           */\r\n  /*                                                                       */\r\n  /*    y_res   :: Only used when `pixel' is value~0 to indicate the       */\r\n  /*               vertical resolution in dpi.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    This type is mainly used to retrieve @FT_Size objects through the  */\r\n  /*    cache manager.                                                     */\r\n  /*                                                                       */\r\n  typedef struct  FTC_ScalerRec_\r\n  {\r\n    FTC_FaceID  face_id;\r\n    FT_UInt     width;\r\n    FT_UInt     height;\r\n    FT_Int      pixel;\r\n    FT_UInt     x_res;\r\n    FT_UInt     y_res;\r\n\r\n  } FTC_ScalerRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FTC_Scaler                                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle to an @FTC_ScalerRec structure.                           */\r\n  /*                                                                       */\r\n  typedef struct FTC_ScalerRec_*  FTC_Scaler;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FTC_Manager_LookupSize                                             */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Retrieve the @FT_Size object that corresponds to a given           */\r\n  /*    @FTC_ScalerRec pointer through a cache manager.                    */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    manager :: A handle to the cache manager.                          */\r\n  /*                                                                       */\r\n  /*    scaler  :: A scaler handle.                                        */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    asize   :: A handle to the size object.                            */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The returned @FT_Size object is always owned by the manager.  You  */\r\n  /*    should never try to discard it by yourself.                        */\r\n  /*                                                                       */\r\n  /*    You can access the parent @FT_Face object simply as `size->face'   */\r\n  /*    if you need it.  Note that this object is also owned by the        */\r\n  /*    manager.                                                           */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    When you perform a lookup, out-of-memory errors are detected       */\r\n  /*    _within_ the lookup and force incremental flushes of the cache     */\r\n  /*    until enough memory is released for the lookup to succeed.         */\r\n  /*                                                                       */\r\n  /*    If a lookup fails with `FT_Err_Out_Of_Memory' the cache has        */\r\n  /*    already been completely flushed, and still no memory is available  */\r\n  /*    for the operation.                                                 */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FTC_Manager_LookupSize( FTC_Manager  manager,\r\n                          FTC_Scaler   scaler,\r\n                          FT_Size     *asize );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FTC_Node_Unref                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Decrement a cache node's internal reference count.  When the count */\r\n  /*    reaches 0, it is not destroyed but becomes eligible for subsequent */\r\n  /*    cache flushes.                                                     */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    node    :: The cache node handle.                                  */\r\n  /*                                                                       */\r\n  /*    manager :: The cache manager handle.                               */\r\n  /*                                                                       */\r\n  FT_EXPORT( void )\r\n  FTC_Node_Unref( FTC_Node     node,\r\n                  FTC_Manager  manager );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @function:\r\n   *   FTC_Manager_RemoveFaceID\r\n   *\r\n   * @description:\r\n   *   A special function used to indicate to the cache manager that\r\n   *   a given @FTC_FaceID is no longer valid, either because its\r\n   *   content changed, or because it was deallocated or uninstalled.\r\n   *\r\n   * @input:\r\n   *   manager ::\r\n   *     The cache manager handle.\r\n   *\r\n   *   face_id ::\r\n   *     The @FTC_FaceID to be removed.\r\n   *\r\n   * @note:\r\n   *   This function flushes all nodes from the cache corresponding to this\r\n   *   `face_id', with the exception of nodes with a non-null reference\r\n   *   count.\r\n   *\r\n   *   Such nodes are however modified internally so as to never appear\r\n   *   in later lookups with the same `face_id' value, and to be immediately\r\n   *   destroyed when released by all their users.\r\n   *\r\n   */\r\n  FT_EXPORT( void )\r\n  FTC_Manager_RemoveFaceID( FTC_Manager  manager,\r\n                            FTC_FaceID   face_id );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    cache_subsystem                                                    */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @type:\r\n   *   FTC_CMapCache\r\n   *\r\n   * @description:\r\n   *   An opaque handle used to model a charmap cache.  This cache is to\r\n   *   hold character codes -> glyph indices mappings.\r\n   *\r\n   */\r\n  typedef struct FTC_CMapCacheRec_*  FTC_CMapCache;\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @function:\r\n   *   FTC_CMapCache_New\r\n   *\r\n   * @description:\r\n   *   Create a new charmap cache.\r\n   *\r\n   * @input:\r\n   *   manager ::\r\n   *     A handle to the cache manager.\r\n   *\r\n   * @output:\r\n   *   acache ::\r\n   *     A new cache handle.  NULL in case of error.\r\n   *\r\n   * @return:\r\n   *   FreeType error code.  0~means success.\r\n   *\r\n   * @note:\r\n   *   Like all other caches, this one will be destroyed with the cache\r\n   *   manager.\r\n   *\r\n   */\r\n  FT_EXPORT( FT_Error )\r\n  FTC_CMapCache_New( FTC_Manager     manager,\r\n                     FTC_CMapCache  *acache );\r\n\r\n\r\n  /************************************************************************\r\n   *\r\n   * @function:\r\n   *   FTC_CMapCache_Lookup\r\n   *\r\n   * @description:\r\n   *   Translate a character code into a glyph index, using the charmap\r\n   *   cache.\r\n   *\r\n   * @input:\r\n   *   cache ::\r\n   *     A charmap cache handle.\r\n   *\r\n   *   face_id ::\r\n   *     The source face ID.\r\n   *\r\n   *   cmap_index ::\r\n   *     The index of the charmap in the source face.  Any negative value\r\n   *     means to use the cache @FT_Face's default charmap.\r\n   *\r\n   *   char_code ::\r\n   *     The character code (in the corresponding charmap).\r\n   *\r\n   * @return:\r\n   *    Glyph index.  0~means `no glyph'.\r\n   *\r\n   */\r\n  FT_EXPORT( FT_UInt )\r\n  FTC_CMapCache_Lookup( FTC_CMapCache  cache,\r\n                        FTC_FaceID     face_id,\r\n                        FT_Int         cmap_index,\r\n                        FT_UInt32      char_code );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    cache_subsystem                                                    */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*****                                                               *****/\r\n  /*****                       IMAGE CACHE OBJECT                      *****/\r\n  /*****                                                               *****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @struct:\r\n   *   FTC_ImageTypeRec\r\n   *\r\n   * @description:\r\n   *   A structure used to model the type of images in a glyph cache.\r\n   *\r\n   * @fields:\r\n   *   face_id ::\r\n   *     The face ID.\r\n   *\r\n   *   width ::\r\n   *     The width in pixels.\r\n   *\r\n   *   height ::\r\n   *     The height in pixels.\r\n   *\r\n   *   flags ::\r\n   *     The load flags, as in @FT_Load_Glyph.\r\n   *\r\n   */\r\n  typedef struct  FTC_ImageTypeRec_\r\n  {\r\n    FTC_FaceID  face_id;\r\n    FT_Int      width;\r\n    FT_Int      height;\r\n    FT_Int32    flags;\r\n\r\n  } FTC_ImageTypeRec;\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @type:\r\n   *   FTC_ImageType\r\n   *\r\n   * @description:\r\n   *   A handle to an @FTC_ImageTypeRec structure.\r\n   *\r\n   */\r\n  typedef struct FTC_ImageTypeRec_*  FTC_ImageType;\r\n\r\n\r\n  /* */\r\n\r\n\r\n#define FTC_IMAGE_TYPE_COMPARE( d1, d2 )      \\\r\n          ( (d1)->face_id == (d2)->face_id && \\\r\n            (d1)->width   == (d2)->width   && \\\r\n            (d1)->flags   == (d2)->flags   )\r\n\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n\r\n  /* this macro is incompatible with LLP64, should not be used */\r\n\r\n#define FTC_IMAGE_TYPE_HASH( d )                          \\\r\n          (FT_UFast)( FTC_FACE_ID_HASH( (d)->face_id )  ^ \\\r\n                      ( (d)->width << 8 ) ^ (d)->height ^ \\\r\n                      ( (d)->flags << 4 )               )\r\n\r\n#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FTC_ImageCache                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle to an glyph image cache object.  They are designed to     */\r\n  /*    hold many distinct glyph images while not exceeding a certain      */\r\n  /*    memory threshold.                                                  */\r\n  /*                                                                       */\r\n  typedef struct FTC_ImageCacheRec_*  FTC_ImageCache;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FTC_ImageCache_New                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Create a new glyph image cache.                                    */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    manager :: The parent manager for the image cache.                 */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    acache  :: A handle to the new glyph image cache object.           */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FTC_ImageCache_New( FTC_Manager      manager,\r\n                      FTC_ImageCache  *acache );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FTC_ImageCache_Lookup                                              */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Retrieve a given glyph image from a glyph image cache.             */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    cache  :: A handle to the source glyph image cache.                */\r\n  /*                                                                       */\r\n  /*    type   :: A pointer to a glyph image type descriptor.              */\r\n  /*                                                                       */\r\n  /*    gindex :: The glyph index to retrieve.                             */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    aglyph :: The corresponding @FT_Glyph object.  0~in case of        */\r\n  /*              failure.                                                 */\r\n  /*                                                                       */\r\n  /*    anode  :: Used to return the address of of the corresponding cache */\r\n  /*              node after incrementing its reference count (see note    */\r\n  /*              below).                                                  */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The returned glyph is owned and managed by the glyph image cache.  */\r\n  /*    Never try to transform or discard it manually!  You can however    */\r\n  /*    create a copy with @FT_Glyph_Copy and modify the new one.          */\r\n  /*                                                                       */\r\n  /*    If `anode' is _not_ NULL, it receives the address of the cache     */\r\n  /*    node containing the glyph image, after increasing its reference    */\r\n  /*    count.  This ensures that the node (as well as the @FT_Glyph) will */\r\n  /*    always be kept in the cache until you call @FTC_Node_Unref to      */\r\n  /*    `release' it.                                                      */\r\n  /*                                                                       */\r\n  /*    If `anode' is NULL, the cache node is left unchanged, which means  */\r\n  /*    that the @FT_Glyph could be flushed out of the cache on the next   */\r\n  /*    call to one of the caching sub-system APIs.  Don't assume that it  */\r\n  /*    is persistent!                                                     */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FTC_ImageCache_Lookup( FTC_ImageCache  cache,\r\n                         FTC_ImageType   type,\r\n                         FT_UInt         gindex,\r\n                         FT_Glyph       *aglyph,\r\n                         FTC_Node       *anode );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FTC_ImageCache_LookupScaler                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A variant of @FTC_ImageCache_Lookup that uses an @FTC_ScalerRec    */\r\n  /*    to specify the face ID and its size.                               */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    cache      :: A handle to the source glyph image cache.            */\r\n  /*                                                                       */\r\n  /*    scaler     :: A pointer to a scaler descriptor.                    */\r\n  /*                                                                       */\r\n  /*    load_flags :: The corresponding load flags.                        */\r\n  /*                                                                       */\r\n  /*    gindex     :: The glyph index to retrieve.                         */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    aglyph     :: The corresponding @FT_Glyph object.  0~in case of    */\r\n  /*                  failure.                                             */\r\n  /*                                                                       */\r\n  /*    anode      :: Used to return the address of of the corresponding   */\r\n  /*                  cache node after incrementing its reference count    */\r\n  /*                  (see note below).                                    */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The returned glyph is owned and managed by the glyph image cache.  */\r\n  /*    Never try to transform or discard it manually!  You can however    */\r\n  /*    create a copy with @FT_Glyph_Copy and modify the new one.          */\r\n  /*                                                                       */\r\n  /*    If `anode' is _not_ NULL, it receives the address of the cache     */\r\n  /*    node containing the glyph image, after increasing its reference    */\r\n  /*    count.  This ensures that the node (as well as the @FT_Glyph) will */\r\n  /*    always be kept in the cache until you call @FTC_Node_Unref to      */\r\n  /*    `release' it.                                                      */\r\n  /*                                                                       */\r\n  /*    If `anode' is NULL, the cache node is left unchanged, which means  */\r\n  /*    that the @FT_Glyph could be flushed out of the cache on the next   */\r\n  /*    call to one of the caching sub-system APIs.  Don't assume that it  */\r\n  /*    is persistent!                                                     */\r\n  /*                                                                       */\r\n  /*    Calls to @FT_Set_Char_Size and friends have no effect on cached    */\r\n  /*    glyphs; you should always use the FreeType cache API instead.      */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FTC_ImageCache_LookupScaler( FTC_ImageCache  cache,\r\n                               FTC_Scaler      scaler,\r\n                               FT_ULong        load_flags,\r\n                               FT_UInt         gindex,\r\n                               FT_Glyph       *aglyph,\r\n                               FTC_Node       *anode );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FTC_SBit                                                           */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle to a small bitmap descriptor.  See the @FTC_SBitRec       */\r\n  /*    structure for details.                                             */\r\n  /*                                                                       */\r\n  typedef struct FTC_SBitRec_*  FTC_SBit;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FTC_SBitRec                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A very compact structure used to describe a small glyph bitmap.    */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    width     :: The bitmap width in pixels.                           */\r\n  /*                                                                       */\r\n  /*    height    :: The bitmap height in pixels.                          */\r\n  /*                                                                       */\r\n  /*    left      :: The horizontal distance from the pen position to the  */\r\n  /*                 left bitmap border (a.k.a. `left side bearing', or    */\r\n  /*                 `lsb').                                               */\r\n  /*                                                                       */\r\n  /*    top       :: The vertical distance from the pen position (on the   */\r\n  /*                 baseline) to the upper bitmap border (a.k.a. `top     */\r\n  /*                 side bearing').  The distance is positive for upwards */\r\n  /*                 y~coordinates.                                        */\r\n  /*                                                                       */\r\n  /*    format    :: The format of the glyph bitmap (monochrome or gray).  */\r\n  /*                                                                       */\r\n  /*    max_grays :: Maximum gray level value (in the range 1 to~255).     */\r\n  /*                                                                       */\r\n  /*    pitch     :: The number of bytes per bitmap line.  May be positive */\r\n  /*                 or negative.                                          */\r\n  /*                                                                       */\r\n  /*    xadvance  :: The horizontal advance width in pixels.               */\r\n  /*                                                                       */\r\n  /*    yadvance  :: The vertical advance height in pixels.                */\r\n  /*                                                                       */\r\n  /*    buffer    :: A pointer to the bitmap pixels.                       */\r\n  /*                                                                       */\r\n  typedef struct  FTC_SBitRec_\r\n  {\r\n    FT_Byte   width;\r\n    FT_Byte   height;\r\n    FT_Char   left;\r\n    FT_Char   top;\r\n\r\n    FT_Byte   format;\r\n    FT_Byte   max_grays;\r\n    FT_Short  pitch;\r\n    FT_Char   xadvance;\r\n    FT_Char   yadvance;\r\n\r\n    FT_Byte*  buffer;\r\n\r\n  } FTC_SBitRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FTC_SBitCache                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle to a small bitmap cache.  These are special cache objects */\r\n  /*    used to store small glyph bitmaps (and anti-aliased pixmaps) in a  */\r\n  /*    much more efficient way than the traditional glyph image cache     */\r\n  /*    implemented by @FTC_ImageCache.                                    */\r\n  /*                                                                       */\r\n  typedef struct FTC_SBitCacheRec_*  FTC_SBitCache;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FTC_SBitCache_New                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Create a new cache to store small glyph bitmaps.                   */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    manager :: A handle to the source cache manager.                   */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    acache  :: A handle to the new sbit cache.  NULL in case of error. */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FTC_SBitCache_New( FTC_Manager     manager,\r\n                     FTC_SBitCache  *acache );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FTC_SBitCache_Lookup                                               */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Look up a given small glyph bitmap in a given sbit cache and       */\r\n  /*    `lock' it to prevent its flushing from the cache until needed.     */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    cache  :: A handle to the source sbit cache.                       */\r\n  /*                                                                       */\r\n  /*    type   :: A pointer to the glyph image type descriptor.            */\r\n  /*                                                                       */\r\n  /*    gindex :: The glyph index.                                         */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    sbit   :: A handle to a small bitmap descriptor.                   */\r\n  /*                                                                       */\r\n  /*    anode  :: Used to return the address of of the corresponding cache */\r\n  /*              node after incrementing its reference count (see note    */\r\n  /*              below).                                                  */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The small bitmap descriptor and its bit buffer are owned by the    */\r\n  /*    cache and should never be freed by the application.  They might    */\r\n  /*    as well disappear from memory on the next cache lookup, so don't   */\r\n  /*    treat them as persistent data.                                     */\r\n  /*                                                                       */\r\n  /*    The descriptor's `buffer' field is set to~0 to indicate a missing  */\r\n  /*    glyph bitmap.                                                      */\r\n  /*                                                                       */\r\n  /*    If `anode' is _not_ NULL, it receives the address of the cache     */\r\n  /*    node containing the bitmap, after increasing its reference count.  */\r\n  /*    This ensures that the node (as well as the image) will always be   */\r\n  /*    kept in the cache until you call @FTC_Node_Unref to `release' it.  */\r\n  /*                                                                       */\r\n  /*    If `anode' is NULL, the cache node is left unchanged, which means  */\r\n  /*    that the bitmap could be flushed out of the cache on the next      */\r\n  /*    call to one of the caching sub-system APIs.  Don't assume that it  */\r\n  /*    is persistent!                                                     */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FTC_SBitCache_Lookup( FTC_SBitCache    cache,\r\n                        FTC_ImageType    type,\r\n                        FT_UInt          gindex,\r\n                        FTC_SBit        *sbit,\r\n                        FTC_Node        *anode );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FTC_SBitCache_LookupScaler                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A variant of @FTC_SBitCache_Lookup that uses an @FTC_ScalerRec     */\r\n  /*    to specify the face ID and its size.                               */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    cache      :: A handle to the source sbit cache.                   */\r\n  /*                                                                       */\r\n  /*    scaler     :: A pointer to the scaler descriptor.                  */\r\n  /*                                                                       */\r\n  /*    load_flags :: The corresponding load flags.                        */\r\n  /*                                                                       */\r\n  /*    gindex     :: The glyph index.                                     */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    sbit       :: A handle to a small bitmap descriptor.               */\r\n  /*                                                                       */\r\n  /*    anode      :: Used to return the address of of the corresponding   */\r\n  /*                  cache node after incrementing its reference count    */\r\n  /*                  (see note below).                                    */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The small bitmap descriptor and its bit buffer are owned by the    */\r\n  /*    cache and should never be freed by the application.  They might    */\r\n  /*    as well disappear from memory on the next cache lookup, so don't   */\r\n  /*    treat them as persistent data.                                     */\r\n  /*                                                                       */\r\n  /*    The descriptor's `buffer' field is set to~0 to indicate a missing  */\r\n  /*    glyph bitmap.                                                      */\r\n  /*                                                                       */\r\n  /*    If `anode' is _not_ NULL, it receives the address of the cache     */\r\n  /*    node containing the bitmap, after increasing its reference count.  */\r\n  /*    This ensures that the node (as well as the image) will always be   */\r\n  /*    kept in the cache until you call @FTC_Node_Unref to `release' it.  */\r\n  /*                                                                       */\r\n  /*    If `anode' is NULL, the cache node is left unchanged, which means  */\r\n  /*    that the bitmap could be flushed out of the cache on the next      */\r\n  /*    call to one of the caching sub-system APIs.  Don't assume that it  */\r\n  /*    is persistent!                                                     */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FTC_SBitCache_LookupScaler( FTC_SBitCache  cache,\r\n                              FTC_Scaler     scaler,\r\n                              FT_ULong       load_flags,\r\n                              FT_UInt        gindex,\r\n                              FTC_SBit      *sbit,\r\n                              FTC_Node      *anode );\r\n\r\n\r\n /* */\r\n\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n\r\n  /*@***********************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FTC_FontRec                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A simple structure used to describe a given `font' to the cache    */\r\n  /*    manager.  Note that a `font' is the combination of a given face    */\r\n  /*    with a given character size.                                       */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    face_id    :: The ID of the face to use.                           */\r\n  /*                                                                       */\r\n  /*    pix_width  :: The character width in integer pixels.               */\r\n  /*                                                                       */\r\n  /*    pix_height :: The character height in integer pixels.              */\r\n  /*                                                                       */\r\n  typedef struct  FTC_FontRec_\r\n  {\r\n    FTC_FaceID  face_id;\r\n    FT_UShort   pix_width;\r\n    FT_UShort   pix_height;\r\n\r\n  } FTC_FontRec;\r\n\r\n\r\n  /* */\r\n\r\n\r\n#define FTC_FONT_COMPARE( f1, f2 )                  \\\r\n          ( (f1)->face_id    == (f2)->face_id    && \\\r\n            (f1)->pix_width  == (f2)->pix_width  && \\\r\n            (f1)->pix_height == (f2)->pix_height )\r\n\r\n  /* this macro is incompatible with LLP64, should not be used */\r\n#define FTC_FONT_HASH( f )                              \\\r\n          (FT_UInt32)( FTC_FACE_ID_HASH((f)->face_id) ^ \\\r\n                       ((f)->pix_width << 8)          ^ \\\r\n                       ((f)->pix_height)              )\r\n\r\n  typedef FTC_FontRec*  FTC_Font;\r\n\r\n\r\n  FT_EXPORT( FT_Error )\r\n  FTC_Manager_Lookup_Face( FTC_Manager  manager,\r\n                           FTC_FaceID   face_id,\r\n                           FT_Face     *aface );\r\n\r\n  FT_EXPORT( FT_Error )\r\n  FTC_Manager_Lookup_Size( FTC_Manager  manager,\r\n                           FTC_Font     font,\r\n                           FT_Face     *aface,\r\n                           FT_Size     *asize );\r\n\r\n#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */\r\n\r\n\r\n /* */\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTCACHE_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftchapters.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/* This file defines the structure of the FreeType reference.              */\r\n/* It is used by the python script which generates the HTML files.         */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n/***************************************************************************/\r\n/*                                                                         */\r\n/* <Chapter>                                                               */\r\n/*    general_remarks                                                      */\r\n/*                                                                         */\r\n/* <Title>                                                                 */\r\n/*    General Remarks                                                      */\r\n/*                                                                         */\r\n/* <Sections>                                                              */\r\n/*    user_allocation                                                      */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n/***************************************************************************/\r\n/*                                                                         */\r\n/* <Chapter>                                                               */\r\n/*    core_api                                                             */\r\n/*                                                                         */\r\n/* <Title>                                                                 */\r\n/*    Core API                                                             */\r\n/*                                                                         */\r\n/* <Sections>                                                              */\r\n/*    version                                                              */\r\n/*    basic_types                                                          */\r\n/*    base_interface                                                       */\r\n/*    glyph_variants                                                       */\r\n/*    glyph_management                                                     */\r\n/*    mac_specific                                                         */\r\n/*    sizes_management                                                     */\r\n/*    header_file_macros                                                   */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n/***************************************************************************/\r\n/*                                                                         */\r\n/* <Chapter>                                                               */\r\n/*    format_specific                                                      */\r\n/*                                                                         */\r\n/* <Title>                                                                 */\r\n/*    Format-Specific API                                                  */\r\n/*                                                                         */\r\n/* <Sections>                                                              */\r\n/*    multiple_masters                                                     */\r\n/*    truetype_tables                                                      */\r\n/*    type1_tables                                                         */\r\n/*    sfnt_names                                                           */\r\n/*    bdf_fonts                                                            */\r\n/*    cid_fonts                                                            */\r\n/*    pfr_fonts                                                            */\r\n/*    winfnt_fonts                                                         */\r\n/*    font_formats                                                         */\r\n/*    gasp_table                                                           */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n/***************************************************************************/\r\n/*                                                                         */\r\n/* <Chapter>                                                               */\r\n/*    cache_subsystem                                                      */\r\n/*                                                                         */\r\n/* <Title>                                                                 */\r\n/*    Cache Sub-System                                                     */\r\n/*                                                                         */\r\n/* <Sections>                                                              */\r\n/*    cache_subsystem                                                      */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n/***************************************************************************/\r\n/*                                                                         */\r\n/* <Chapter>                                                               */\r\n/*    support_api                                                          */\r\n/*                                                                         */\r\n/* <Title>                                                                 */\r\n/*    Support API                                                          */\r\n/*                                                                         */\r\n/* <Sections>                                                              */\r\n/*    computations                                                         */\r\n/*    list_processing                                                      */\r\n/*    outline_processing                                                   */\r\n/*    quick_advance                                                        */\r\n/*    bitmap_handling                                                      */\r\n/*    raster                                                               */\r\n/*    glyph_stroker                                                        */\r\n/*    system_interface                                                     */\r\n/*    module_management                                                    */\r\n/*    gzip                                                                 */\r\n/*    lzw                                                                  */\r\n/*    bzip2                                                                */\r\n/*    lcd_filtering                                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftcid.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftcid.h                                                                */\r\n/*                                                                         */\r\n/*    FreeType API for accessing CID font information (specification).     */\r\n/*                                                                         */\r\n/*  Copyright 2007, 2009 by Dereg Clegg, Michael Toftdal.                  */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTCID_H__\r\n#define __FTCID_H__\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    cid_fonts                                                          */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    CID Fonts                                                          */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    CID-keyed font specific API.                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This section contains the declaration of CID-keyed font specific   */\r\n  /*    functions.                                                         */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /**********************************************************************\r\n   *\r\n   * @function:\r\n   *    FT_Get_CID_Registry_Ordering_Supplement\r\n   *\r\n   * @description:\r\n   *    Retrieve the Registry/Ordering/Supplement triple (also known as the\r\n   *    \"R/O/S\") from a CID-keyed font.\r\n   *\r\n   * @input:\r\n   *    face ::\r\n   *       A handle to the input face.\r\n   *\r\n   * @output:\r\n   *    registry ::\r\n   *       The registry, as a C~string, owned by the face.\r\n   *\r\n   *    ordering ::\r\n   *       The ordering, as a C~string, owned by the face.\r\n   *\r\n   *    supplement ::\r\n   *       The supplement.\r\n   *\r\n   * @return:\r\n   *    FreeType error code.  0~means success.\r\n   *\r\n   * @note:\r\n   *    This function only works with CID faces, returning an error\r\n   *    otherwise.\r\n   *\r\n   * @since:\r\n   *    2.3.6\r\n   */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Get_CID_Registry_Ordering_Supplement( FT_Face       face,\r\n                                           const char*  *registry,\r\n                                           const char*  *ordering,\r\n                                           FT_Int       *supplement);\r\n\r\n\r\n  /**********************************************************************\r\n   *\r\n   * @function:\r\n   *    FT_Get_CID_Is_Internally_CID_Keyed\r\n   *\r\n   * @description:\r\n   *    Retrieve the type of the input face, CID keyed or not.  In\r\n   *    constrast to the @FT_IS_CID_KEYED macro this function returns\r\n   *    successfully also for CID-keyed fonts in an SNFT wrapper.\r\n   *\r\n   * @input:\r\n   *    face ::\r\n   *       A handle to the input face.\r\n   *\r\n   * @output:\r\n   *    is_cid ::\r\n   *       The type of the face as an @FT_Bool.\r\n   *\r\n   * @return:\r\n   *    FreeType error code.  0~means success.\r\n   *\r\n   * @note:\r\n   *    This function only works with CID faces and OpenType fonts,\r\n   *    returning an error otherwise.\r\n   *\r\n   * @since:\r\n   *    2.3.9\r\n   */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Get_CID_Is_Internally_CID_Keyed( FT_Face   face,\r\n                                      FT_Bool  *is_cid );\r\n\r\n\r\n  /**********************************************************************\r\n   *\r\n   * @function:\r\n   *    FT_Get_CID_From_Glyph_Index\r\n   *\r\n   * @description:\r\n   *    Retrieve the CID of the input glyph index.\r\n   *\r\n   * @input:\r\n   *    face ::\r\n   *       A handle to the input face.\r\n   *\r\n   *    glyph_index ::\r\n   *       The input glyph index.\r\n   *\r\n   * @output:\r\n   *    cid ::\r\n   *       The CID as an @FT_UInt.\r\n   *\r\n   * @return:\r\n   *    FreeType error code.  0~means success.\r\n   *\r\n   * @note:\r\n   *    This function only works with CID faces and OpenType fonts,\r\n   *    returning an error otherwise.\r\n   *\r\n   * @since:\r\n   *    2.3.9\r\n   */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Get_CID_From_Glyph_Index( FT_Face   face,\r\n                               FT_UInt   glyph_index,\r\n                               FT_UInt  *cid );\r\n\r\n /* */\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTCID_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/fterrdef.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  fterrdef.h                                                             */\r\n/*                                                                         */\r\n/*    FreeType error codes (specification).                                */\r\n/*                                                                         */\r\n/*  Copyright 2002, 2004, 2006, 2007, 2010 by                              */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n  /*******************************************************************/\r\n  /*******************************************************************/\r\n  /*****                                                         *****/\r\n  /*****                LIST OF ERROR CODES/MESSAGES             *****/\r\n  /*****                                                         *****/\r\n  /*******************************************************************/\r\n  /*******************************************************************/\r\n\r\n\r\n  /* You need to define both FT_ERRORDEF_ and FT_NOERRORDEF_ before */\r\n  /* including this file.                                           */\r\n\r\n\r\n  /* generic errors */\r\n\r\n  FT_NOERRORDEF_( Ok,                                        0x00, \\\r\n                  \"no error\" )\r\n\r\n  FT_ERRORDEF_( Cannot_Open_Resource,                        0x01, \\\r\n                \"cannot open resource\" )\r\n  FT_ERRORDEF_( Unknown_File_Format,                         0x02, \\\r\n                \"unknown file format\" )\r\n  FT_ERRORDEF_( Invalid_File_Format,                         0x03, \\\r\n                \"broken file\" )\r\n  FT_ERRORDEF_( Invalid_Version,                             0x04, \\\r\n                \"invalid FreeType version\" )\r\n  FT_ERRORDEF_( Lower_Module_Version,                        0x05, \\\r\n                \"module version is too low\" )\r\n  FT_ERRORDEF_( Invalid_Argument,                            0x06, \\\r\n                \"invalid argument\" )\r\n  FT_ERRORDEF_( Unimplemented_Feature,                       0x07, \\\r\n                \"unimplemented feature\" )\r\n  FT_ERRORDEF_( Invalid_Table,                               0x08, \\\r\n                \"broken table\" )\r\n  FT_ERRORDEF_( Invalid_Offset,                              0x09, \\\r\n                \"broken offset within table\" )\r\n  FT_ERRORDEF_( Array_Too_Large,                             0x0A, \\\r\n                \"array allocation size too large\" )\r\n\r\n  /* glyph/character errors */\r\n\r\n  FT_ERRORDEF_( Invalid_Glyph_Index,                         0x10, \\\r\n                \"invalid glyph index\" )\r\n  FT_ERRORDEF_( Invalid_Character_Code,                      0x11, \\\r\n                \"invalid character code\" )\r\n  FT_ERRORDEF_( Invalid_Glyph_Format,                        0x12, \\\r\n                \"unsupported glyph image format\" )\r\n  FT_ERRORDEF_( Cannot_Render_Glyph,                         0x13, \\\r\n                \"cannot render this glyph format\" )\r\n  FT_ERRORDEF_( Invalid_Outline,                             0x14, \\\r\n                \"invalid outline\" )\r\n  FT_ERRORDEF_( Invalid_Composite,                           0x15, \\\r\n                \"invalid composite glyph\" )\r\n  FT_ERRORDEF_( Too_Many_Hints,                              0x16, \\\r\n                \"too many hints\" )\r\n  FT_ERRORDEF_( Invalid_Pixel_Size,                          0x17, \\\r\n                \"invalid pixel size\" )\r\n\r\n  /* handle errors */\r\n\r\n  FT_ERRORDEF_( Invalid_Handle,                              0x20, \\\r\n                \"invalid object handle\" )\r\n  FT_ERRORDEF_( Invalid_Library_Handle,                      0x21, \\\r\n                \"invalid library handle\" )\r\n  FT_ERRORDEF_( Invalid_Driver_Handle,                       0x22, \\\r\n                \"invalid module handle\" )\r\n  FT_ERRORDEF_( Invalid_Face_Handle,                         0x23, \\\r\n                \"invalid face handle\" )\r\n  FT_ERRORDEF_( Invalid_Size_Handle,                         0x24, \\\r\n                \"invalid size handle\" )\r\n  FT_ERRORDEF_( Invalid_Slot_Handle,                         0x25, \\\r\n                \"invalid glyph slot handle\" )\r\n  FT_ERRORDEF_( Invalid_CharMap_Handle,                      0x26, \\\r\n                \"invalid charmap handle\" )\r\n  FT_ERRORDEF_( Invalid_Cache_Handle,                        0x27, \\\r\n                \"invalid cache manager handle\" )\r\n  FT_ERRORDEF_( Invalid_Stream_Handle,                       0x28, \\\r\n                \"invalid stream handle\" )\r\n\r\n  /* driver errors */\r\n\r\n  FT_ERRORDEF_( Too_Many_Drivers,                            0x30, \\\r\n                \"too many modules\" )\r\n  FT_ERRORDEF_( Too_Many_Extensions,                         0x31, \\\r\n                \"too many extensions\" )\r\n\r\n  /* memory errors */\r\n\r\n  FT_ERRORDEF_( Out_Of_Memory,                               0x40, \\\r\n                \"out of memory\" )\r\n  FT_ERRORDEF_( Unlisted_Object,                             0x41, \\\r\n                \"unlisted object\" )\r\n\r\n  /* stream errors */\r\n\r\n  FT_ERRORDEF_( Cannot_Open_Stream,                          0x51, \\\r\n                \"cannot open stream\" )\r\n  FT_ERRORDEF_( Invalid_Stream_Seek,                         0x52, \\\r\n                \"invalid stream seek\" )\r\n  FT_ERRORDEF_( Invalid_Stream_Skip,                         0x53, \\\r\n                \"invalid stream skip\" )\r\n  FT_ERRORDEF_( Invalid_Stream_Read,                         0x54, \\\r\n                \"invalid stream read\" )\r\n  FT_ERRORDEF_( Invalid_Stream_Operation,                    0x55, \\\r\n                \"invalid stream operation\" )\r\n  FT_ERRORDEF_( Invalid_Frame_Operation,                     0x56, \\\r\n                \"invalid frame operation\" )\r\n  FT_ERRORDEF_( Nested_Frame_Access,                         0x57, \\\r\n                \"nested frame access\" )\r\n  FT_ERRORDEF_( Invalid_Frame_Read,                          0x58, \\\r\n                \"invalid frame read\" )\r\n\r\n  /* raster errors */\r\n\r\n  FT_ERRORDEF_( Raster_Uninitialized,                        0x60, \\\r\n                \"raster uninitialized\" )\r\n  FT_ERRORDEF_( Raster_Corrupted,                            0x61, \\\r\n                \"raster corrupted\" )\r\n  FT_ERRORDEF_( Raster_Overflow,                             0x62, \\\r\n                \"raster overflow\" )\r\n  FT_ERRORDEF_( Raster_Negative_Height,                      0x63, \\\r\n                \"negative height while rastering\" )\r\n\r\n  /* cache errors */\r\n\r\n  FT_ERRORDEF_( Too_Many_Caches,                             0x70, \\\r\n                \"too many registered caches\" )\r\n\r\n  /* TrueType and SFNT errors */\r\n\r\n  FT_ERRORDEF_( Invalid_Opcode,                              0x80, \\\r\n                \"invalid opcode\" )\r\n  FT_ERRORDEF_( Too_Few_Arguments,                           0x81, \\\r\n                \"too few arguments\" )\r\n  FT_ERRORDEF_( Stack_Overflow,                              0x82, \\\r\n                \"stack overflow\" )\r\n  FT_ERRORDEF_( Code_Overflow,                               0x83, \\\r\n                \"code overflow\" )\r\n  FT_ERRORDEF_( Bad_Argument,                                0x84, \\\r\n                \"bad argument\" )\r\n  FT_ERRORDEF_( Divide_By_Zero,                              0x85, \\\r\n                \"division by zero\" )\r\n  FT_ERRORDEF_( Invalid_Reference,                           0x86, \\\r\n                \"invalid reference\" )\r\n  FT_ERRORDEF_( Debug_OpCode,                                0x87, \\\r\n                \"found debug opcode\" )\r\n  FT_ERRORDEF_( ENDF_In_Exec_Stream,                         0x88, \\\r\n                \"found ENDF opcode in execution stream\" )\r\n  FT_ERRORDEF_( Nested_DEFS,                                 0x89, \\\r\n                \"nested DEFS\" )\r\n  FT_ERRORDEF_( Invalid_CodeRange,                           0x8A, \\\r\n                \"invalid code range\" )\r\n  FT_ERRORDEF_( Execution_Too_Long,                          0x8B, \\\r\n                \"execution context too long\" )\r\n  FT_ERRORDEF_( Too_Many_Function_Defs,                      0x8C, \\\r\n                \"too many function definitions\" )\r\n  FT_ERRORDEF_( Too_Many_Instruction_Defs,                   0x8D, \\\r\n                \"too many instruction definitions\" )\r\n  FT_ERRORDEF_( Table_Missing,                               0x8E, \\\r\n                \"SFNT font table missing\" )\r\n  FT_ERRORDEF_( Horiz_Header_Missing,                        0x8F, \\\r\n                \"horizontal header (hhea) table missing\" )\r\n  FT_ERRORDEF_( Locations_Missing,                           0x90, \\\r\n                \"locations (loca) table missing\" )\r\n  FT_ERRORDEF_( Name_Table_Missing,                          0x91, \\\r\n                \"name table missing\" )\r\n  FT_ERRORDEF_( CMap_Table_Missing,                          0x92, \\\r\n                \"character map (cmap) table missing\" )\r\n  FT_ERRORDEF_( Hmtx_Table_Missing,                          0x93, \\\r\n                \"horizontal metrics (hmtx) table missing\" )\r\n  FT_ERRORDEF_( Post_Table_Missing,                          0x94, \\\r\n                \"PostScript (post) table missing\" )\r\n  FT_ERRORDEF_( Invalid_Horiz_Metrics,                       0x95, \\\r\n                \"invalid horizontal metrics\" )\r\n  FT_ERRORDEF_( Invalid_CharMap_Format,                      0x96, \\\r\n                \"invalid character map (cmap) format\" )\r\n  FT_ERRORDEF_( Invalid_PPem,                                0x97, \\\r\n                \"invalid ppem value\" )\r\n  FT_ERRORDEF_( Invalid_Vert_Metrics,                        0x98, \\\r\n                \"invalid vertical metrics\" )\r\n  FT_ERRORDEF_( Could_Not_Find_Context,                      0x99, \\\r\n                \"could not find context\" )\r\n  FT_ERRORDEF_( Invalid_Post_Table_Format,                   0x9A, \\\r\n                \"invalid PostScript (post) table format\" )\r\n  FT_ERRORDEF_( Invalid_Post_Table,                          0x9B, \\\r\n                \"invalid PostScript (post) table\" )\r\n\r\n  /* CFF, CID, and Type 1 errors */\r\n\r\n  FT_ERRORDEF_( Syntax_Error,                                0xA0, \\\r\n                \"opcode syntax error\" )\r\n  FT_ERRORDEF_( Stack_Underflow,                             0xA1, \\\r\n                \"argument stack underflow\" )\r\n  FT_ERRORDEF_( Ignore,                                      0xA2, \\\r\n                \"ignore\" )\r\n  FT_ERRORDEF_( No_Unicode_Glyph_Name,                       0xA3, \\\r\n                \"no Unicode glyph name found\" )\r\n\r\n  /* BDF errors */\r\n\r\n  FT_ERRORDEF_( Missing_Startfont_Field,                     0xB0, \\\r\n                \"`STARTFONT' field missing\" )\r\n  FT_ERRORDEF_( Missing_Font_Field,                          0xB1, \\\r\n                \"`FONT' field missing\" )\r\n  FT_ERRORDEF_( Missing_Size_Field,                          0xB2, \\\r\n                \"`SIZE' field missing\" )\r\n  FT_ERRORDEF_( Missing_Fontboundingbox_Field,               0xB3, \\\r\n                \"`FONTBOUNDINGBOX' field missing\" )\r\n  FT_ERRORDEF_( Missing_Chars_Field,                         0xB4, \\\r\n                \"`CHARS' field missing\" )\r\n  FT_ERRORDEF_( Missing_Startchar_Field,                     0xB5, \\\r\n                \"`STARTCHAR' field missing\" )\r\n  FT_ERRORDEF_( Missing_Encoding_Field,                      0xB6, \\\r\n                \"`ENCODING' field missing\" )\r\n  FT_ERRORDEF_( Missing_Bbx_Field,                           0xB7, \\\r\n                \"`BBX' field missing\" )\r\n  FT_ERRORDEF_( Bbx_Too_Big,                                 0xB8, \\\r\n                \"`BBX' too big\" )\r\n  FT_ERRORDEF_( Corrupted_Font_Header,                       0xB9, \\\r\n                \"Font header corrupted or missing fields\" )\r\n  FT_ERRORDEF_( Corrupted_Font_Glyphs,                       0xBA, \\\r\n                \"Font glyphs corrupted or missing fields\" )\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/fterrors.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  fterrors.h                                                             */\r\n/*                                                                         */\r\n/*    FreeType error code handling (specification).                        */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2002, 2004, 2007 by                               */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* This special header file is used to define the handling of FT2        */\r\n  /* enumeration constants.  It can also be used to generate error message */\r\n  /* strings with a small macro trick explained below.                     */\r\n  /*                                                                       */\r\n  /* I - Error Formats                                                     */\r\n  /* -----------------                                                     */\r\n  /*                                                                       */\r\n  /*   The configuration macro FT_CONFIG_OPTION_USE_MODULE_ERRORS can be   */\r\n  /*   defined in ftoption.h in order to make the higher byte indicate     */\r\n  /*   the module where the error has happened (this is not compatible     */\r\n  /*   with standard builds of FreeType 2).  You can then use the macro    */\r\n  /*   FT_ERROR_BASE macro to extract the generic error code from an       */\r\n  /*   FT_Error value.                                                     */\r\n  /*                                                                       */\r\n  /*                                                                       */\r\n  /* II - Error Message strings                                            */\r\n  /* --------------------------                                            */\r\n  /*                                                                       */\r\n  /*   The error definitions below are made through special macros that    */\r\n  /*   allow client applications to build a table of error message strings */\r\n  /*   if they need it.  The strings are not included in a normal build of */\r\n  /*   FreeType 2 to save space (most client applications do not use       */\r\n  /*   them).                                                              */\r\n  /*                                                                       */\r\n  /*   To do so, you have to define the following macros before including  */\r\n  /*   this file:                                                          */\r\n  /*                                                                       */\r\n  /*   FT_ERROR_START_LIST ::                                              */\r\n  /*     This macro is called before anything else to define the start of  */\r\n  /*     the error list.  It is followed by several FT_ERROR_DEF calls     */\r\n  /*     (see below).                                                      */\r\n  /*                                                                       */\r\n  /*   FT_ERROR_DEF( e, v, s ) ::                                          */\r\n  /*     This macro is called to define one single error.                  */\r\n  /*     `e' is the error code identifier (e.g. FT_Err_Invalid_Argument).  */\r\n  /*     `v' is the error numerical value.                                 */\r\n  /*     `s' is the corresponding error string.                            */\r\n  /*                                                                       */\r\n  /*   FT_ERROR_END_LIST ::                                                */\r\n  /*     This macro ends the list.                                         */\r\n  /*                                                                       */\r\n  /*   Additionally, you have to undefine __FTERRORS_H__ before #including */\r\n  /*   this file.                                                          */\r\n  /*                                                                       */\r\n  /*   Here is a simple example:                                           */\r\n  /*                                                                       */\r\n  /*     {                                                                 */\r\n  /*       #undef __FTERRORS_H__                                           */\r\n  /*       #define FT_ERRORDEF( e, v, s )  { e, s },                       */\r\n  /*       #define FT_ERROR_START_LIST     {                               */\r\n  /*       #define FT_ERROR_END_LIST       { 0, 0 } };                     */\r\n  /*                                                                       */\r\n  /*       const struct                                                    */\r\n  /*       {                                                               */\r\n  /*         int          err_code;                                        */\r\n  /*         const char*  err_msg;                                         */\r\n  /*       } ft_errors[] =                                                 */\r\n  /*                                                                       */\r\n  /*       #include FT_ERRORS_H                                            */\r\n  /*     }                                                                 */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n#ifndef __FTERRORS_H__\r\n#define __FTERRORS_H__\r\n\r\n\r\n  /* include module base error codes */\r\n#include FT_MODULE_ERRORS_H\r\n\r\n\r\n  /*******************************************************************/\r\n  /*******************************************************************/\r\n  /*****                                                         *****/\r\n  /*****                       SETUP MACROS                      *****/\r\n  /*****                                                         *****/\r\n  /*******************************************************************/\r\n  /*******************************************************************/\r\n\r\n\r\n#undef  FT_NEED_EXTERN_C\r\n\r\n#undef  FT_ERR_XCAT\r\n#undef  FT_ERR_CAT\r\n\r\n#define FT_ERR_XCAT( x, y )  x ## y\r\n#define FT_ERR_CAT( x, y )   FT_ERR_XCAT( x, y )\r\n\r\n\r\n  /* FT_ERR_PREFIX is used as a prefix for error identifiers. */\r\n  /* By default, we use `FT_Err_'.                            */\r\n  /*                                                          */\r\n#ifndef FT_ERR_PREFIX\r\n#define FT_ERR_PREFIX  FT_Err_\r\n#endif\r\n\r\n\r\n  /* FT_ERR_BASE is used as the base for module-specific errors. */\r\n  /*                                                             */\r\n#ifdef FT_CONFIG_OPTION_USE_MODULE_ERRORS\r\n\r\n#ifndef FT_ERR_BASE\r\n#define FT_ERR_BASE  FT_Mod_Err_Base\r\n#endif\r\n\r\n#else\r\n\r\n#undef FT_ERR_BASE\r\n#define FT_ERR_BASE  0\r\n\r\n#endif /* FT_CONFIG_OPTION_USE_MODULE_ERRORS */\r\n\r\n\r\n  /* If FT_ERRORDEF is not defined, we need to define a simple */\r\n  /* enumeration type.                                         */\r\n  /*                                                           */\r\n#ifndef FT_ERRORDEF\r\n\r\n#define FT_ERRORDEF( e, v, s )  e = v,\r\n#define FT_ERROR_START_LIST     enum {\r\n#define FT_ERROR_END_LIST       FT_ERR_CAT( FT_ERR_PREFIX, Max ) };\r\n\r\n#ifdef __cplusplus\r\n#define FT_NEED_EXTERN_C\r\n  extern \"C\" {\r\n#endif\r\n\r\n#endif /* !FT_ERRORDEF */\r\n\r\n\r\n  /* this macro is used to define an error */\r\n#define FT_ERRORDEF_( e, v, s )   \\\r\n          FT_ERRORDEF( FT_ERR_CAT( FT_ERR_PREFIX, e ), v + FT_ERR_BASE, s )\r\n\r\n  /* this is only used for <module>_Err_Ok, which must be 0! */\r\n#define FT_NOERRORDEF_( e, v, s ) \\\r\n          FT_ERRORDEF( FT_ERR_CAT( FT_ERR_PREFIX, e ), v, s )\r\n\r\n\r\n#ifdef FT_ERROR_START_LIST\r\n  FT_ERROR_START_LIST\r\n#endif\r\n\r\n\r\n  /* now include the error codes */\r\n#include FT_ERROR_DEFINITIONS_H\r\n\r\n\r\n#ifdef FT_ERROR_END_LIST\r\n  FT_ERROR_END_LIST\r\n#endif\r\n\r\n\r\n  /*******************************************************************/\r\n  /*******************************************************************/\r\n  /*****                                                         *****/\r\n  /*****                      SIMPLE CLEANUP                     *****/\r\n  /*****                                                         *****/\r\n  /*******************************************************************/\r\n  /*******************************************************************/\r\n\r\n#ifdef FT_NEED_EXTERN_C\r\n  }\r\n#endif\r\n\r\n#undef FT_ERROR_START_LIST\r\n#undef FT_ERROR_END_LIST\r\n\r\n#undef FT_ERRORDEF\r\n#undef FT_ERRORDEF_\r\n#undef FT_NOERRORDEF_\r\n\r\n#undef FT_NEED_EXTERN_C\r\n#undef FT_ERR_CONCAT\r\n#undef FT_ERR_BASE\r\n\r\n  /* FT_KEEP_ERR_PREFIX is needed for ftvalid.h */\r\n#ifndef FT_KEEP_ERR_PREFIX\r\n#undef FT_ERR_PREFIX\r\n#endif\r\n\r\n#endif /* __FTERRORS_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftgasp.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftgasp.h                                                               */\r\n/*                                                                         */\r\n/*    Access of TrueType's `gasp' table (specification).                   */\r\n/*                                                                         */\r\n/*  Copyright 2007, 2008, 2011 by                                          */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef _FT_GASP_H_\r\n#define _FT_GASP_H_\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\n  /***************************************************************************\r\n   *\r\n   * @section:\r\n   *   gasp_table\r\n   *\r\n   * @title:\r\n   *   Gasp Table\r\n   *\r\n   * @abstract:\r\n   *   Retrieving TrueType `gasp' table entries.\r\n   *\r\n   * @description:\r\n   *   The function @FT_Get_Gasp can be used to query a TrueType or OpenType\r\n   *   font for specific entries in its `gasp' table, if any.  This is\r\n   *   mainly useful when implementing native TrueType hinting with the\r\n   *   bytecode interpreter to duplicate the Windows text rendering results.\r\n   */\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @enum:\r\n   *   FT_GASP_XXX\r\n   *\r\n   * @description:\r\n   *   A list of values and/or bit-flags returned by the @FT_Get_Gasp\r\n   *   function.\r\n   *\r\n   * @values:\r\n   *   FT_GASP_NO_TABLE ::\r\n   *     This special value means that there is no GASP table in this face.\r\n   *     It is up to the client to decide what to do.\r\n   *\r\n   *   FT_GASP_DO_GRIDFIT ::\r\n   *     Grid-fitting and hinting should be performed at the specified ppem. \r\n   *     This *really* means TrueType bytecode interpretation.  If this bit\r\n   *     is not set, no hinting gets applied.\r\n   *\r\n   *   FT_GASP_DO_GRAY ::\r\n   *     Anti-aliased rendering should be performed at the specified ppem. \r\n   *     If not set, do monochrome rendering.\r\n   *\r\n   *   FT_GASP_SYMMETRIC_SMOOTHING ::\r\n   *     If set, smoothing along multiple axes must be used with ClearType.\r\n   *\r\n   *   FT_GASP_SYMMETRIC_GRIDFIT ::\r\n   *     Grid-fitting must be used with ClearType's symmetric smoothing.\r\n   *\r\n   * @note:\r\n   *   The bit-flags `FT_GASP_DO_GRIDFIT' and `FT_GASP_DO_GRAY' are to be\r\n   *   used for standard font rasterization only.  Independently of that,\r\n   *   `FT_GASP_SYMMETRIC_SMOOTHING' and `FT_GASP_SYMMETRIC_GRIDFIT' are to\r\n   *   be used if ClearType is enabled (and `FT_GASP_DO_GRIDFIT' and\r\n   *   `FT_GASP_DO_GRAY' are consequently ignored).\r\n   *\r\n   *   `ClearType' is Microsoft's implementation of LCD rendering, partly\r\n   *   protected by patents.\r\n   *\r\n   * @since:\r\n   *   2.3.0\r\n   */\r\n#define FT_GASP_NO_TABLE               -1\r\n#define FT_GASP_DO_GRIDFIT           0x01\r\n#define FT_GASP_DO_GRAY              0x02\r\n#define FT_GASP_SYMMETRIC_SMOOTHING  0x08\r\n#define FT_GASP_SYMMETRIC_GRIDFIT    0x10\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @func:\r\n   *   FT_Get_Gasp\r\n   *\r\n   * @description:\r\n   *   Read the `gasp' table from a TrueType or OpenType font file and\r\n   *   return the entry corresponding to a given character pixel size.\r\n   *\r\n   * @input:\r\n   *   face :: The source face handle.\r\n   *   ppem :: The vertical character pixel size.\r\n   *\r\n   * @return:\r\n   *   Bit flags (see @FT_GASP_XXX), or @FT_GASP_NO_TABLE if there is no\r\n   *   `gasp' table in the face.\r\n   *\r\n   * @since:\r\n   *   2.3.0\r\n   */\r\n  FT_EXPORT( FT_Int )\r\n  FT_Get_Gasp( FT_Face  face,\r\n               FT_UInt  ppem );\r\n\r\n/* */\r\n\r\n#endif /* _FT_GASP_H_ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftglyph.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftglyph.h                                                              */\r\n/*                                                                         */\r\n/*    FreeType convenience functions to handle glyphs (specification).     */\r\n/*                                                                         */\r\n/*  Copyright 1996-2003, 2006, 2008, 2009, 2011 by                         */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* This file contains the definition of several convenience functions    */\r\n  /* that can be used by client applications to easily retrieve glyph      */\r\n  /* bitmaps and outlines from a given face.                               */\r\n  /*                                                                       */\r\n  /* These functions should be optional if you are writing a font server   */\r\n  /* or text layout engine on top of FreeType.  However, they are pretty   */\r\n  /* handy for many other simple uses of the library.                      */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n#ifndef __FTGLYPH_H__\r\n#define __FTGLYPH_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    glyph_management                                                   */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    Glyph Management                                                   */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    Generic interface to manage individual glyph data.                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This section contains definitions used to manage glyph data        */\r\n  /*    through generic FT_Glyph objects.  Each of them can contain a      */\r\n  /*    bitmap, a vector outline, or even images in other formats.         */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /* forward declaration to a private type */\r\n  typedef struct FT_Glyph_Class_  FT_Glyph_Class;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Glyph                                                           */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Handle to an object used to model generic glyph images.  It is a   */\r\n  /*    pointer to the @FT_GlyphRec structure and can contain a glyph      */\r\n  /*    bitmap or pointer.                                                 */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    Glyph objects are not owned by the library.  You must thus release */\r\n  /*    them manually (through @FT_Done_Glyph) _before_ calling            */\r\n  /*    @FT_Done_FreeType.                                                 */\r\n  /*                                                                       */\r\n  typedef struct FT_GlyphRec_*  FT_Glyph;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_GlyphRec                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    The root glyph structure contains a given glyph image plus its     */\r\n  /*    advance width in 16.16 fixed float format.                         */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    library :: A handle to the FreeType library object.                */\r\n  /*                                                                       */\r\n  /*    clazz   :: A pointer to the glyph's class.  Private.               */\r\n  /*                                                                       */\r\n  /*    format  :: The format of the glyph's image.                        */\r\n  /*                                                                       */\r\n  /*    advance :: A 16.16 vector that gives the glyph's advance width.    */\r\n  /*                                                                       */\r\n  typedef struct  FT_GlyphRec_\r\n  {\r\n    FT_Library             library;\r\n    const FT_Glyph_Class*  clazz;\r\n    FT_Glyph_Format        format;\r\n    FT_Vector              advance;\r\n\r\n  } FT_GlyphRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_BitmapGlyph                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle to an object used to model a bitmap glyph image.  This is */\r\n  /*    a sub-class of @FT_Glyph, and a pointer to @FT_BitmapGlyphRec.     */\r\n  /*                                                                       */\r\n  typedef struct FT_BitmapGlyphRec_*  FT_BitmapGlyph;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_BitmapGlyphRec                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used for bitmap glyph images.  This really is a        */\r\n  /*    `sub-class' of @FT_GlyphRec.                                       */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    root   :: The root @FT_Glyph fields.                               */\r\n  /*                                                                       */\r\n  /*    left   :: The left-side bearing, i.e., the horizontal distance     */\r\n  /*              from the current pen position to the left border of the  */\r\n  /*              glyph bitmap.                                            */\r\n  /*                                                                       */\r\n  /*    top    :: The top-side bearing, i.e., the vertical distance from   */\r\n  /*              the current pen position to the top border of the glyph  */\r\n  /*              bitmap.  This distance is positive for upwards~y!        */\r\n  /*                                                                       */\r\n  /*    bitmap :: A descriptor for the bitmap.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    You can typecast an @FT_Glyph to @FT_BitmapGlyph if you have       */\r\n  /*    `glyph->format == FT_GLYPH_FORMAT_BITMAP'.  This lets you access   */\r\n  /*    the bitmap's contents easily.                                      */\r\n  /*                                                                       */\r\n  /*    The corresponding pixel buffer is always owned by @FT_BitmapGlyph  */\r\n  /*    and is thus created and destroyed with it.                         */\r\n  /*                                                                       */\r\n  typedef struct  FT_BitmapGlyphRec_\r\n  {\r\n    FT_GlyphRec  root;\r\n    FT_Int       left;\r\n    FT_Int       top;\r\n    FT_Bitmap    bitmap;\r\n\r\n  } FT_BitmapGlyphRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_OutlineGlyph                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle to an object used to model an outline glyph image.  This  */\r\n  /*    is a sub-class of @FT_Glyph, and a pointer to @FT_OutlineGlyphRec. */\r\n  /*                                                                       */\r\n  typedef struct FT_OutlineGlyphRec_*  FT_OutlineGlyph;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_OutlineGlyphRec                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used for outline (vectorial) glyph images.  This       */\r\n  /*    really is a `sub-class' of @FT_GlyphRec.                           */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    root    :: The root @FT_Glyph fields.                              */\r\n  /*                                                                       */\r\n  /*    outline :: A descriptor for the outline.                           */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    You can typecast an @FT_Glyph to @FT_OutlineGlyph if you have      */\r\n  /*    `glyph->format == FT_GLYPH_FORMAT_OUTLINE'.  This lets you access  */\r\n  /*    the outline's content easily.                                      */\r\n  /*                                                                       */\r\n  /*    As the outline is extracted from a glyph slot, its coordinates are */\r\n  /*    expressed normally in 26.6 pixels, unless the flag                 */\r\n  /*    @FT_LOAD_NO_SCALE was used in @FT_Load_Glyph() or @FT_Load_Char(). */\r\n  /*                                                                       */\r\n  /*    The outline's tables are always owned by the object and are        */\r\n  /*    destroyed with it.                                                 */\r\n  /*                                                                       */\r\n  typedef struct  FT_OutlineGlyphRec_\r\n  {\r\n    FT_GlyphRec  root;\r\n    FT_Outline   outline;\r\n\r\n  } FT_OutlineGlyphRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Get_Glyph                                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A function used to extract a glyph image from a slot.  Note that   */\r\n  /*    the created @FT_Glyph object must be released with @FT_Done_Glyph. */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    slot   :: A handle to the source glyph slot.                       */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    aglyph :: A handle to the glyph object.                            */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Get_Glyph( FT_GlyphSlot  slot,\r\n                FT_Glyph     *aglyph );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Glyph_Copy                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A function used to copy a glyph image.  Note that the created      */\r\n  /*    @FT_Glyph object must be released with @FT_Done_Glyph.             */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    source :: A handle to the source glyph object.                     */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    target :: A handle to the target glyph object.  0~in case of       */\r\n  /*              error.                                                   */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Glyph_Copy( FT_Glyph   source,\r\n                 FT_Glyph  *target );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Glyph_Transform                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Transform a glyph image if its format is scalable.                 */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    glyph  :: A handle to the target glyph object.                     */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    matrix :: A pointer to a 2x2 matrix to apply.                      */\r\n  /*                                                                       */\r\n  /*    delta  :: A pointer to a 2d vector to apply.  Coordinates are      */\r\n  /*              expressed in 1/64th of a pixel.                          */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code (if not 0, the glyph format is not scalable).  */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The 2x2 transformation matrix is also applied to the glyph's       */\r\n  /*    advance vector.                                                    */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Glyph_Transform( FT_Glyph    glyph,\r\n                      FT_Matrix*  matrix,\r\n                      FT_Vector*  delta );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Enum>                                                                */\r\n  /*    FT_Glyph_BBox_Mode                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    The mode how the values of @FT_Glyph_Get_CBox are returned.        */\r\n  /*                                                                       */\r\n  /* <Values>                                                              */\r\n  /*    FT_GLYPH_BBOX_UNSCALED ::                                          */\r\n  /*      Return unscaled font units.                                      */\r\n  /*                                                                       */\r\n  /*    FT_GLYPH_BBOX_SUBPIXELS ::                                         */\r\n  /*      Return unfitted 26.6 coordinates.                                */\r\n  /*                                                                       */\r\n  /*    FT_GLYPH_BBOX_GRIDFIT ::                                           */\r\n  /*      Return grid-fitted 26.6 coordinates.                             */\r\n  /*                                                                       */\r\n  /*    FT_GLYPH_BBOX_TRUNCATE ::                                          */\r\n  /*      Return coordinates in integer pixels.                            */\r\n  /*                                                                       */\r\n  /*    FT_GLYPH_BBOX_PIXELS ::                                            */\r\n  /*      Return grid-fitted pixel coordinates.                            */\r\n  /*                                                                       */\r\n  typedef enum  FT_Glyph_BBox_Mode_\r\n  {\r\n    FT_GLYPH_BBOX_UNSCALED  = 0,\r\n    FT_GLYPH_BBOX_SUBPIXELS = 0,\r\n    FT_GLYPH_BBOX_GRIDFIT   = 1,\r\n    FT_GLYPH_BBOX_TRUNCATE  = 2,\r\n    FT_GLYPH_BBOX_PIXELS    = 3\r\n\r\n  } FT_Glyph_BBox_Mode;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Enum>                                                                */\r\n  /*    ft_glyph_bbox_xxx                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    These constants are deprecated.  Use the corresponding             */\r\n  /*    @FT_Glyph_BBox_Mode values instead.                                */\r\n  /*                                                                       */\r\n  /* <Values>                                                              */\r\n  /*   ft_glyph_bbox_unscaled  :: See @FT_GLYPH_BBOX_UNSCALED.             */\r\n  /*   ft_glyph_bbox_subpixels :: See @FT_GLYPH_BBOX_SUBPIXELS.            */\r\n  /*   ft_glyph_bbox_gridfit   :: See @FT_GLYPH_BBOX_GRIDFIT.              */\r\n  /*   ft_glyph_bbox_truncate  :: See @FT_GLYPH_BBOX_TRUNCATE.             */\r\n  /*   ft_glyph_bbox_pixels    :: See @FT_GLYPH_BBOX_PIXELS.               */\r\n  /*                                                                       */\r\n#define ft_glyph_bbox_unscaled   FT_GLYPH_BBOX_UNSCALED\r\n#define ft_glyph_bbox_subpixels  FT_GLYPH_BBOX_SUBPIXELS\r\n#define ft_glyph_bbox_gridfit    FT_GLYPH_BBOX_GRIDFIT\r\n#define ft_glyph_bbox_truncate   FT_GLYPH_BBOX_TRUNCATE\r\n#define ft_glyph_bbox_pixels     FT_GLYPH_BBOX_PIXELS\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Glyph_Get_CBox                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Return a glyph's `control box'.  The control box encloses all the  */\r\n  /*    outline's points, including Bézier control points.  Though it      */\r\n  /*    coincides with the exact bounding box for most glyphs, it can be   */\r\n  /*    slightly larger in some situations (like when rotating an outline  */\r\n  /*    which contains Bézier outside arcs).                               */\r\n  /*                                                                       */\r\n  /*    Computing the control box is very fast, while getting the bounding */\r\n  /*    box can take much more time as it needs to walk over all segments  */\r\n  /*    and arcs in the outline.  To get the latter, you can use the       */\r\n  /*    `ftbbox' component which is dedicated to this single task.         */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    glyph :: A handle to the source glyph object.                      */\r\n  /*                                                                       */\r\n  /*    mode  :: The mode which indicates how to interpret the returned    */\r\n  /*             bounding box values.                                      */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    acbox :: The glyph coordinate bounding box.  Coordinates are       */\r\n  /*             expressed in 1/64th of pixels if it is grid-fitted.       */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    Coordinates are relative to the glyph origin, using the y~upwards  */\r\n  /*    convention.                                                        */\r\n  /*                                                                       */\r\n  /*    If the glyph has been loaded with @FT_LOAD_NO_SCALE, `bbox_mode'   */\r\n  /*    must be set to @FT_GLYPH_BBOX_UNSCALED to get unscaled font        */\r\n  /*    units in 26.6 pixel format.  The value @FT_GLYPH_BBOX_SUBPIXELS    */\r\n  /*    is another name for this constant.                                 */\r\n  /*                                                                       */\r\n  /*    If the font is tricky and the glyph has been loaded with           */\r\n  /*    @FT_LOAD_NO_SCALE, the resulting CBox is meaningless.  To get      */\r\n  /*    reasonable values for the CBox it is necessary to load the glyph   */\r\n  /*    at a large ppem value (so that the hinting instructions can        */\r\n  /*    properly shift and scale the subglyphs), then extracting the CBox  */\r\n  /*    which can be eventually converted back to font units.              */\r\n  /*                                                                       */\r\n  /*    Note that the maximum coordinates are exclusive, which means that  */\r\n  /*    one can compute the width and height of the glyph image (be it in  */\r\n  /*    integer or 26.6 pixels) as:                                        */\r\n  /*                                                                       */\r\n  /*    {                                                                  */\r\n  /*      width  = bbox.xMax - bbox.xMin;                                  */\r\n  /*      height = bbox.yMax - bbox.yMin;                                  */\r\n  /*    }                                                                  */\r\n  /*                                                                       */\r\n  /*    Note also that for 26.6 coordinates, if `bbox_mode' is set to      */\r\n  /*    @FT_GLYPH_BBOX_GRIDFIT, the coordinates will also be grid-fitted,  */\r\n  /*    which corresponds to:                                              */\r\n  /*                                                                       */\r\n  /*    {                                                                  */\r\n  /*      bbox.xMin = FLOOR(bbox.xMin);                                    */\r\n  /*      bbox.yMin = FLOOR(bbox.yMin);                                    */\r\n  /*      bbox.xMax = CEILING(bbox.xMax);                                  */\r\n  /*      bbox.yMax = CEILING(bbox.yMax);                                  */\r\n  /*    }                                                                  */\r\n  /*                                                                       */\r\n  /*    To get the bbox in pixel coordinates, set `bbox_mode' to           */\r\n  /*    @FT_GLYPH_BBOX_TRUNCATE.                                           */\r\n  /*                                                                       */\r\n  /*    To get the bbox in grid-fitted pixel coordinates, set `bbox_mode'  */\r\n  /*    to @FT_GLYPH_BBOX_PIXELS.                                          */\r\n  /*                                                                       */\r\n  FT_EXPORT( void )\r\n  FT_Glyph_Get_CBox( FT_Glyph  glyph,\r\n                     FT_UInt   bbox_mode,\r\n                     FT_BBox  *acbox );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Glyph_To_Bitmap                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Convert a given glyph object to a bitmap glyph object.             */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    the_glyph   :: A pointer to a handle to the target glyph.          */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    render_mode :: An enumeration that describes how the data is       */\r\n  /*                   rendered.                                           */\r\n  /*                                                                       */\r\n  /*    origin      :: A pointer to a vector used to translate the glyph   */\r\n  /*                   image before rendering.  Can be~0 (if no            */\r\n  /*                   translation).  The origin is expressed in           */\r\n  /*                   26.6 pixels.                                        */\r\n  /*                                                                       */\r\n  /*    destroy     :: A boolean that indicates that the original glyph    */\r\n  /*                   image should be destroyed by this function.  It is  */\r\n  /*                   never destroyed in case of error.                   */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    This function does nothing if the glyph format isn't scalable.     */\r\n  /*                                                                       */\r\n  /*    The glyph image is translated with the `origin' vector before      */\r\n  /*    rendering.                                                         */\r\n  /*                                                                       */\r\n  /*    The first parameter is a pointer to an @FT_Glyph handle, that will */\r\n  /*    be _replaced_ by this function (with newly allocated data).        */\r\n  /*    Typically, you would use (omitting error handling):                */\r\n  /*                                                                       */\r\n  /*                                                                       */\r\n  /*      {                                                                */\r\n  /*        FT_Glyph        glyph;                                         */\r\n  /*        FT_BitmapGlyph  glyph_bitmap;                                  */\r\n  /*                                                                       */\r\n  /*                                                                       */\r\n  /*        // load glyph                                                  */\r\n  /*        error = FT_Load_Char( face, glyph_index, FT_LOAD_DEFAUT );     */\r\n  /*                                                                       */\r\n  /*        // extract glyph image                                         */\r\n  /*        error = FT_Get_Glyph( face->glyph, &glyph );                   */\r\n  /*                                                                       */\r\n  /*        // convert to a bitmap (default render mode + destroying old)  */\r\n  /*        if ( glyph->format != FT_GLYPH_FORMAT_BITMAP )                 */\r\n  /*        {                                                              */\r\n  /*          error = FT_Glyph_To_Bitmap( &glyph, FT_RENDER_MODE_NORMAL,   */\r\n  /*                                      0, 1 );                          */\r\n  /*          if ( error ) // `glyph' unchanged                            */\r\n  /*            ...                                                        */\r\n  /*        }                                                              */\r\n  /*                                                                       */\r\n  /*        // access bitmap content by typecasting                        */\r\n  /*        glyph_bitmap = (FT_BitmapGlyph)glyph;                          */\r\n  /*                                                                       */\r\n  /*        // do funny stuff with it, like blitting/drawing               */\r\n  /*        ...                                                            */\r\n  /*                                                                       */\r\n  /*        // discard glyph image (bitmap or not)                         */\r\n  /*        FT_Done_Glyph( glyph );                                        */\r\n  /*      }                                                                */\r\n  /*                                                                       */\r\n  /*                                                                       */\r\n  /*    Here another example, again without error handling:                */\r\n  /*                                                                       */\r\n  /*                                                                       */\r\n  /*      {                                                                */\r\n  /*        FT_Glyph  glyphs[MAX_GLYPHS]                                   */\r\n  /*                                                                       */\r\n  /*                                                                       */\r\n  /*        ...                                                            */\r\n  /*                                                                       */\r\n  /*        for ( idx = 0; i < MAX_GLYPHS; i++ )                           */\r\n  /*          error = FT_Load_Glyph( face, idx, FT_LOAD_DEFAULT ) ||       */\r\n  /*                  FT_Get_Glyph ( face->glyph, &glyph[idx] );           */\r\n  /*                                                                       */\r\n  /*        ...                                                            */\r\n  /*                                                                       */\r\n  /*        for ( idx = 0; i < MAX_GLYPHS; i++ )                           */\r\n  /*        {                                                              */\r\n  /*          FT_Glyph  bitmap = glyphs[idx];                              */\r\n  /*                                                                       */\r\n  /*                                                                       */\r\n  /*          ...                                                          */\r\n  /*                                                                       */\r\n  /*          // after this call, `bitmap' no longer points into           */\r\n  /*          // the `glyphs' array (and the old value isn't destroyed)    */\r\n  /*          FT_Glyph_To_Bitmap( &bitmap, FT_RENDER_MODE_MONO, 0, 0 );    */\r\n  /*                                                                       */\r\n  /*          ...                                                          */\r\n  /*                                                                       */\r\n  /*          FT_Done_Glyph( bitmap );                                     */\r\n  /*        }                                                              */\r\n  /*                                                                       */\r\n  /*        ...                                                            */\r\n  /*                                                                       */\r\n  /*        for ( idx = 0; i < MAX_GLYPHS; i++ )                           */\r\n  /*          FT_Done_Glyph( glyphs[idx] );                                */\r\n  /*      }                                                                */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Glyph_To_Bitmap( FT_Glyph*       the_glyph,\r\n                      FT_Render_Mode  render_mode,\r\n                      FT_Vector*      origin,\r\n                      FT_Bool         destroy );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Done_Glyph                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Destroy a given glyph.                                             */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    glyph :: A handle to the target glyph object.                      */\r\n  /*                                                                       */\r\n  FT_EXPORT( void )\r\n  FT_Done_Glyph( FT_Glyph  glyph );\r\n\r\n  /* */\r\n\r\n\r\n  /* other helpful functions */\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    computations                                                       */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Matrix_Multiply                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Perform the matrix operation `b = a*b'.                            */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    a :: A pointer to matrix `a'.                                      */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    b :: A pointer to matrix `b'.                                      */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The result is undefined if either `a' or `b' is zero.              */\r\n  /*                                                                       */\r\n  FT_EXPORT( void )\r\n  FT_Matrix_Multiply( const FT_Matrix*  a,\r\n                      FT_Matrix*        b );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Matrix_Invert                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Invert a 2x2 matrix.  Return an error if it can't be inverted.     */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    matrix :: A pointer to the target matrix.  Remains untouched in    */\r\n  /*              case of error.                                           */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Matrix_Invert( FT_Matrix*  matrix );\r\n\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTGLYPH_H__ */\r\n\r\n\r\n/* END */\r\n\r\n\r\n/* Local Variables: */\r\n/* coding: utf-8    */\r\n/* End:             */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftgxval.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftgxval.h                                                              */\r\n/*                                                                         */\r\n/*    FreeType API for validating TrueTypeGX/AAT tables (specification).   */\r\n/*                                                                         */\r\n/*  Copyright 2004, 2005, 2006 by                                          */\r\n/*  Masatake YAMATO, Redhat K.K,                                           */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n/***************************************************************************/\r\n/*                                                                         */\r\n/* gxvalid is derived from both gxlayout module and otvalid module.        */\r\n/* Development of gxlayout is supported by the Information-technology      */\r\n/* Promotion Agency(IPA), Japan.                                           */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTGXVAL_H__\r\n#define __FTGXVAL_H__\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    gx_validation                                                      */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    TrueTypeGX/AAT Validation                                          */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    An API to validate TrueTypeGX/AAT tables.                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This section contains the declaration of functions to validate     */\r\n  /*    some TrueTypeGX tables (feat, mort, morx, bsln, just, kern, opbd,  */\r\n  /*    trak, prop, lcar).                                                 */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /*                                                                       */\r\n  /* Warning: Use FT_VALIDATE_XXX to validate a table.                     */\r\n  /*          Following definitions are for gxvalid developers.            */\r\n  /*                                                                       */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n#define FT_VALIDATE_feat_INDEX     0\r\n#define FT_VALIDATE_mort_INDEX     1\r\n#define FT_VALIDATE_morx_INDEX     2\r\n#define FT_VALIDATE_bsln_INDEX     3\r\n#define FT_VALIDATE_just_INDEX     4\r\n#define FT_VALIDATE_kern_INDEX     5\r\n#define FT_VALIDATE_opbd_INDEX     6\r\n#define FT_VALIDATE_trak_INDEX     7\r\n#define FT_VALIDATE_prop_INDEX     8\r\n#define FT_VALIDATE_lcar_INDEX     9\r\n#define FT_VALIDATE_GX_LAST_INDEX  FT_VALIDATE_lcar_INDEX\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_VALIDATE_GX_LENGTH\r\n   *\r\n   * @description:\r\n   *   The number of tables checked in this module.  Use it as a parameter\r\n   *   for the `table-length' argument of function @FT_TrueTypeGX_Validate.\r\n   */\r\n#define FT_VALIDATE_GX_LENGTH     (FT_VALIDATE_GX_LAST_INDEX + 1)\r\n\r\n  /* */\r\n\r\n  /* Up to 0x1000 is used by otvalid.\r\n     Ox2xxx is reserved for feature OT extension. */\r\n#define FT_VALIDATE_GX_START 0x4000\r\n#define FT_VALIDATE_GX_BITFIELD( tag )                  \\\r\n  ( FT_VALIDATE_GX_START << FT_VALIDATE_##tag##_INDEX )\r\n\r\n\r\n /**********************************************************************\r\n  *\r\n  * @enum:\r\n  *    FT_VALIDATE_GXXXX\r\n  *\r\n  * @description:\r\n  *    A list of bit-field constants used with @FT_TrueTypeGX_Validate to\r\n  *    indicate which TrueTypeGX/AAT Type tables should be validated.\r\n  *\r\n  * @values:\r\n  *    FT_VALIDATE_feat ::\r\n  *      Validate `feat' table.\r\n  *\r\n  *    FT_VALIDATE_mort ::\r\n  *      Validate `mort' table.\r\n  *\r\n  *    FT_VALIDATE_morx ::\r\n  *      Validate `morx' table.\r\n  *\r\n  *    FT_VALIDATE_bsln ::\r\n  *      Validate `bsln' table.\r\n  *\r\n  *    FT_VALIDATE_just ::\r\n  *      Validate `just' table.\r\n  *\r\n  *    FT_VALIDATE_kern ::\r\n  *      Validate `kern' table.\r\n  *\r\n  *    FT_VALIDATE_opbd ::\r\n  *      Validate `opbd' table.\r\n  *\r\n  *    FT_VALIDATE_trak ::\r\n  *      Validate `trak' table.\r\n  *\r\n  *    FT_VALIDATE_prop ::\r\n  *      Validate `prop' table.\r\n  *\r\n  *    FT_VALIDATE_lcar ::\r\n  *      Validate `lcar' table.\r\n  *\r\n  *    FT_VALIDATE_GX ::\r\n  *      Validate all TrueTypeGX tables (feat, mort, morx, bsln, just, kern,\r\n  *      opbd, trak, prop and lcar).\r\n  *\r\n  */\r\n\r\n#define FT_VALIDATE_feat  FT_VALIDATE_GX_BITFIELD( feat )\r\n#define FT_VALIDATE_mort  FT_VALIDATE_GX_BITFIELD( mort )\r\n#define FT_VALIDATE_morx  FT_VALIDATE_GX_BITFIELD( morx )\r\n#define FT_VALIDATE_bsln  FT_VALIDATE_GX_BITFIELD( bsln )\r\n#define FT_VALIDATE_just  FT_VALIDATE_GX_BITFIELD( just )\r\n#define FT_VALIDATE_kern  FT_VALIDATE_GX_BITFIELD( kern )\r\n#define FT_VALIDATE_opbd  FT_VALIDATE_GX_BITFIELD( opbd )\r\n#define FT_VALIDATE_trak  FT_VALIDATE_GX_BITFIELD( trak )\r\n#define FT_VALIDATE_prop  FT_VALIDATE_GX_BITFIELD( prop )\r\n#define FT_VALIDATE_lcar  FT_VALIDATE_GX_BITFIELD( lcar )\r\n\r\n#define FT_VALIDATE_GX  ( FT_VALIDATE_feat | \\\r\n                          FT_VALIDATE_mort | \\\r\n                          FT_VALIDATE_morx | \\\r\n                          FT_VALIDATE_bsln | \\\r\n                          FT_VALIDATE_just | \\\r\n                          FT_VALIDATE_kern | \\\r\n                          FT_VALIDATE_opbd | \\\r\n                          FT_VALIDATE_trak | \\\r\n                          FT_VALIDATE_prop | \\\r\n                          FT_VALIDATE_lcar )\r\n\r\n\r\n  /* */\r\n\r\n /**********************************************************************\r\n  *\r\n  * @function:\r\n  *    FT_TrueTypeGX_Validate\r\n  *\r\n  * @description:\r\n  *    Validate various TrueTypeGX tables to assure that all offsets and\r\n  *    indices are valid.  The idea is that a higher-level library which\r\n  *    actually does the text layout can access those tables without\r\n  *    error checking (which can be quite time consuming).\r\n  *\r\n  * @input:\r\n  *    face ::\r\n  *       A handle to the input face.\r\n  *\r\n  *    validation_flags ::\r\n  *       A bit field which specifies the tables to be validated.  See\r\n  *       @FT_VALIDATE_GXXXX for possible values.\r\n  *\r\n  *    table_length ::\r\n  *       The size of the `tables' array.  Normally, @FT_VALIDATE_GX_LENGTH\r\n  *       should be passed.\r\n  *\r\n  * @output:\r\n  *    tables ::\r\n  *       The array where all validated sfnt tables are stored.\r\n  *       The array itself must be allocated by a client.\r\n  *\r\n  * @return:\r\n  *   FreeType error code.  0~means success.\r\n  *\r\n  * @note:\r\n  *   This function only works with TrueTypeGX fonts, returning an error\r\n  *   otherwise.\r\n  *\r\n  *   After use, the application should deallocate the buffers pointed to by\r\n  *   each `tables' element, by calling @FT_TrueTypeGX_Free.  A NULL value\r\n  *   indicates that the table either doesn't exist in the font, the\r\n  *   application hasn't asked for validation, or the validator doesn't have\r\n  *   the ability to validate the sfnt table.\r\n  */\r\n  FT_EXPORT( FT_Error )\r\n  FT_TrueTypeGX_Validate( FT_Face   face,\r\n                          FT_UInt   validation_flags,\r\n                          FT_Bytes  tables[FT_VALIDATE_GX_LENGTH],\r\n                          FT_UInt   table_length );\r\n\r\n\r\n  /* */\r\n\r\n /**********************************************************************\r\n  *\r\n  * @function:\r\n  *    FT_TrueTypeGX_Free\r\n  *\r\n  * @description:\r\n  *    Free the buffer allocated by TrueTypeGX validator.\r\n  *\r\n  * @input:\r\n  *    face ::\r\n  *       A handle to the input face.\r\n  *\r\n  *    table ::\r\n  *       The pointer to the buffer allocated by\r\n  *       @FT_TrueTypeGX_Validate.\r\n  *\r\n  * @note:\r\n  *   This function must be used to free the buffer allocated by\r\n  *   @FT_TrueTypeGX_Validate only.\r\n  */\r\n  FT_EXPORT( void )\r\n  FT_TrueTypeGX_Free( FT_Face   face,\r\n                      FT_Bytes  table );\r\n\r\n\r\n  /* */\r\n\r\n /**********************************************************************\r\n  *\r\n  * @enum:\r\n  *    FT_VALIDATE_CKERNXXX\r\n  *\r\n  * @description:\r\n  *    A list of bit-field constants used with @FT_ClassicKern_Validate\r\n  *    to indicate the classic kern dialect or dialects.  If the selected\r\n  *    type doesn't fit, @FT_ClassicKern_Validate regards the table as\r\n  *    invalid.\r\n  *\r\n  * @values:\r\n  *    FT_VALIDATE_MS ::\r\n  *      Handle the `kern' table as a classic Microsoft kern table.\r\n  *\r\n  *    FT_VALIDATE_APPLE ::\r\n  *      Handle the `kern' table as a classic Apple kern table.\r\n  *\r\n  *    FT_VALIDATE_CKERN ::\r\n  *      Handle the `kern' as either classic Apple or Microsoft kern table.\r\n  */\r\n#define FT_VALIDATE_MS     ( FT_VALIDATE_GX_START << 0 )\r\n#define FT_VALIDATE_APPLE  ( FT_VALIDATE_GX_START << 1 )\r\n\r\n#define FT_VALIDATE_CKERN  ( FT_VALIDATE_MS | FT_VALIDATE_APPLE )\r\n\r\n\r\n  /* */\r\n\r\n /**********************************************************************\r\n  *\r\n  * @function:\r\n  *    FT_ClassicKern_Validate\r\n  *\r\n  * @description:\r\n  *    Validate classic (16-bit format) kern table to assure that the offsets\r\n  *    and indices are valid.  The idea is that a higher-level library which\r\n  *    actually does the text layout can access those tables without error\r\n  *    checking (which can be quite time consuming).\r\n  *\r\n  *    The `kern' table validator in @FT_TrueTypeGX_Validate deals with both\r\n  *    the new 32-bit format and the classic 16-bit format, while\r\n  *    FT_ClassicKern_Validate only supports the classic 16-bit format.\r\n  *\r\n  * @input:\r\n  *    face ::\r\n  *       A handle to the input face.\r\n  *\r\n  *    validation_flags ::\r\n  *       A bit field which specifies the dialect to be validated.  See\r\n  *       @FT_VALIDATE_CKERNXXX for possible values.\r\n  *\r\n  * @output:\r\n  *    ckern_table ::\r\n  *       A pointer to the kern table.\r\n  *\r\n  * @return:\r\n  *   FreeType error code.  0~means success.\r\n  *\r\n  * @note:\r\n  *   After use, the application should deallocate the buffers pointed to by\r\n  *   `ckern_table', by calling @FT_ClassicKern_Free.  A NULL value\r\n  *   indicates that the table doesn't exist in the font.\r\n  */\r\n  FT_EXPORT( FT_Error )\r\n  FT_ClassicKern_Validate( FT_Face    face,\r\n                           FT_UInt    validation_flags,\r\n                           FT_Bytes  *ckern_table );\r\n\r\n\r\n  /* */\r\n\r\n /**********************************************************************\r\n  *\r\n  * @function:\r\n  *    FT_ClassicKern_Free\r\n  *\r\n  * @description:\r\n  *    Free the buffer allocated by classic Kern validator.\r\n  *\r\n  * @input:\r\n  *    face ::\r\n  *       A handle to the input face.\r\n  *\r\n  *    table ::\r\n  *       The pointer to the buffer that is allocated by\r\n  *       @FT_ClassicKern_Validate.\r\n  *\r\n  * @note:\r\n  *   This function must be used to free the buffer allocated by\r\n  *   @FT_ClassicKern_Validate only.\r\n  */\r\n  FT_EXPORT( void )\r\n  FT_ClassicKern_Free( FT_Face   face,\r\n                       FT_Bytes  table );\r\n\r\n\r\n /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTGXVAL_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftgzip.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftgzip.h                                                               */\r\n/*                                                                         */\r\n/*    Gzip-compressed stream support.                                      */\r\n/*                                                                         */\r\n/*  Copyright 2002, 2003, 2004, 2006 by                                    */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTGZIP_H__\r\n#define __FTGZIP_H__\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    gzip                                                               */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    GZIP Streams                                                       */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    Using gzip-compressed font files.                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This section contains the declaration of Gzip-specific functions.  */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n /************************************************************************\r\n  *\r\n  * @function:\r\n  *   FT_Stream_OpenGzip\r\n  *\r\n  * @description:\r\n  *   Open a new stream to parse gzip-compressed font files.  This is\r\n  *   mainly used to support the compressed `*.pcf.gz' fonts that come\r\n  *   with XFree86.\r\n  *\r\n  * @input:\r\n  *   stream ::\r\n  *     The target embedding stream.\r\n  *\r\n  *   source ::\r\n  *     The source stream.\r\n  *\r\n  * @return:\r\n  *   FreeType error code.  0~means success.\r\n  *\r\n  * @note:\r\n  *   The source stream must be opened _before_ calling this function.\r\n  *\r\n  *   Calling the internal function `FT_Stream_Close' on the new stream will\r\n  *   *not* call `FT_Stream_Close' on the source stream.  None of the stream\r\n  *   objects will be released to the heap.\r\n  *\r\n  *   The stream implementation is very basic and resets the decompression\r\n  *   process each time seeking backwards is needed within the stream.\r\n  *\r\n  *   In certain builds of the library, gzip compression recognition is\r\n  *   automatically handled when calling @FT_New_Face or @FT_Open_Face.\r\n  *   This means that if no font driver is capable of handling the raw\r\n  *   compressed file, the library will try to open a gzipped stream from\r\n  *   it and re-open the face with it.\r\n  *\r\n  *   This function may return `FT_Err_Unimplemented_Feature' if your build\r\n  *   of FreeType was not compiled with zlib support.\r\n  */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Stream_OpenGzip( FT_Stream  stream,\r\n                      FT_Stream  source );\r\n\r\n /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTGZIP_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftimage.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftimage.h                                                              */\r\n/*                                                                         */\r\n/*    FreeType glyph image formats and default raster interface            */\r\n/*    (specification).                                                     */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,   */\r\n/*            2010 by                                                      */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Note: A `raster' is simply a scan-line converter, used to render      */\r\n  /*       FT_Outlines into FT_Bitmaps.                                    */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n#ifndef __FTIMAGE_H__\r\n#define __FTIMAGE_H__\r\n\r\n\r\n  /* _STANDALONE_ is from ftgrays.c */\r\n#ifndef _STANDALONE_\r\n#include <ft2build.h>\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    basic_types                                                        */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Pos                                                             */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    The type FT_Pos is used to store vectorial coordinates.  Depending */\r\n  /*    on the context, these can represent distances in integer font      */\r\n  /*    units, or 16.16, or 26.6 fixed float pixel coordinates.            */\r\n  /*                                                                       */\r\n  typedef signed long  FT_Pos;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Vector                                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A simple structure used to store a 2D vector; coordinates are of   */\r\n  /*    the FT_Pos type.                                                   */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    x :: The horizontal coordinate.                                    */\r\n  /*    y :: The vertical coordinate.                                      */\r\n  /*                                                                       */\r\n  typedef struct  FT_Vector_\r\n  {\r\n    FT_Pos  x;\r\n    FT_Pos  y;\r\n\r\n  } FT_Vector;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_BBox                                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to hold an outline's bounding box, i.e., the      */\r\n  /*    coordinates of its extrema in the horizontal and vertical          */\r\n  /*    directions.                                                        */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    xMin :: The horizontal minimum (left-most).                        */\r\n  /*                                                                       */\r\n  /*    yMin :: The vertical minimum (bottom-most).                        */\r\n  /*                                                                       */\r\n  /*    xMax :: The horizontal maximum (right-most).                       */\r\n  /*                                                                       */\r\n  /*    yMax :: The vertical maximum (top-most).                           */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The bounding box is specified with the coordinates of the lower    */\r\n  /*    left and the upper right corner.  In PostScript, those values are  */\r\n  /*    often called (llx,lly) and (urx,ury), respectively.                */\r\n  /*                                                                       */\r\n  /*    If `yMin' is negative, this value gives the glyph's descender.     */\r\n  /*    Otherwise, the glyph doesn't descend below the baseline.           */\r\n  /*    Similarly, if `ymax' is positive, this value gives the glyph's     */\r\n  /*    ascender.                                                          */\r\n  /*                                                                       */\r\n  /*    `xMin' gives the horizontal distance from the glyph's origin to    */\r\n  /*    the left edge of the glyph's bounding box.  If `xMin' is negative, */\r\n  /*    the glyph extends to the left of the origin.                       */\r\n  /*                                                                       */\r\n  typedef struct  FT_BBox_\r\n  {\r\n    FT_Pos  xMin, yMin;\r\n    FT_Pos  xMax, yMax;\r\n\r\n  } FT_BBox;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Enum>                                                                */\r\n  /*    FT_Pixel_Mode                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    An enumeration type used to describe the format of pixels in a     */\r\n  /*    given bitmap.  Note that additional formats may be added in the    */\r\n  /*    future.                                                            */\r\n  /*                                                                       */\r\n  /* <Values>                                                              */\r\n  /*    FT_PIXEL_MODE_NONE ::                                              */\r\n  /*      Value~0 is reserved.                                             */\r\n  /*                                                                       */\r\n  /*    FT_PIXEL_MODE_MONO ::                                              */\r\n  /*      A monochrome bitmap, using 1~bit per pixel.  Note that pixels    */\r\n  /*      are stored in most-significant order (MSB), which means that     */\r\n  /*      the left-most pixel in a byte has value 128.                     */\r\n  /*                                                                       */\r\n  /*    FT_PIXEL_MODE_GRAY ::                                              */\r\n  /*      An 8-bit bitmap, generally used to represent anti-aliased glyph  */\r\n  /*      images.  Each pixel is stored in one byte.  Note that the number */\r\n  /*      of `gray' levels is stored in the `num_grays' field of the       */\r\n  /*      @FT_Bitmap structure (it generally is 256).                      */\r\n  /*                                                                       */\r\n  /*    FT_PIXEL_MODE_GRAY2 ::                                             */\r\n  /*      A 2-bit per pixel bitmap, used to represent embedded             */\r\n  /*      anti-aliased bitmaps in font files according to the OpenType     */\r\n  /*      specification.  We haven't found a single font using this        */\r\n  /*      format, however.                                                 */\r\n  /*                                                                       */\r\n  /*    FT_PIXEL_MODE_GRAY4 ::                                             */\r\n  /*      A 4-bit per pixel bitmap, representing embedded anti-aliased     */\r\n  /*      bitmaps in font files according to the OpenType specification.   */\r\n  /*      We haven't found a single font using this format, however.       */\r\n  /*                                                                       */\r\n  /*    FT_PIXEL_MODE_LCD ::                                               */\r\n  /*      An 8-bit bitmap, representing RGB or BGR decimated glyph images  */\r\n  /*      used for display on LCD displays; the bitmap is three times      */\r\n  /*      wider than the original glyph image.  See also                   */\r\n  /*      @FT_RENDER_MODE_LCD.                                             */\r\n  /*                                                                       */\r\n  /*    FT_PIXEL_MODE_LCD_V ::                                             */\r\n  /*      An 8-bit bitmap, representing RGB or BGR decimated glyph images  */\r\n  /*      used for display on rotated LCD displays; the bitmap is three    */\r\n  /*      times taller than the original glyph image.  See also            */\r\n  /*      @FT_RENDER_MODE_LCD_V.                                           */\r\n  /*                                                                       */\r\n  typedef enum  FT_Pixel_Mode_\r\n  {\r\n    FT_PIXEL_MODE_NONE = 0,\r\n    FT_PIXEL_MODE_MONO,\r\n    FT_PIXEL_MODE_GRAY,\r\n    FT_PIXEL_MODE_GRAY2,\r\n    FT_PIXEL_MODE_GRAY4,\r\n    FT_PIXEL_MODE_LCD,\r\n    FT_PIXEL_MODE_LCD_V,\r\n\r\n    FT_PIXEL_MODE_MAX      /* do not remove */\r\n\r\n  } FT_Pixel_Mode;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Enum>                                                                */\r\n  /*    ft_pixel_mode_xxx                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A list of deprecated constants.  Use the corresponding             */\r\n  /*    @FT_Pixel_Mode values instead.                                     */\r\n  /*                                                                       */\r\n  /* <Values>                                                              */\r\n  /*    ft_pixel_mode_none  :: See @FT_PIXEL_MODE_NONE.                    */\r\n  /*    ft_pixel_mode_mono  :: See @FT_PIXEL_MODE_MONO.                    */\r\n  /*    ft_pixel_mode_grays :: See @FT_PIXEL_MODE_GRAY.                    */\r\n  /*    ft_pixel_mode_pal2  :: See @FT_PIXEL_MODE_GRAY2.                   */\r\n  /*    ft_pixel_mode_pal4  :: See @FT_PIXEL_MODE_GRAY4.                   */\r\n  /*                                                                       */\r\n#define ft_pixel_mode_none   FT_PIXEL_MODE_NONE\r\n#define ft_pixel_mode_mono   FT_PIXEL_MODE_MONO\r\n#define ft_pixel_mode_grays  FT_PIXEL_MODE_GRAY\r\n#define ft_pixel_mode_pal2   FT_PIXEL_MODE_GRAY2\r\n#define ft_pixel_mode_pal4   FT_PIXEL_MODE_GRAY4\r\n\r\n /* */\r\n\r\n#if 0\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Enum>                                                                */\r\n  /*    FT_Palette_Mode                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    THIS TYPE IS DEPRECATED.  DO NOT USE IT!                           */\r\n  /*                                                                       */\r\n  /*    An enumeration type to describe the format of a bitmap palette,    */\r\n  /*    used with ft_pixel_mode_pal4 and ft_pixel_mode_pal8.               */\r\n  /*                                                                       */\r\n  /* <Values>                                                              */\r\n  /*    ft_palette_mode_rgb  :: The palette is an array of 3-byte RGB      */\r\n  /*                            records.                                   */\r\n  /*                                                                       */\r\n  /*    ft_palette_mode_rgba :: The palette is an array of 4-byte RGBA     */\r\n  /*                            records.                                   */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    As ft_pixel_mode_pal2, pal4 and pal8 are currently unused by       */\r\n  /*    FreeType, these types are not handled by the library itself.       */\r\n  /*                                                                       */\r\n  typedef enum  FT_Palette_Mode_\r\n  {\r\n    ft_palette_mode_rgb = 0,\r\n    ft_palette_mode_rgba,\r\n\r\n    ft_palette_mode_max   /* do not remove */\r\n\r\n  } FT_Palette_Mode;\r\n\r\n  /* */\r\n\r\n#endif\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Bitmap                                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to describe a bitmap or pixmap to the raster.     */\r\n  /*    Note that we now manage pixmaps of various depths through the      */\r\n  /*    `pixel_mode' field.                                                */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    rows         :: The number of bitmap rows.                         */\r\n  /*                                                                       */\r\n  /*    width        :: The number of pixels in bitmap row.                */\r\n  /*                                                                       */\r\n  /*    pitch        :: The pitch's absolute value is the number of bytes  */\r\n  /*                    taken by one bitmap row, including padding.        */\r\n  /*                    However, the pitch is positive when the bitmap has */\r\n  /*                    a `down' flow, and negative when it has an `up'    */\r\n  /*                    flow.  In all cases, the pitch is an offset to add */\r\n  /*                    to a bitmap pointer in order to go down one row.   */\r\n  /*                                                                       */\r\n  /*                    Note that `padding' means the alignment of a       */\r\n  /*                    bitmap to a byte border, and FreeType functions    */\r\n  /*                    normally align to the smallest possible integer    */\r\n  /*                    value.                                             */\r\n  /*                                                                       */\r\n  /*                    For the B/W rasterizer, `pitch' is always an even  */\r\n  /*                    number.                                            */\r\n  /*                                                                       */\r\n  /*                    To change the pitch of a bitmap (say, to make it a */\r\n  /*                    multiple of 4), use @FT_Bitmap_Convert.            */\r\n  /*                    Alternatively, you might use callback functions to */\r\n  /*                    directly render to the application's surface; see  */\r\n  /*                    the file `example2.cpp' in the tutorial for a      */\r\n  /*                    demonstration.                                     */\r\n  /*                                                                       */\r\n  /*    buffer       :: A typeless pointer to the bitmap buffer.  This     */\r\n  /*                    value should be aligned on 32-bit boundaries in    */\r\n  /*                    most cases.                                        */\r\n  /*                                                                       */\r\n  /*    num_grays    :: This field is only used with                       */\r\n  /*                    @FT_PIXEL_MODE_GRAY; it gives the number of gray   */\r\n  /*                    levels used in the bitmap.                         */\r\n  /*                                                                       */\r\n  /*    pixel_mode   :: The pixel mode, i.e., how pixel bits are stored.   */\r\n  /*                    See @FT_Pixel_Mode for possible values.            */\r\n  /*                                                                       */\r\n  /*    palette_mode :: This field is intended for paletted pixel modes;   */\r\n  /*                    it indicates how the palette is stored.  Not       */\r\n  /*                    used currently.                                    */\r\n  /*                                                                       */\r\n  /*    palette      :: A typeless pointer to the bitmap palette; this     */\r\n  /*                    field is intended for paletted pixel modes.  Not   */\r\n  /*                    used currently.                                    */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*   For now, the only pixel modes supported by FreeType are mono and    */\r\n  /*   grays.  However, drivers might be added in the future to support    */\r\n  /*   more `colorful' options.                                            */\r\n  /*                                                                       */\r\n  typedef struct  FT_Bitmap_\r\n  {\r\n    int             rows;\r\n    int             width;\r\n    int             pitch;\r\n    unsigned char*  buffer;\r\n    short           num_grays;\r\n    char            pixel_mode;\r\n    char            palette_mode;\r\n    void*           palette;\r\n\r\n  } FT_Bitmap;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    outline_processing                                                 */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Outline                                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This structure is used to describe an outline to the scan-line     */\r\n  /*    converter.                                                         */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    n_contours :: The number of contours in the outline.               */\r\n  /*                                                                       */\r\n  /*    n_points   :: The number of points in the outline.                 */\r\n  /*                                                                       */\r\n  /*    points     :: A pointer to an array of `n_points' @FT_Vector       */\r\n  /*                  elements, giving the outline's point coordinates.    */\r\n  /*                                                                       */\r\n  /*    tags       :: A pointer to an array of `n_points' chars, giving    */\r\n  /*                  each outline point's type.                           */\r\n  /*                                                                       */\r\n  /*                  If bit~0 is unset, the point is `off' the curve,     */\r\n  /*                  i.e., a Bézier control point, while it is `on' if    */\r\n  /*                  set.                                                 */\r\n  /*                                                                       */\r\n  /*                  Bit~1 is meaningful for `off' points only.  If set,  */\r\n  /*                  it indicates a third-order Bézier arc control point; */\r\n  /*                  and a second-order control point if unset.           */\r\n  /*                                                                       */\r\n  /*                  If bit~2 is set, bits 5-7 contain the drop-out mode  */\r\n  /*                  (as defined in the OpenType specification; the value */\r\n  /*                  is the same as the argument to the SCANMODE          */\r\n  /*                  instruction).                                        */\r\n  /*                                                                       */\r\n  /*                  Bits 3 and~4 are reserved for internal purposes.     */\r\n  /*                                                                       */\r\n  /*    contours   :: An array of `n_contours' shorts, giving the end      */\r\n  /*                  point of each contour within the outline.  For       */\r\n  /*                  example, the first contour is defined by the points  */\r\n  /*                  `0' to `contours[0]', the second one is defined by   */\r\n  /*                  the points `contours[0]+1' to `contours[1]', etc.    */\r\n  /*                                                                       */\r\n  /*    flags      :: A set of bit flags used to characterize the outline  */\r\n  /*                  and give hints to the scan-converter and hinter on   */\r\n  /*                  how to convert/grid-fit it.  See @FT_OUTLINE_FLAGS.  */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The B/W rasterizer only checks bit~2 in the `tags' array for the   */\r\n  /*    first point of each contour.  The drop-out mode as given with      */\r\n  /*    @FT_OUTLINE_IGNORE_DROPOUTS, @FT_OUTLINE_SMART_DROPOUTS, and       */\r\n  /*    @FT_OUTLINE_INCLUDE_STUBS in `flags' is then overridden.           */\r\n  /*                                                                       */\r\n  typedef struct  FT_Outline_\r\n  {\r\n    short       n_contours;      /* number of contours in glyph        */\r\n    short       n_points;        /* number of points in the glyph      */\r\n\r\n    FT_Vector*  points;          /* the outline's points               */\r\n    char*       tags;            /* the points flags                   */\r\n    short*      contours;        /* the contour end points             */\r\n\r\n    int         flags;           /* outline masks                      */\r\n\r\n  } FT_Outline;\r\n\r\n  /* Following limits must be consistent with */\r\n  /* FT_Outline.{n_contours,n_points}         */\r\n#define FT_OUTLINE_CONTOURS_MAX  SHRT_MAX\r\n#define FT_OUTLINE_POINTS_MAX    SHRT_MAX\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Enum>                                                                */\r\n  /*    FT_OUTLINE_FLAGS                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A list of bit-field constants use for the flags in an outline's    */\r\n  /*    `flags' field.                                                     */\r\n  /*                                                                       */\r\n  /* <Values>                                                              */\r\n  /*    FT_OUTLINE_NONE ::                                                 */\r\n  /*      Value~0 is reserved.                                             */\r\n  /*                                                                       */\r\n  /*    FT_OUTLINE_OWNER ::                                                */\r\n  /*      If set, this flag indicates that the outline's field arrays      */\r\n  /*      (i.e., `points', `flags', and `contours') are `owned' by the     */\r\n  /*      outline object, and should thus be freed when it is destroyed.   */\r\n  /*                                                                       */\r\n  /*    FT_OUTLINE_EVEN_ODD_FILL ::                                        */\r\n  /*      By default, outlines are filled using the non-zero winding rule. */\r\n  /*      If set to 1, the outline will be filled using the even-odd fill  */\r\n  /*      rule (only works with the smooth rasterizer).                    */\r\n  /*                                                                       */\r\n  /*    FT_OUTLINE_REVERSE_FILL ::                                         */\r\n  /*      By default, outside contours of an outline are oriented in       */\r\n  /*      clock-wise direction, as defined in the TrueType specification.  */\r\n  /*      This flag is set if the outline uses the opposite direction      */\r\n  /*      (typically for Type~1 fonts).  This flag is ignored by the scan  */\r\n  /*      converter.                                                       */\r\n  /*                                                                       */\r\n  /*    FT_OUTLINE_IGNORE_DROPOUTS ::                                      */\r\n  /*      By default, the scan converter will try to detect drop-outs in   */\r\n  /*      an outline and correct the glyph bitmap to ensure consistent     */\r\n  /*      shape continuity.  If set, this flag hints the scan-line         */\r\n  /*      converter to ignore such cases.  See below for more information. */\r\n  /*                                                                       */\r\n  /*    FT_OUTLINE_SMART_DROPOUTS ::                                       */\r\n  /*      Select smart dropout control.  If unset, use simple dropout      */\r\n  /*      control.  Ignored if @FT_OUTLINE_IGNORE_DROPOUTS is set.  See    */\r\n  /*      below for more information.                                      */\r\n  /*                                                                       */\r\n  /*    FT_OUTLINE_INCLUDE_STUBS ::                                        */\r\n  /*      If set, turn pixels on for `stubs', otherwise exclude them.      */\r\n  /*      Ignored if @FT_OUTLINE_IGNORE_DROPOUTS is set.  See below for    */\r\n  /*      more information.                                                */\r\n  /*                                                                       */\r\n  /*    FT_OUTLINE_HIGH_PRECISION ::                                       */\r\n  /*      This flag indicates that the scan-line converter should try to   */\r\n  /*      convert this outline to bitmaps with the highest possible        */\r\n  /*      quality.  It is typically set for small character sizes.  Note   */\r\n  /*      that this is only a hint that might be completely ignored by a   */\r\n  /*      given scan-converter.                                            */\r\n  /*                                                                       */\r\n  /*    FT_OUTLINE_SINGLE_PASS ::                                          */\r\n  /*      This flag is set to force a given scan-converter to only use a   */\r\n  /*      single pass over the outline to render a bitmap glyph image.     */\r\n  /*      Normally, it is set for very large character sizes.  It is only  */\r\n  /*      a hint that might be completely ignored by a given               */\r\n  /*      scan-converter.                                                  */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The flags @FT_OUTLINE_IGNORE_DROPOUTS, @FT_OUTLINE_SMART_DROPOUTS, */\r\n  /*    and @FT_OUTLINE_INCLUDE_STUBS are ignored by the smooth            */\r\n  /*    rasterizer.                                                        */\r\n  /*                                                                       */\r\n  /*    There exists a second mechanism to pass the drop-out mode to the   */\r\n  /*    B/W rasterizer; see the `tags' field in @FT_Outline.               */\r\n  /*                                                                       */\r\n  /*    Please refer to the description of the `SCANTYPE' instruction in   */\r\n  /*    the OpenType specification (in file `ttinst1.doc') how simple      */\r\n  /*    drop-outs, smart drop-outs, and stubs are defined.                 */\r\n  /*                                                                       */\r\n#define FT_OUTLINE_NONE             0x0\r\n#define FT_OUTLINE_OWNER            0x1\r\n#define FT_OUTLINE_EVEN_ODD_FILL    0x2\r\n#define FT_OUTLINE_REVERSE_FILL     0x4\r\n#define FT_OUTLINE_IGNORE_DROPOUTS  0x8\r\n#define FT_OUTLINE_SMART_DROPOUTS   0x10\r\n#define FT_OUTLINE_INCLUDE_STUBS    0x20\r\n\r\n#define FT_OUTLINE_HIGH_PRECISION   0x100\r\n#define FT_OUTLINE_SINGLE_PASS      0x200\r\n\r\n\r\n /*************************************************************************\r\n  *\r\n  * @enum:\r\n  *   ft_outline_flags\r\n  *\r\n  * @description:\r\n  *   These constants are deprecated.  Please use the corresponding\r\n  *   @FT_OUTLINE_FLAGS values.\r\n  *\r\n  * @values:\r\n  *   ft_outline_none            :: See @FT_OUTLINE_NONE.\r\n  *   ft_outline_owner           :: See @FT_OUTLINE_OWNER.\r\n  *   ft_outline_even_odd_fill   :: See @FT_OUTLINE_EVEN_ODD_FILL.\r\n  *   ft_outline_reverse_fill    :: See @FT_OUTLINE_REVERSE_FILL.\r\n  *   ft_outline_ignore_dropouts :: See @FT_OUTLINE_IGNORE_DROPOUTS.\r\n  *   ft_outline_high_precision  :: See @FT_OUTLINE_HIGH_PRECISION.\r\n  *   ft_outline_single_pass     :: See @FT_OUTLINE_SINGLE_PASS.\r\n  */\r\n#define ft_outline_none             FT_OUTLINE_NONE\r\n#define ft_outline_owner            FT_OUTLINE_OWNER\r\n#define ft_outline_even_odd_fill    FT_OUTLINE_EVEN_ODD_FILL\r\n#define ft_outline_reverse_fill     FT_OUTLINE_REVERSE_FILL\r\n#define ft_outline_ignore_dropouts  FT_OUTLINE_IGNORE_DROPOUTS\r\n#define ft_outline_high_precision   FT_OUTLINE_HIGH_PRECISION\r\n#define ft_outline_single_pass      FT_OUTLINE_SINGLE_PASS\r\n\r\n  /* */\r\n\r\n#define FT_CURVE_TAG( flag )  ( flag & 3 )\r\n\r\n#define FT_CURVE_TAG_ON            1\r\n#define FT_CURVE_TAG_CONIC         0\r\n#define FT_CURVE_TAG_CUBIC         2\r\n\r\n#define FT_CURVE_TAG_HAS_SCANMODE  4\r\n\r\n#define FT_CURVE_TAG_TOUCH_X       8  /* reserved for the TrueType hinter */\r\n#define FT_CURVE_TAG_TOUCH_Y      16  /* reserved for the TrueType hinter */\r\n\r\n#define FT_CURVE_TAG_TOUCH_BOTH    ( FT_CURVE_TAG_TOUCH_X | \\\r\n                                     FT_CURVE_TAG_TOUCH_Y )\r\n\r\n#define FT_Curve_Tag_On       FT_CURVE_TAG_ON\r\n#define FT_Curve_Tag_Conic    FT_CURVE_TAG_CONIC\r\n#define FT_Curve_Tag_Cubic    FT_CURVE_TAG_CUBIC\r\n#define FT_Curve_Tag_Touch_X  FT_CURVE_TAG_TOUCH_X\r\n#define FT_Curve_Tag_Touch_Y  FT_CURVE_TAG_TOUCH_Y\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_Outline_MoveToFunc                                              */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A function pointer type used to describe the signature of a `move  */\r\n  /*    to' function during outline walking/decomposition.                 */\r\n  /*                                                                       */\r\n  /*    A `move to' is emitted to start a new contour in an outline.       */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    to   :: A pointer to the target point of the `move to'.            */\r\n  /*                                                                       */\r\n  /*    user :: A typeless pointer which is passed from the caller of the  */\r\n  /*            decomposition function.                                    */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    Error code.  0~means success.                                      */\r\n  /*                                                                       */\r\n  typedef int\r\n  (*FT_Outline_MoveToFunc)( const FT_Vector*  to,\r\n                            void*             user );\r\n\r\n#define FT_Outline_MoveTo_Func  FT_Outline_MoveToFunc\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_Outline_LineToFunc                                              */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A function pointer type used to describe the signature of a `line  */\r\n  /*    to' function during outline walking/decomposition.                 */\r\n  /*                                                                       */\r\n  /*    A `line to' is emitted to indicate a segment in the outline.       */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    to   :: A pointer to the target point of the `line to'.            */\r\n  /*                                                                       */\r\n  /*    user :: A typeless pointer which is passed from the caller of the  */\r\n  /*            decomposition function.                                    */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    Error code.  0~means success.                                      */\r\n  /*                                                                       */\r\n  typedef int\r\n  (*FT_Outline_LineToFunc)( const FT_Vector*  to,\r\n                            void*             user );\r\n\r\n#define FT_Outline_LineTo_Func  FT_Outline_LineToFunc\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_Outline_ConicToFunc                                             */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A function pointer type used to describe the signature of a `conic */\r\n  /*    to' function during outline walking or decomposition.              */\r\n  /*                                                                       */\r\n  /*    A `conic to' is emitted to indicate a second-order Bézier arc in   */\r\n  /*    the outline.                                                       */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    control :: An intermediate control point between the last position */\r\n  /*               and the new target in `to'.                             */\r\n  /*                                                                       */\r\n  /*    to      :: A pointer to the target end point of the conic arc.     */\r\n  /*                                                                       */\r\n  /*    user    :: A typeless pointer which is passed from the caller of   */\r\n  /*               the decomposition function.                             */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    Error code.  0~means success.                                      */\r\n  /*                                                                       */\r\n  typedef int\r\n  (*FT_Outline_ConicToFunc)( const FT_Vector*  control,\r\n                             const FT_Vector*  to,\r\n                             void*             user );\r\n\r\n#define FT_Outline_ConicTo_Func  FT_Outline_ConicToFunc\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_Outline_CubicToFunc                                             */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A function pointer type used to describe the signature of a `cubic */\r\n  /*    to' function during outline walking or decomposition.              */\r\n  /*                                                                       */\r\n  /*    A `cubic to' is emitted to indicate a third-order Bézier arc.      */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    control1 :: A pointer to the first Bézier control point.           */\r\n  /*                                                                       */\r\n  /*    control2 :: A pointer to the second Bézier control point.          */\r\n  /*                                                                       */\r\n  /*    to       :: A pointer to the target end point.                     */\r\n  /*                                                                       */\r\n  /*    user     :: A typeless pointer which is passed from the caller of  */\r\n  /*                the decomposition function.                            */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    Error code.  0~means success.                                      */\r\n  /*                                                                       */\r\n  typedef int\r\n  (*FT_Outline_CubicToFunc)( const FT_Vector*  control1,\r\n                             const FT_Vector*  control2,\r\n                             const FT_Vector*  to,\r\n                             void*             user );\r\n\r\n#define FT_Outline_CubicTo_Func  FT_Outline_CubicToFunc\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Outline_Funcs                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure to hold various function pointers used during outline  */\r\n  /*    decomposition in order to emit segments, conic, and cubic Béziers. */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    move_to  :: The `move to' emitter.                                 */\r\n  /*                                                                       */\r\n  /*    line_to  :: The segment emitter.                                   */\r\n  /*                                                                       */\r\n  /*    conic_to :: The second-order Bézier arc emitter.                   */\r\n  /*                                                                       */\r\n  /*    cubic_to :: The third-order Bézier arc emitter.                    */\r\n  /*                                                                       */\r\n  /*    shift    :: The shift that is applied to coordinates before they   */\r\n  /*                are sent to the emitter.                               */\r\n  /*                                                                       */\r\n  /*    delta    :: The delta that is applied to coordinates before they   */\r\n  /*                are sent to the emitter, but after the shift.          */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The point coordinates sent to the emitters are the transformed     */\r\n  /*    version of the original coordinates (this is important for high    */\r\n  /*    accuracy during scan-conversion).  The transformation is simple:   */\r\n  /*                                                                       */\r\n  /*    {                                                                  */\r\n  /*      x' = (x << shift) - delta                                        */\r\n  /*      y' = (x << shift) - delta                                        */\r\n  /*    }                                                                  */\r\n  /*                                                                       */\r\n  /*    Set the values of `shift' and `delta' to~0 to get the original     */\r\n  /*    point coordinates.                                                 */\r\n  /*                                                                       */\r\n  typedef struct  FT_Outline_Funcs_\r\n  {\r\n    FT_Outline_MoveToFunc   move_to;\r\n    FT_Outline_LineToFunc   line_to;\r\n    FT_Outline_ConicToFunc  conic_to;\r\n    FT_Outline_CubicToFunc  cubic_to;\r\n\r\n    int                     shift;\r\n    FT_Pos                  delta;\r\n\r\n  } FT_Outline_Funcs;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    basic_types                                                        */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Macro>                                                               */\r\n  /*    FT_IMAGE_TAG                                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This macro converts four-letter tags to an unsigned long type.     */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    Since many 16-bit compilers don't like 32-bit enumerations, you    */\r\n  /*    should redefine this macro in case of problems to something like   */\r\n  /*    this:                                                              */\r\n  /*                                                                       */\r\n  /*    {                                                                  */\r\n  /*      #define FT_IMAGE_TAG( value, _x1, _x2, _x3, _x4 )  value         */\r\n  /*    }                                                                  */\r\n  /*                                                                       */\r\n  /*    to get a simple enumeration without assigning special numbers.     */\r\n  /*                                                                       */\r\n#ifndef FT_IMAGE_TAG\r\n#define FT_IMAGE_TAG( value, _x1, _x2, _x3, _x4 )  \\\r\n          value = ( ( (unsigned long)_x1 << 24 ) | \\\r\n                    ( (unsigned long)_x2 << 16 ) | \\\r\n                    ( (unsigned long)_x3 << 8  ) | \\\r\n                      (unsigned long)_x4         )\r\n#endif /* FT_IMAGE_TAG */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Enum>                                                                */\r\n  /*    FT_Glyph_Format                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    An enumeration type used to describe the format of a given glyph   */\r\n  /*    image.  Note that this version of FreeType only supports two image */\r\n  /*    formats, even though future font drivers will be able to register  */\r\n  /*    their own format.                                                  */\r\n  /*                                                                       */\r\n  /* <Values>                                                              */\r\n  /*    FT_GLYPH_FORMAT_NONE ::                                            */\r\n  /*      The value~0 is reserved.                                         */\r\n  /*                                                                       */\r\n  /*    FT_GLYPH_FORMAT_COMPOSITE ::                                       */\r\n  /*      The glyph image is a composite of several other images.  This    */\r\n  /*      format is _only_ used with @FT_LOAD_NO_RECURSE, and is used to   */\r\n  /*      report compound glyphs (like accented characters).               */\r\n  /*                                                                       */\r\n  /*    FT_GLYPH_FORMAT_BITMAP ::                                          */\r\n  /*      The glyph image is a bitmap, and can be described as an          */\r\n  /*      @FT_Bitmap.  You generally need to access the `bitmap' field of  */\r\n  /*      the @FT_GlyphSlotRec structure to read it.                       */\r\n  /*                                                                       */\r\n  /*    FT_GLYPH_FORMAT_OUTLINE ::                                         */\r\n  /*      The glyph image is a vectorial outline made of line segments     */\r\n  /*      and Bézier arcs; it can be described as an @FT_Outline; you      */\r\n  /*      generally want to access the `outline' field of the              */\r\n  /*      @FT_GlyphSlotRec structure to read it.                           */\r\n  /*                                                                       */\r\n  /*    FT_GLYPH_FORMAT_PLOTTER ::                                         */\r\n  /*      The glyph image is a vectorial path with no inside and outside   */\r\n  /*      contours.  Some Type~1 fonts, like those in the Hershey family,  */\r\n  /*      contain glyphs in this format.  These are described as           */\r\n  /*      @FT_Outline, but FreeType isn't currently capable of rendering   */\r\n  /*      them correctly.                                                  */\r\n  /*                                                                       */\r\n  typedef enum  FT_Glyph_Format_\r\n  {\r\n    FT_IMAGE_TAG( FT_GLYPH_FORMAT_NONE, 0, 0, 0, 0 ),\r\n\r\n    FT_IMAGE_TAG( FT_GLYPH_FORMAT_COMPOSITE, 'c', 'o', 'm', 'p' ),\r\n    FT_IMAGE_TAG( FT_GLYPH_FORMAT_BITMAP,    'b', 'i', 't', 's' ),\r\n    FT_IMAGE_TAG( FT_GLYPH_FORMAT_OUTLINE,   'o', 'u', 't', 'l' ),\r\n    FT_IMAGE_TAG( FT_GLYPH_FORMAT_PLOTTER,   'p', 'l', 'o', 't' )\r\n\r\n  } FT_Glyph_Format;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Enum>                                                                */\r\n  /*    ft_glyph_format_xxx                                                */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A list of deprecated constants.  Use the corresponding             */\r\n  /*    @FT_Glyph_Format values instead.                                   */\r\n  /*                                                                       */\r\n  /* <Values>                                                              */\r\n  /*    ft_glyph_format_none      :: See @FT_GLYPH_FORMAT_NONE.            */\r\n  /*    ft_glyph_format_composite :: See @FT_GLYPH_FORMAT_COMPOSITE.       */\r\n  /*    ft_glyph_format_bitmap    :: See @FT_GLYPH_FORMAT_BITMAP.          */\r\n  /*    ft_glyph_format_outline   :: See @FT_GLYPH_FORMAT_OUTLINE.         */\r\n  /*    ft_glyph_format_plotter   :: See @FT_GLYPH_FORMAT_PLOTTER.         */\r\n  /*                                                                       */\r\n#define ft_glyph_format_none       FT_GLYPH_FORMAT_NONE\r\n#define ft_glyph_format_composite  FT_GLYPH_FORMAT_COMPOSITE\r\n#define ft_glyph_format_bitmap     FT_GLYPH_FORMAT_BITMAP\r\n#define ft_glyph_format_outline    FT_GLYPH_FORMAT_OUTLINE\r\n#define ft_glyph_format_plotter    FT_GLYPH_FORMAT_PLOTTER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*****                                                               *****/\r\n  /*****            R A S T E R   D E F I N I T I O N S                *****/\r\n  /*****                                                               *****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* A raster is a scan converter, in charge of rendering an outline into  */\r\n  /* a a bitmap.  This section contains the public API for rasters.        */\r\n  /*                                                                       */\r\n  /* Note that in FreeType 2, all rasters are now encapsulated within      */\r\n  /* specific modules called `renderers'.  See `freetype/ftrender.h' for   */\r\n  /* more details on renderers.                                            */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    raster                                                             */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    Scanline Converter                                                 */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    How vectorial outlines are converted into bitmaps and pixmaps.     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This section contains technical definitions.                       */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Raster                                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle (pointer) to a raster object.  Each object can be used    */\r\n  /*    independently to convert an outline into a bitmap or pixmap.       */\r\n  /*                                                                       */\r\n  typedef struct FT_RasterRec_*  FT_Raster;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Span                                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to model a single span of gray (or black) pixels  */\r\n  /*    when rendering a monochrome or anti-aliased bitmap.                */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    x        :: The span's horizontal start position.                  */\r\n  /*                                                                       */\r\n  /*    len      :: The span's length in pixels.                           */\r\n  /*                                                                       */\r\n  /*    coverage :: The span color/coverage, ranging from 0 (background)   */\r\n  /*                to 255 (foreground).  Only used for anti-aliased       */\r\n  /*                rendering.                                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    This structure is used by the span drawing callback type named     */\r\n  /*    @FT_SpanFunc which takes the y~coordinate of the span as a         */\r\n  /*    a parameter.                                                       */\r\n  /*                                                                       */\r\n  /*    The coverage value is always between 0 and 255.  If you want less  */\r\n  /*    gray values, the callback function has to reduce them.             */\r\n  /*                                                                       */\r\n  typedef struct  FT_Span_\r\n  {\r\n    short           x;\r\n    unsigned short  len;\r\n    unsigned char   coverage;\r\n\r\n  } FT_Span;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_SpanFunc                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A function used as a call-back by the anti-aliased renderer in     */\r\n  /*    order to let client applications draw themselves the gray pixel    */\r\n  /*    spans on each scan line.                                           */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    y     :: The scanline's y~coordinate.                              */\r\n  /*                                                                       */\r\n  /*    count :: The number of spans to draw on this scanline.             */\r\n  /*                                                                       */\r\n  /*    spans :: A table of `count' spans to draw on the scanline.         */\r\n  /*                                                                       */\r\n  /*    user  :: User-supplied data that is passed to the callback.        */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    This callback allows client applications to directly render the    */\r\n  /*    gray spans of the anti-aliased bitmap to any kind of surfaces.     */\r\n  /*                                                                       */\r\n  /*    This can be used to write anti-aliased outlines directly to a      */\r\n  /*    given background bitmap, and even perform translucency.            */\r\n  /*                                                                       */\r\n  /*    Note that the `count' field cannot be greater than a fixed value   */\r\n  /*    defined by the `FT_MAX_GRAY_SPANS' configuration macro in          */\r\n  /*    `ftoption.h'.  By default, this value is set to~32, which means    */\r\n  /*    that if there are more than 32~spans on a given scanline, the      */\r\n  /*    callback is called several times with the same `y' parameter in    */\r\n  /*    order to draw all callbacks.                                       */\r\n  /*                                                                       */\r\n  /*    Otherwise, the callback is only called once per scan-line, and     */\r\n  /*    only for those scanlines that do have `gray' pixels on them.       */\r\n  /*                                                                       */\r\n  typedef void\r\n  (*FT_SpanFunc)( int             y,\r\n                  int             count,\r\n                  const FT_Span*  spans,\r\n                  void*           user );\r\n\r\n#define FT_Raster_Span_Func  FT_SpanFunc\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_Raster_BitTest_Func                                             */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    THIS TYPE IS DEPRECATED.  DO NOT USE IT.                           */\r\n  /*                                                                       */\r\n  /*    A function used as a call-back by the monochrome scan-converter    */\r\n  /*    to test whether a given target pixel is already set to the drawing */\r\n  /*    `color'.  These tests are crucial to implement drop-out control    */\r\n  /*    per-se the TrueType spec.                                          */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    y     :: The pixel's y~coordinate.                                 */\r\n  /*                                                                       */\r\n  /*    x     :: The pixel's x~coordinate.                                 */\r\n  /*                                                                       */\r\n  /*    user  :: User-supplied data that is passed to the callback.        */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*   1~if the pixel is `set', 0~otherwise.                               */\r\n  /*                                                                       */\r\n  typedef int\r\n  (*FT_Raster_BitTest_Func)( int    y,\r\n                             int    x,\r\n                             void*  user );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_Raster_BitSet_Func                                              */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    THIS TYPE IS DEPRECATED.  DO NOT USE IT.                           */\r\n  /*                                                                       */\r\n  /*    A function used as a call-back by the monochrome scan-converter    */\r\n  /*    to set an individual target pixel.  This is crucial to implement   */\r\n  /*    drop-out control according to the TrueType specification.          */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    y     :: The pixel's y~coordinate.                                 */\r\n  /*                                                                       */\r\n  /*    x     :: The pixel's x~coordinate.                                 */\r\n  /*                                                                       */\r\n  /*    user  :: User-supplied data that is passed to the callback.        */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    1~if the pixel is `set', 0~otherwise.                              */\r\n  /*                                                                       */\r\n  typedef void\r\n  (*FT_Raster_BitSet_Func)( int    y,\r\n                            int    x,\r\n                            void*  user );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Enum>                                                                */\r\n  /*    FT_RASTER_FLAG_XXX                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A list of bit flag constants as used in the `flags' field of a     */\r\n  /*    @FT_Raster_Params structure.                                       */\r\n  /*                                                                       */\r\n  /* <Values>                                                              */\r\n  /*    FT_RASTER_FLAG_DEFAULT :: This value is 0.                         */\r\n  /*                                                                       */\r\n  /*    FT_RASTER_FLAG_AA      :: This flag is set to indicate that an     */\r\n  /*                              anti-aliased glyph image should be       */\r\n  /*                              generated.  Otherwise, it will be        */\r\n  /*                              monochrome (1-bit).                      */\r\n  /*                                                                       */\r\n  /*    FT_RASTER_FLAG_DIRECT  :: This flag is set to indicate direct      */\r\n  /*                              rendering.  In this mode, client         */\r\n  /*                              applications must provide their own span */\r\n  /*                              callback.  This lets them directly       */\r\n  /*                              draw or compose over an existing bitmap. */\r\n  /*                              If this bit is not set, the target       */\r\n  /*                              pixmap's buffer _must_ be zeroed before  */\r\n  /*                              rendering.                               */\r\n  /*                                                                       */\r\n  /*                              Note that for now, direct rendering is   */\r\n  /*                              only possible with anti-aliased glyphs.  */\r\n  /*                                                                       */\r\n  /*    FT_RASTER_FLAG_CLIP    :: This flag is only used in direct         */\r\n  /*                              rendering mode.  If set, the output will */\r\n  /*                              be clipped to a box specified in the     */\r\n  /*                              `clip_box' field of the                  */\r\n  /*                              @FT_Raster_Params structure.             */\r\n  /*                                                                       */\r\n  /*                              Note that by default, the glyph bitmap   */\r\n  /*                              is clipped to the target pixmap, except  */\r\n  /*                              in direct rendering mode where all spans */\r\n  /*                              are generated if no clipping box is set. */\r\n  /*                                                                       */\r\n#define FT_RASTER_FLAG_DEFAULT  0x0\r\n#define FT_RASTER_FLAG_AA       0x1\r\n#define FT_RASTER_FLAG_DIRECT   0x2\r\n#define FT_RASTER_FLAG_CLIP     0x4\r\n\r\n  /* deprecated */\r\n#define ft_raster_flag_default  FT_RASTER_FLAG_DEFAULT\r\n#define ft_raster_flag_aa       FT_RASTER_FLAG_AA\r\n#define ft_raster_flag_direct   FT_RASTER_FLAG_DIRECT\r\n#define ft_raster_flag_clip     FT_RASTER_FLAG_CLIP\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Raster_Params                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure to hold the arguments used by a raster's render        */\r\n  /*    function.                                                          */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    target      :: The target bitmap.                                  */\r\n  /*                                                                       */\r\n  /*    source      :: A pointer to the source glyph image (e.g., an       */\r\n  /*                   @FT_Outline).                                       */\r\n  /*                                                                       */\r\n  /*    flags       :: The rendering flags.                                */\r\n  /*                                                                       */\r\n  /*    gray_spans  :: The gray span drawing callback.                     */\r\n  /*                                                                       */\r\n  /*    black_spans :: The black span drawing callback.  UNIMPLEMENTED!    */\r\n  /*                                                                       */\r\n  /*    bit_test    :: The bit test callback.  UNIMPLEMENTED!              */\r\n  /*                                                                       */\r\n  /*    bit_set     :: The bit set callback.  UNIMPLEMENTED!               */\r\n  /*                                                                       */\r\n  /*    user        :: User-supplied data that is passed to each drawing   */\r\n  /*                   callback.                                           */\r\n  /*                                                                       */\r\n  /*    clip_box    :: An optional clipping box.  It is only used in       */\r\n  /*                   direct rendering mode.  Note that coordinates here  */\r\n  /*                   should be expressed in _integer_ pixels (and not in */\r\n  /*                   26.6 fixed-point units).                            */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    An anti-aliased glyph bitmap is drawn if the @FT_RASTER_FLAG_AA    */\r\n  /*    bit flag is set in the `flags' field, otherwise a monochrome       */\r\n  /*    bitmap is generated.                                               */\r\n  /*                                                                       */\r\n  /*    If the @FT_RASTER_FLAG_DIRECT bit flag is set in `flags', the      */\r\n  /*    raster will call the `gray_spans' callback to draw gray pixel      */\r\n  /*    spans, in the case of an aa glyph bitmap, it will call             */\r\n  /*    `black_spans', and `bit_test' and `bit_set' in the case of a       */\r\n  /*    monochrome bitmap.  This allows direct composition over a          */\r\n  /*    pre-existing bitmap through user-provided callbacks to perform the */\r\n  /*    span drawing/composition.                                          */\r\n  /*                                                                       */\r\n  /*    Note that the `bit_test' and `bit_set' callbacks are required when */\r\n  /*    rendering a monochrome bitmap, as they are crucial to implement    */\r\n  /*    correct drop-out control as defined in the TrueType specification. */\r\n  /*                                                                       */\r\n  typedef struct  FT_Raster_Params_\r\n  {\r\n    const FT_Bitmap*        target;\r\n    const void*             source;\r\n    int                     flags;\r\n    FT_SpanFunc             gray_spans;\r\n    FT_SpanFunc             black_spans;  /* doesn't work! */\r\n    FT_Raster_BitTest_Func  bit_test;     /* doesn't work! */\r\n    FT_Raster_BitSet_Func   bit_set;      /* doesn't work! */\r\n    void*                   user;\r\n    FT_BBox                 clip_box;\r\n\r\n  } FT_Raster_Params;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_Raster_NewFunc                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A function used to create a new raster object.                     */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    memory :: A handle to the memory allocator.                        */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    raster :: A handle to the new raster object.                       */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    Error code.  0~means success.                                      */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The `memory' parameter is a typeless pointer in order to avoid     */\r\n  /*    un-wanted dependencies on the rest of the FreeType code.  In       */\r\n  /*    practice, it is an @FT_Memory object, i.e., a handle to the        */\r\n  /*    standard FreeType memory allocator.  However, this field can be    */\r\n  /*    completely ignored by a given raster implementation.               */\r\n  /*                                                                       */\r\n  typedef int\r\n  (*FT_Raster_NewFunc)( void*       memory,\r\n                        FT_Raster*  raster );\r\n\r\n#define FT_Raster_New_Func  FT_Raster_NewFunc\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_Raster_DoneFunc                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A function used to destroy a given raster object.                  */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    raster :: A handle to the raster object.                           */\r\n  /*                                                                       */\r\n  typedef void\r\n  (*FT_Raster_DoneFunc)( FT_Raster  raster );\r\n\r\n#define FT_Raster_Done_Func  FT_Raster_DoneFunc\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_Raster_ResetFunc                                                */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    FreeType provides an area of memory called the `render pool',      */\r\n  /*    available to all registered rasters.  This pool can be freely used */\r\n  /*    during a given scan-conversion but is shared by all rasters.  Its  */\r\n  /*    content is thus transient.                                         */\r\n  /*                                                                       */\r\n  /*    This function is called each time the render pool changes, or just */\r\n  /*    after a new raster object is created.                              */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    raster    :: A handle to the new raster object.                    */\r\n  /*                                                                       */\r\n  /*    pool_base :: The address in memory of the render pool.             */\r\n  /*                                                                       */\r\n  /*    pool_size :: The size in bytes of the render pool.                 */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    Rasters can ignore the render pool and rely on dynamic memory      */\r\n  /*    allocation if they want to (a handle to the memory allocator is    */\r\n  /*    passed to the raster constructor).  However, this is not           */\r\n  /*    recommended for efficiency purposes.                               */\r\n  /*                                                                       */\r\n  typedef void\r\n  (*FT_Raster_ResetFunc)( FT_Raster       raster,\r\n                          unsigned char*  pool_base,\r\n                          unsigned long   pool_size );\r\n\r\n#define FT_Raster_Reset_Func  FT_Raster_ResetFunc\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_Raster_SetModeFunc                                              */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This function is a generic facility to change modes or attributes  */\r\n  /*    in a given raster.  This can be used for debugging purposes, or    */\r\n  /*    simply to allow implementation-specific `features' in a given      */\r\n  /*    raster module.                                                     */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    raster :: A handle to the new raster object.                       */\r\n  /*                                                                       */\r\n  /*    mode   :: A 4-byte tag used to name the mode or property.          */\r\n  /*                                                                       */\r\n  /*    args   :: A pointer to the new mode/property to use.               */\r\n  /*                                                                       */\r\n  typedef int\r\n  (*FT_Raster_SetModeFunc)( FT_Raster      raster,\r\n                            unsigned long  mode,\r\n                            void*          args );\r\n\r\n#define FT_Raster_Set_Mode_Func  FT_Raster_SetModeFunc\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_Raster_RenderFunc                                               */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Invoke a given raster to scan-convert a given glyph image into a   */\r\n  /*    target bitmap.                                                     */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    raster :: A handle to the raster object.                           */\r\n  /*                                                                       */\r\n  /*    params :: A pointer to an @FT_Raster_Params structure used to      */\r\n  /*              store the rendering parameters.                          */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    Error code.  0~means success.                                      */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The exact format of the source image depends on the raster's glyph */\r\n  /*    format defined in its @FT_Raster_Funcs structure.  It can be an    */\r\n  /*    @FT_Outline or anything else in order to support a large array of  */\r\n  /*    glyph formats.                                                     */\r\n  /*                                                                       */\r\n  /*    Note also that the render function can fail and return a           */\r\n  /*    `FT_Err_Unimplemented_Feature' error code if the raster used does  */\r\n  /*    not support direct composition.                                    */\r\n  /*                                                                       */\r\n  /*    XXX: For now, the standard raster doesn't support direct           */\r\n  /*         composition but this should change for the final release (see */\r\n  /*         the files `demos/src/ftgrays.c' and `demos/src/ftgrays2.c'    */\r\n  /*         for examples of distinct implementations which support direct */\r\n  /*         composition).                                                 */\r\n  /*                                                                       */\r\n  typedef int\r\n  (*FT_Raster_RenderFunc)( FT_Raster                raster,\r\n                           const FT_Raster_Params*  params );\r\n\r\n#define FT_Raster_Render_Func  FT_Raster_RenderFunc\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Raster_Funcs                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*   A structure used to describe a given raster class to the library.   */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    glyph_format  :: The supported glyph format for this raster.       */\r\n  /*                                                                       */\r\n  /*    raster_new    :: The raster constructor.                           */\r\n  /*                                                                       */\r\n  /*    raster_reset  :: Used to reset the render pool within the raster.  */\r\n  /*                                                                       */\r\n  /*    raster_render :: A function to render a glyph into a given bitmap. */\r\n  /*                                                                       */\r\n  /*    raster_done   :: The raster destructor.                            */\r\n  /*                                                                       */\r\n  typedef struct  FT_Raster_Funcs_\r\n  {\r\n    FT_Glyph_Format        glyph_format;\r\n    FT_Raster_NewFunc      raster_new;\r\n    FT_Raster_ResetFunc    raster_reset;\r\n    FT_Raster_SetModeFunc  raster_set_mode;\r\n    FT_Raster_RenderFunc   raster_render;\r\n    FT_Raster_DoneFunc     raster_done;\r\n\r\n  } FT_Raster_Funcs;\r\n\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTIMAGE_H__ */\r\n\r\n\r\n/* END */\r\n\r\n\r\n/* Local Variables: */\r\n/* coding: utf-8    */\r\n/* End:             */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftincrem.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftincrem.h                                                             */\r\n/*                                                                         */\r\n/*    FreeType incremental loading (specification).                        */\r\n/*                                                                         */\r\n/*  Copyright 2002, 2003, 2006, 2007, 2008, 2010 by                        */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTINCREM_H__\r\n#define __FTINCREM_H__\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n  /***************************************************************************\r\n   *\r\n   * @section:\r\n   *    incremental\r\n   *\r\n   * @title:\r\n   *    Incremental Loading\r\n   *\r\n   * @abstract:\r\n   *    Custom Glyph Loading.\r\n   *\r\n   * @description:\r\n   *   This section contains various functions used to perform so-called\r\n   *   `incremental' glyph loading.  This is a mode where all glyphs loaded\r\n   *   from a given @FT_Face are provided by the client application,\r\n   *\r\n   *   Apart from that, all other tables are loaded normally from the font\r\n   *   file.  This mode is useful when FreeType is used within another\r\n   *   engine, e.g., a PostScript Imaging Processor.\r\n   *\r\n   *   To enable this mode, you must use @FT_Open_Face, passing an\r\n   *   @FT_Parameter with the @FT_PARAM_TAG_INCREMENTAL tag and an\r\n   *   @FT_Incremental_Interface value.  See the comments for\r\n   *   @FT_Incremental_InterfaceRec for an example.\r\n   *\r\n   */\r\n\r\n\r\n  /***************************************************************************\r\n   *\r\n   * @type:\r\n   *   FT_Incremental\r\n   *\r\n   * @description:\r\n   *   An opaque type describing a user-provided object used to implement\r\n   *   `incremental' glyph loading within FreeType.  This is used to support\r\n   *   embedded fonts in certain environments (e.g., PostScript interpreters),\r\n   *   where the glyph data isn't in the font file, or must be overridden by\r\n   *   different values.\r\n   *\r\n   * @note:\r\n   *   It is up to client applications to create and implement @FT_Incremental\r\n   *   objects, as long as they provide implementations for the methods\r\n   *   @FT_Incremental_GetGlyphDataFunc, @FT_Incremental_FreeGlyphDataFunc\r\n   *   and @FT_Incremental_GetGlyphMetricsFunc.\r\n   *\r\n   *   See the description of @FT_Incremental_InterfaceRec to understand how\r\n   *   to use incremental objects with FreeType.\r\n   *\r\n   */\r\n  typedef struct FT_IncrementalRec_*  FT_Incremental;\r\n\r\n\r\n  /***************************************************************************\r\n   *\r\n   * @struct:\r\n   *   FT_Incremental_MetricsRec\r\n   *\r\n   * @description:\r\n   *   A small structure used to contain the basic glyph metrics returned\r\n   *   by the @FT_Incremental_GetGlyphMetricsFunc method.\r\n   *\r\n   * @fields:\r\n   *   bearing_x ::\r\n   *     Left bearing, in font units.\r\n   *\r\n   *   bearing_y ::\r\n   *     Top bearing, in font units.\r\n   *\r\n   *   advance ::\r\n   *     Horizontal component of glyph advance, in font units.\r\n   *\r\n   *   advance_v ::\r\n   *     Vertical component of glyph advance, in font units.\r\n   *\r\n   * @note:\r\n   *   These correspond to horizontal or vertical metrics depending on the\r\n   *   value of the `vertical' argument to the function\r\n   *   @FT_Incremental_GetGlyphMetricsFunc.\r\n   *\r\n   */\r\n  typedef struct  FT_Incremental_MetricsRec_\r\n  {\r\n    FT_Long  bearing_x;\r\n    FT_Long  bearing_y;\r\n    FT_Long  advance;\r\n    FT_Long  advance_v;     /* since 2.3.12 */\r\n\r\n  } FT_Incremental_MetricsRec;\r\n\r\n\r\n  /***************************************************************************\r\n   *\r\n   * @struct:\r\n   *   FT_Incremental_Metrics\r\n   *\r\n   * @description:\r\n   *   A handle to an @FT_Incremental_MetricsRec structure.\r\n   *\r\n   */\r\n   typedef struct FT_Incremental_MetricsRec_*  FT_Incremental_Metrics;\r\n\r\n\r\n  /***************************************************************************\r\n   *\r\n   * @type:\r\n   *   FT_Incremental_GetGlyphDataFunc\r\n   *\r\n   * @description:\r\n   *   A function called by FreeType to access a given glyph's data bytes\r\n   *   during @FT_Load_Glyph or @FT_Load_Char if incremental loading is\r\n   *   enabled.\r\n   *\r\n   *   Note that the format of the glyph's data bytes depends on the font\r\n   *   file format.  For TrueType, it must correspond to the raw bytes within\r\n   *   the `glyf' table.  For PostScript formats, it must correspond to the\r\n   *   *unencrypted* charstring bytes, without any `lenIV' header.  It is\r\n   *   undefined for any other format.\r\n   *\r\n   * @input:\r\n   *   incremental ::\r\n   *     Handle to an opaque @FT_Incremental handle provided by the client\r\n   *     application.\r\n   *\r\n   *   glyph_index ::\r\n   *     Index of relevant glyph.\r\n   *\r\n   * @output:\r\n   *   adata ::\r\n   *     A structure describing the returned glyph data bytes (which will be\r\n   *     accessed as a read-only byte block).\r\n   *\r\n   * @return:\r\n   *   FreeType error code.  0~means success.\r\n   *\r\n   * @note:\r\n   *   If this function returns successfully the method\r\n   *   @FT_Incremental_FreeGlyphDataFunc will be called later to release\r\n   *   the data bytes.\r\n   *\r\n   *   Nested calls to @FT_Incremental_GetGlyphDataFunc can happen for\r\n   *   compound glyphs.\r\n   *\r\n   */\r\n  typedef FT_Error\r\n  (*FT_Incremental_GetGlyphDataFunc)( FT_Incremental  incremental,\r\n                                      FT_UInt         glyph_index,\r\n                                      FT_Data*        adata );\r\n\r\n\r\n  /***************************************************************************\r\n   *\r\n   * @type:\r\n   *   FT_Incremental_FreeGlyphDataFunc\r\n   *\r\n   * @description:\r\n   *   A function used to release the glyph data bytes returned by a\r\n   *   successful call to @FT_Incremental_GetGlyphDataFunc.\r\n   *\r\n   * @input:\r\n   *   incremental ::\r\n   *     A handle to an opaque @FT_Incremental handle provided by the client\r\n   *     application.\r\n   *\r\n   *   data ::\r\n   *     A structure describing the glyph data bytes (which will be accessed\r\n   *     as a read-only byte block).\r\n   *\r\n   */\r\n  typedef void\r\n  (*FT_Incremental_FreeGlyphDataFunc)( FT_Incremental  incremental,\r\n                                       FT_Data*        data );\r\n\r\n\r\n  /***************************************************************************\r\n   *\r\n   * @type:\r\n   *   FT_Incremental_GetGlyphMetricsFunc\r\n   *\r\n   * @description:\r\n   *   A function used to retrieve the basic metrics of a given glyph index\r\n   *   before accessing its data.  This is necessary because, in certain\r\n   *   formats like TrueType, the metrics are stored in a different place from\r\n   *   the glyph images proper.\r\n   *\r\n   * @input:\r\n   *   incremental ::\r\n   *     A handle to an opaque @FT_Incremental handle provided by the client\r\n   *     application.\r\n   *\r\n   *   glyph_index ::\r\n   *     Index of relevant glyph.\r\n   *\r\n   *   vertical ::\r\n   *     If true, return vertical metrics.\r\n   *\r\n   *   ametrics ::\r\n   *     This parameter is used for both input and output.\r\n   *     The original glyph metrics, if any, in font units.  If metrics are\r\n   *     not available all the values must be set to zero.\r\n   *\r\n   * @output:\r\n   *   ametrics ::\r\n   *     The replacement glyph metrics in font units.\r\n   *\r\n   */\r\n  typedef FT_Error\r\n  (*FT_Incremental_GetGlyphMetricsFunc)\r\n                      ( FT_Incremental              incremental,\r\n                        FT_UInt                     glyph_index,\r\n                        FT_Bool                     vertical,\r\n                        FT_Incremental_MetricsRec  *ametrics );\r\n\r\n\r\n  /**************************************************************************\r\n   *\r\n   * @struct:\r\n   *   FT_Incremental_FuncsRec\r\n   *\r\n   * @description:\r\n   *   A table of functions for accessing fonts that load data\r\n   *   incrementally.  Used in @FT_Incremental_InterfaceRec.\r\n   *\r\n   * @fields:\r\n   *   get_glyph_data ::\r\n   *     The function to get glyph data.  Must not be null.\r\n   *\r\n   *   free_glyph_data ::\r\n   *     The function to release glyph data.  Must not be null.\r\n   *\r\n   *   get_glyph_metrics ::\r\n   *     The function to get glyph metrics.  May be null if the font does\r\n   *     not provide overriding glyph metrics.\r\n   *\r\n   */\r\n  typedef struct  FT_Incremental_FuncsRec_\r\n  {\r\n    FT_Incremental_GetGlyphDataFunc     get_glyph_data;\r\n    FT_Incremental_FreeGlyphDataFunc    free_glyph_data;\r\n    FT_Incremental_GetGlyphMetricsFunc  get_glyph_metrics;\r\n\r\n  } FT_Incremental_FuncsRec;\r\n\r\n\r\n  /***************************************************************************\r\n   *\r\n   * @struct:\r\n   *   FT_Incremental_InterfaceRec\r\n   *\r\n   * @description:\r\n   *   A structure to be used with @FT_Open_Face to indicate that the user\r\n   *   wants to support incremental glyph loading.  You should use it with\r\n   *   @FT_PARAM_TAG_INCREMENTAL as in the following example:\r\n   *\r\n   *     {\r\n   *       FT_Incremental_InterfaceRec  inc_int;\r\n   *       FT_Parameter                 parameter;\r\n   *       FT_Open_Args                 open_args;\r\n   *\r\n   *\r\n   *       // set up incremental descriptor\r\n   *       inc_int.funcs  = my_funcs;\r\n   *       inc_int.object = my_object;\r\n   *\r\n   *       // set up optional parameter\r\n   *       parameter.tag  = FT_PARAM_TAG_INCREMENTAL;\r\n   *       parameter.data = &inc_int;\r\n   *\r\n   *       // set up FT_Open_Args structure\r\n   *       open_args.flags      = FT_OPEN_PATHNAME | FT_OPEN_PARAMS;\r\n   *       open_args.pathname   = my_font_pathname;\r\n   *       open_args.num_params = 1;\r\n   *       open_args.params     = &parameter; // we use one optional argument\r\n   *\r\n   *       // open the font\r\n   *       error = FT_Open_Face( library, &open_args, index, &face );\r\n   *       ...\r\n   *     }\r\n   *\r\n   */\r\n  typedef struct  FT_Incremental_InterfaceRec_\r\n  {\r\n    const FT_Incremental_FuncsRec*  funcs;\r\n    FT_Incremental                  object;\r\n\r\n  } FT_Incremental_InterfaceRec;\r\n\r\n\r\n  /***************************************************************************\r\n   *\r\n   * @type:\r\n   *   FT_Incremental_Interface\r\n   *\r\n   * @description:\r\n   *   A pointer to an @FT_Incremental_InterfaceRec structure.\r\n   *\r\n   */\r\n  typedef FT_Incremental_InterfaceRec*   FT_Incremental_Interface;\r\n\r\n\r\n  /***************************************************************************\r\n   *\r\n   * @constant:\r\n   *   FT_PARAM_TAG_INCREMENTAL\r\n   *\r\n   * @description:\r\n   *   A constant used as the tag of @FT_Parameter structures to indicate\r\n   *   an incremental loading object to be used by FreeType.\r\n   *\r\n   */\r\n#define FT_PARAM_TAG_INCREMENTAL  FT_MAKE_TAG( 'i', 'n', 'c', 'r' )\r\n\r\n  /* */\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTINCREM_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftlcdfil.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftlcdfil.h                                                             */\r\n/*                                                                         */\r\n/*    FreeType API for color filtering of subpixel bitmap glyphs           */\r\n/*    (specification).                                                     */\r\n/*                                                                         */\r\n/*  Copyright 2006, 2007, 2008, 2010 by                                    */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FT_LCD_FILTER_H__\r\n#define __FT_LCD_FILTER_H__\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n  /***************************************************************************\r\n   *\r\n   * @section:\r\n   *   lcd_filtering\r\n   *\r\n   * @title:\r\n   *   LCD Filtering\r\n   *\r\n   * @abstract:\r\n   *   Reduce color fringes of LCD-optimized bitmaps.\r\n   *\r\n   * @description:\r\n   *   The @FT_Library_SetLcdFilter API can be used to specify a low-pass\r\n   *   filter which is then applied to LCD-optimized bitmaps generated\r\n   *   through @FT_Render_Glyph.  This is useful to reduce color fringes\r\n   *   which would occur with unfiltered rendering.\r\n   *\r\n   *   Note that no filter is active by default, and that this function is\r\n   *   *not* implemented in default builds of the library.  You need to\r\n   *   #define FT_CONFIG_OPTION_SUBPIXEL_RENDERING in your `ftoption.h' file\r\n   *   in order to activate it.\r\n   */\r\n\r\n\r\n  /****************************************************************************\r\n   *\r\n   * @enum:\r\n   *   FT_LcdFilter\r\n   *\r\n   * @description:\r\n   *   A list of values to identify various types of LCD filters.\r\n   *\r\n   * @values:\r\n   *   FT_LCD_FILTER_NONE ::\r\n   *     Do not perform filtering.  When used with subpixel rendering, this\r\n   *     results in sometimes severe color fringes.\r\n   *\r\n   *   FT_LCD_FILTER_DEFAULT ::\r\n   *     The default filter reduces color fringes considerably, at the cost\r\n   *     of a slight blurriness in the output.\r\n   *\r\n   *   FT_LCD_FILTER_LIGHT ::\r\n   *     The light filter is a variant that produces less blurriness at the\r\n   *     cost of slightly more color fringes than the default one.  It might\r\n   *     be better, depending on taste, your monitor, or your personal vision.\r\n   *\r\n   *   FT_LCD_FILTER_LEGACY ::\r\n   *     This filter corresponds to the original libXft color filter.  It\r\n   *     provides high contrast output but can exhibit really bad color\r\n   *     fringes if glyphs are not extremely well hinted to the pixel grid.\r\n   *     In other words, it only works well if the TrueType bytecode\r\n   *     interpreter is enabled *and* high-quality hinted fonts are used.\r\n   *\r\n   *     This filter is only provided for comparison purposes, and might be\r\n   *     disabled or stay unsupported in the future.\r\n   *\r\n   * @since:\r\n   *   2.3.0\r\n   */\r\n  typedef enum  FT_LcdFilter_\r\n  {\r\n    FT_LCD_FILTER_NONE    = 0,\r\n    FT_LCD_FILTER_DEFAULT = 1,\r\n    FT_LCD_FILTER_LIGHT   = 2,\r\n    FT_LCD_FILTER_LEGACY  = 16,\r\n\r\n    FT_LCD_FILTER_MAX   /* do not remove */\r\n\r\n  } FT_LcdFilter;\r\n\r\n\r\n  /**************************************************************************\r\n   *\r\n   * @func:\r\n   *   FT_Library_SetLcdFilter\r\n   *\r\n   * @description:\r\n   *   This function is used to apply color filtering to LCD decimated\r\n   *   bitmaps, like the ones used when calling @FT_Render_Glyph with\r\n   *   @FT_RENDER_MODE_LCD or @FT_RENDER_MODE_LCD_V.\r\n   *\r\n   * @input:\r\n   *   library ::\r\n   *     A handle to the target library instance.\r\n   *\r\n   *   filter ::\r\n   *     The filter type.\r\n   *\r\n   *     You can use @FT_LCD_FILTER_NONE here to disable this feature, or\r\n   *     @FT_LCD_FILTER_DEFAULT to use a default filter that should work\r\n   *     well on most LCD screens.\r\n   *\r\n   * @return:\r\n   *   FreeType error code.  0~means success.\r\n   *\r\n   * @note:\r\n   *   This feature is always disabled by default.  Clients must make an\r\n   *   explicit call to this function with a `filter' value other than\r\n   *   @FT_LCD_FILTER_NONE in order to enable it.\r\n   *\r\n   *   Due to *PATENTS* covering subpixel rendering, this function doesn't\r\n   *   do anything except returning `FT_Err_Unimplemented_Feature' if the\r\n   *   configuration macro FT_CONFIG_OPTION_SUBPIXEL_RENDERING is not\r\n   *   defined in your build of the library, which should correspond to all\r\n   *   default builds of FreeType.\r\n   *\r\n   *   The filter affects glyph bitmaps rendered through @FT_Render_Glyph,\r\n   *   @FT_Outline_Get_Bitmap, @FT_Load_Glyph, and @FT_Load_Char.\r\n   *\r\n   *   It does _not_ affect the output of @FT_Outline_Render and\r\n   *   @FT_Outline_Get_Bitmap.\r\n   *\r\n   *   If this feature is activated, the dimensions of LCD glyph bitmaps are\r\n   *   either larger or taller than the dimensions of the corresponding\r\n   *   outline with regards to the pixel grid.  For example, for\r\n   *   @FT_RENDER_MODE_LCD, the filter adds up to 3~pixels to the left, and\r\n   *   up to 3~pixels to the right.\r\n   *\r\n   *   The bitmap offset values are adjusted correctly, so clients shouldn't\r\n   *   need to modify their layout and glyph positioning code when enabling\r\n   *   the filter.\r\n   *\r\n   * @since:\r\n   *   2.3.0\r\n   */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Library_SetLcdFilter( FT_Library    library,\r\n                           FT_LcdFilter  filter );\r\n\r\n\r\n  /**************************************************************************\r\n   *\r\n   * @func:\r\n   *   FT_Library_SetLcdFilterWeights\r\n   *\r\n   * @description:\r\n   *   Use this function to override the filter weights selected by\r\n   *   @FT_Library_SetLcdFilter.  By default, FreeType uses the quintuple\r\n   *   (0x00, 0x55, 0x56, 0x55, 0x00) for FT_LCD_FILTER_LIGHT, and (0x10,\r\n   *   0x40, 0x70, 0x40, 0x10) for FT_LCD_FILTER_DEFAULT and\r\n   *   FT_LCD_FILTER_LEGACY.\r\n   *\r\n   * @input:\r\n   *   library ::\r\n   *     A handle to the target library instance.\r\n   *\r\n   *   weights ::\r\n   *     A pointer to an array; the function copies the first five bytes and\r\n   *     uses them to specify the filter weights.\r\n   *\r\n   * @return:\r\n   *   FreeType error code.  0~means success.\r\n   *\r\n   * @note:\r\n   *   Due to *PATENTS* covering subpixel rendering, this function doesn't\r\n   *   do anything except returning `FT_Err_Unimplemented_Feature' if the\r\n   *   configuration macro FT_CONFIG_OPTION_SUBPIXEL_RENDERING is not\r\n   *   defined in your build of the library, which should correspond to all\r\n   *   default builds of FreeType.\r\n   *\r\n   *   This function must be called after @FT_Library_SetLcdFilter to have\r\n   *   any effect.\r\n   *\r\n   * @since:\r\n   *   2.4.0\r\n   */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Library_SetLcdFilterWeights( FT_Library      library,\r\n                                  unsigned char  *weights );\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FT_LCD_FILTER_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftlist.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftlist.h                                                               */\r\n/*                                                                         */\r\n/*    Generic list support for FreeType (specification).                   */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2003, 2007, 2010 by                               */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /*  This file implements functions relative to list processing.  Its     */\r\n  /*  data structures are defined in `freetype.h'.                         */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n#ifndef __FTLIST_H__\r\n#define __FTLIST_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    list_processing                                                    */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    List Processing                                                    */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    Simple management of lists.                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This section contains various definitions related to list          */\r\n  /*    processing using doubly-linked nodes.                              */\r\n  /*                                                                       */\r\n  /* <Order>                                                               */\r\n  /*    FT_List                                                            */\r\n  /*    FT_ListNode                                                        */\r\n  /*    FT_ListRec                                                         */\r\n  /*    FT_ListNodeRec                                                     */\r\n  /*                                                                       */\r\n  /*    FT_List_Add                                                        */\r\n  /*    FT_List_Insert                                                     */\r\n  /*    FT_List_Find                                                       */\r\n  /*    FT_List_Remove                                                     */\r\n  /*    FT_List_Up                                                         */\r\n  /*    FT_List_Iterate                                                    */\r\n  /*    FT_List_Iterator                                                   */\r\n  /*    FT_List_Finalize                                                   */\r\n  /*    FT_List_Destructor                                                 */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_List_Find                                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Find the list node for a given listed object.                      */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    list :: A pointer to the parent list.                              */\r\n  /*    data :: The address of the listed object.                          */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    List node.  NULL if it wasn't found.                               */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_ListNode )\r\n  FT_List_Find( FT_List  list,\r\n                void*    data );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_List_Add                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Append an element to the end of a list.                            */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    list :: A pointer to the parent list.                              */\r\n  /*    node :: The node to append.                                        */\r\n  /*                                                                       */\r\n  FT_EXPORT( void )\r\n  FT_List_Add( FT_List      list,\r\n               FT_ListNode  node );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_List_Insert                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Insert an element at the head of a list.                           */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    list :: A pointer to parent list.                                  */\r\n  /*    node :: The node to insert.                                        */\r\n  /*                                                                       */\r\n  FT_EXPORT( void )\r\n  FT_List_Insert( FT_List      list,\r\n                  FT_ListNode  node );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_List_Remove                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Remove a node from a list.  This function doesn't check whether    */\r\n  /*    the node is in the list!                                           */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    node :: The node to remove.                                        */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    list :: A pointer to the parent list.                              */\r\n  /*                                                                       */\r\n  FT_EXPORT( void )\r\n  FT_List_Remove( FT_List      list,\r\n                  FT_ListNode  node );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_List_Up                                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Move a node to the head/top of a list.  Used to maintain LRU       */\r\n  /*    lists.                                                             */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    list :: A pointer to the parent list.                              */\r\n  /*    node :: The node to move.                                          */\r\n  /*                                                                       */\r\n  FT_EXPORT( void )\r\n  FT_List_Up( FT_List      list,\r\n              FT_ListNode  node );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_List_Iterator                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    An FT_List iterator function which is called during a list parse   */\r\n  /*    by @FT_List_Iterate.                                               */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    node :: The current iteration list node.                           */\r\n  /*                                                                       */\r\n  /*    user :: A typeless pointer passed to @FT_List_Iterate.             */\r\n  /*            Can be used to point to the iteration's state.             */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*FT_List_Iterator)( FT_ListNode  node,\r\n                       void*        user );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_List_Iterate                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Parse a list and calls a given iterator function on each element.  */\r\n  /*    Note that parsing is stopped as soon as one of the iterator calls  */\r\n  /*    returns a non-zero value.                                          */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    list     :: A handle to the list.                                  */\r\n  /*    iterator :: An iterator function, called on each node of the list. */\r\n  /*    user     :: A user-supplied field which is passed as the second    */\r\n  /*                argument to the iterator.                              */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    The result (a FreeType error code) of the last iterator call.      */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_List_Iterate( FT_List           list,\r\n                   FT_List_Iterator  iterator,\r\n                   void*             user );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_List_Destructor                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    An @FT_List iterator function which is called during a list        */\r\n  /*    finalization by @FT_List_Finalize to destroy all elements in a     */\r\n  /*    given list.                                                        */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    system :: The current system object.                               */\r\n  /*                                                                       */\r\n  /*    data   :: The current object to destroy.                           */\r\n  /*                                                                       */\r\n  /*    user   :: A typeless pointer passed to @FT_List_Iterate.  It can   */\r\n  /*              be used to point to the iteration's state.               */\r\n  /*                                                                       */\r\n  typedef void\r\n  (*FT_List_Destructor)( FT_Memory  memory,\r\n                         void*      data,\r\n                         void*      user );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_List_Finalize                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Destroy all elements in the list as well as the list itself.       */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    list    :: A handle to the list.                                   */\r\n  /*                                                                       */\r\n  /*    destroy :: A list destructor that will be applied to each element  */\r\n  /*               of the list.                                            */\r\n  /*                                                                       */\r\n  /*    memory  :: The current memory object which handles deallocation.   */\r\n  /*                                                                       */\r\n  /*    user    :: A user-supplied field which is passed as the last       */\r\n  /*               argument to the destructor.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    This function expects that all nodes added by @FT_List_Add or      */\r\n  /*    @FT_List_Insert have been dynamically allocated.                   */\r\n  /*                                                                       */\r\n  FT_EXPORT( void )\r\n  FT_List_Finalize( FT_List             list,\r\n                    FT_List_Destructor  destroy,\r\n                    FT_Memory           memory,\r\n                    void*               user );\r\n\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTLIST_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftlzw.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftlzw.h                                                                */\r\n/*                                                                         */\r\n/*    LZW-compressed stream support.                                       */\r\n/*                                                                         */\r\n/*  Copyright 2004, 2006 by                                                */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTLZW_H__\r\n#define __FTLZW_H__\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    lzw                                                                */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    LZW Streams                                                        */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    Using LZW-compressed font files.                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This section contains the declaration of LZW-specific functions.   */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n /************************************************************************\r\n  *\r\n  * @function:\r\n  *   FT_Stream_OpenLZW\r\n  *\r\n  * @description:\r\n  *   Open a new stream to parse LZW-compressed font files.  This is\r\n  *   mainly used to support the compressed `*.pcf.Z' fonts that come\r\n  *   with XFree86.\r\n  *\r\n  * @input:\r\n  *   stream :: The target embedding stream.\r\n  *\r\n  *   source :: The source stream.\r\n  *\r\n  * @return:\r\n  *   FreeType error code.  0~means success.\r\n  *\r\n  * @note:\r\n  *   The source stream must be opened _before_ calling this function.\r\n  *\r\n  *   Calling the internal function `FT_Stream_Close' on the new stream will\r\n  *   *not* call `FT_Stream_Close' on the source stream.  None of the stream\r\n  *   objects will be released to the heap.\r\n  *\r\n  *   The stream implementation is very basic and resets the decompression\r\n  *   process each time seeking backwards is needed within the stream\r\n  *\r\n  *   In certain builds of the library, LZW compression recognition is\r\n  *   automatically handled when calling @FT_New_Face or @FT_Open_Face.\r\n  *   This means that if no font driver is capable of handling the raw\r\n  *   compressed file, the library will try to open a LZW stream from it\r\n  *   and re-open the face with it.\r\n  *\r\n  *   This function may return `FT_Err_Unimplemented_Feature' if your build\r\n  *   of FreeType was not compiled with LZW support.\r\n  */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Stream_OpenLZW( FT_Stream  stream,\r\n                     FT_Stream  source );\r\n\r\n /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTLZW_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftmac.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftmac.h                                                                */\r\n/*                                                                         */\r\n/*    Additional Mac-specific API.                                         */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2004, 2006, 2007 by                               */\r\n/*  Just van Rossum, David Turner, Robert Wilhelm, and Werner Lemberg.     */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n/***************************************************************************/\r\n/*                                                                         */\r\n/* NOTE: Include this file after <freetype/freetype.h> and after any       */\r\n/*       Mac-specific headers (because this header uses Mac types such as  */\r\n/*       Handle, FSSpec, FSRef, etc.)                                      */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTMAC_H__\r\n#define __FTMAC_H__\r\n\r\n\r\n#include <ft2build.h>\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n/* gcc-3.4.1 and later can warn about functions tagged as deprecated */\r\n#ifndef FT_DEPRECATED_ATTRIBUTE\r\n#if defined(__GNUC__)                                               && \\\r\n    ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))\r\n#define FT_DEPRECATED_ATTRIBUTE  __attribute__((deprecated))\r\n#else\r\n#define FT_DEPRECATED_ATTRIBUTE\r\n#endif\r\n#endif\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    mac_specific                                                       */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    Mac Specific Interface                                             */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    Only available on the Macintosh.                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    The following definitions are only available if FreeType is        */\r\n  /*    compiled on a Macintosh.                                           */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_New_Face_From_FOND                                              */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Create a new face object from a FOND resource.                     */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    library    :: A handle to the library resource.                    */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    fond       :: A FOND resource.                                     */\r\n  /*                                                                       */\r\n  /*    face_index :: Only supported for the -1 `sanity check' special     */\r\n  /*                  case.                                                */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    aface      :: A handle to a new face object.                       */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Notes>                                                               */\r\n  /*    This function can be used to create @FT_Face objects from fonts    */\r\n  /*    that are installed in the system as follows.                       */\r\n  /*                                                                       */\r\n  /*    {                                                                  */\r\n  /*      fond = GetResource( 'FOND', fontName );                          */\r\n  /*      error = FT_New_Face_From_FOND( library, fond, 0, &face );        */\r\n  /*    }                                                                  */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_New_Face_From_FOND( FT_Library  library,\r\n                         Handle      fond,\r\n                         FT_Long     face_index,\r\n                         FT_Face    *aface )\r\n                       FT_DEPRECATED_ATTRIBUTE;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_GetFile_From_Mac_Name                                           */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Return an FSSpec for the disk file containing the named font.      */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    fontName   :: Mac OS name of the font (e.g., Times New Roman       */\r\n  /*                  Bold).                                               */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    pathSpec   :: FSSpec to the file.  For passing to                  */\r\n  /*                  @FT_New_Face_From_FSSpec.                            */\r\n  /*                                                                       */\r\n  /*    face_index :: Index of the face.  For passing to                   */\r\n  /*                  @FT_New_Face_From_FSSpec.                            */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_GetFile_From_Mac_Name( const char*  fontName,\r\n                            FSSpec*      pathSpec,\r\n                            FT_Long*     face_index )\r\n                          FT_DEPRECATED_ATTRIBUTE;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_GetFile_From_Mac_ATS_Name                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Return an FSSpec for the disk file containing the named font.      */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    fontName   :: Mac OS name of the font in ATS framework.            */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    pathSpec   :: FSSpec to the file. For passing to                   */\r\n  /*                  @FT_New_Face_From_FSSpec.                            */\r\n  /*                                                                       */\r\n  /*    face_index :: Index of the face. For passing to                    */\r\n  /*                  @FT_New_Face_From_FSSpec.                            */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_GetFile_From_Mac_ATS_Name( const char*  fontName,\r\n                                FSSpec*      pathSpec,\r\n                                FT_Long*     face_index )\r\n                              FT_DEPRECATED_ATTRIBUTE;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_GetFilePath_From_Mac_ATS_Name                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Return a pathname of the disk file and face index for given font   */\r\n  /*    name which is handled by ATS framework.                            */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    fontName    :: Mac OS name of the font in ATS framework.           */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    path        :: Buffer to store pathname of the file.  For passing  */\r\n  /*                   to @FT_New_Face.  The client must allocate this     */\r\n  /*                   buffer before calling this function.                */\r\n  /*                                                                       */\r\n  /*    maxPathSize :: Lengths of the buffer `path' that client allocated. */\r\n  /*                                                                       */\r\n  /*    face_index  :: Index of the face.  For passing to @FT_New_Face.    */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_GetFilePath_From_Mac_ATS_Name( const char*  fontName,\r\n                                    UInt8*       path,\r\n                                    UInt32       maxPathSize,\r\n                                    FT_Long*     face_index )\r\n                                  FT_DEPRECATED_ATTRIBUTE;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_New_Face_From_FSSpec                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Create a new face object from a given resource and typeface index  */\r\n  /*    using an FSSpec to the font file.                                  */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    library    :: A handle to the library resource.                    */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    spec       :: FSSpec to the font file.                             */\r\n  /*                                                                       */\r\n  /*    face_index :: The index of the face within the resource.  The      */\r\n  /*                  first face has index~0.                              */\r\n  /* <Output>                                                              */\r\n  /*    aface      :: A handle to a new face object.                       */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    @FT_New_Face_From_FSSpec is identical to @FT_New_Face except       */\r\n  /*    it accepts an FSSpec instead of a path.                            */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_New_Face_From_FSSpec( FT_Library     library,\r\n                           const FSSpec  *spec,\r\n                           FT_Long        face_index,\r\n                           FT_Face       *aface )\r\n                         FT_DEPRECATED_ATTRIBUTE;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_New_Face_From_FSRef                                             */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Create a new face object from a given resource and typeface index  */\r\n  /*    using an FSRef to the font file.                                   */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    library    :: A handle to the library resource.                    */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    spec       :: FSRef to the font file.                              */\r\n  /*                                                                       */\r\n  /*    face_index :: The index of the face within the resource.  The      */\r\n  /*                  first face has index~0.                              */\r\n  /* <Output>                                                              */\r\n  /*    aface      :: A handle to a new face object.                       */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    @FT_New_Face_From_FSRef is identical to @FT_New_Face except        */\r\n  /*    it accepts an FSRef instead of a path.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_New_Face_From_FSRef( FT_Library    library,\r\n                          const FSRef  *ref,\r\n                          FT_Long       face_index,\r\n                          FT_Face      *aface )\r\n                        FT_DEPRECATED_ATTRIBUTE;\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n\r\n#endif /* __FTMAC_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftmm.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftmm.h                                                                 */\r\n/*                                                                         */\r\n/*    FreeType Multiple Master font interface (specification).             */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2003, 2004, 2006, 2009 by                         */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTMM_H__\r\n#define __FTMM_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_TYPE1_TABLES_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    multiple_masters                                                   */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    Multiple Masters                                                   */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    How to manage Multiple Masters fonts.                              */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    The following types and functions are used to manage Multiple      */\r\n  /*    Master fonts, i.e., the selection of specific design instances by  */\r\n  /*    setting design axis coordinates.                                   */\r\n  /*                                                                       */\r\n  /*    George Williams has extended this interface to make it work with   */\r\n  /*    both Type~1 Multiple Masters fonts and GX distortable (var)        */\r\n  /*    fonts.  Some of these routines only work with MM fonts, others     */\r\n  /*    will work with both types.  They are similar enough that a         */\r\n  /*    consistent interface makes sense.                                  */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_MM_Axis                                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A simple structure used to model a given axis in design space for  */\r\n  /*    Multiple Masters fonts.                                            */\r\n  /*                                                                       */\r\n  /*    This structure can't be used for GX var fonts.                     */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    name    :: The axis's name.                                        */\r\n  /*                                                                       */\r\n  /*    minimum :: The axis's minimum design coordinate.                   */\r\n  /*                                                                       */\r\n  /*    maximum :: The axis's maximum design coordinate.                   */\r\n  /*                                                                       */\r\n  typedef struct  FT_MM_Axis_\r\n  {\r\n    FT_String*  name;\r\n    FT_Long     minimum;\r\n    FT_Long     maximum;\r\n\r\n  } FT_MM_Axis;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Multi_Master                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to model the axes and space of a Multiple Masters */\r\n  /*    font.                                                              */\r\n  /*                                                                       */\r\n  /*    This structure can't be used for GX var fonts.                     */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    num_axis    :: Number of axes.  Cannot exceed~4.                   */\r\n  /*                                                                       */\r\n  /*    num_designs :: Number of designs; should be normally 2^num_axis    */\r\n  /*                   even though the Type~1 specification strangely      */\r\n  /*                   allows for intermediate designs to be present. This */\r\n  /*                   number cannot exceed~16.                            */\r\n  /*                                                                       */\r\n  /*    axis        :: A table of axis descriptors.                        */\r\n  /*                                                                       */\r\n  typedef struct  FT_Multi_Master_\r\n  {\r\n    FT_UInt     num_axis;\r\n    FT_UInt     num_designs;\r\n    FT_MM_Axis  axis[T1_MAX_MM_AXIS];\r\n\r\n  } FT_Multi_Master;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Var_Axis                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A simple structure used to model a given axis in design space for  */\r\n  /*    Multiple Masters and GX var fonts.                                 */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    name    :: The axis's name.                                        */\r\n  /*               Not always meaningful for GX.                           */\r\n  /*                                                                       */\r\n  /*    minimum :: The axis's minimum design coordinate.                   */\r\n  /*                                                                       */\r\n  /*    def     :: The axis's default design coordinate.                   */\r\n  /*               FreeType computes meaningful default values for MM; it  */\r\n  /*               is then an integer value, not in 16.16 format.          */\r\n  /*                                                                       */\r\n  /*    maximum :: The axis's maximum design coordinate.                   */\r\n  /*                                                                       */\r\n  /*    tag     :: The axis's tag (the GX equivalent to `name').           */\r\n  /*               FreeType provides default values for MM if possible.    */\r\n  /*                                                                       */\r\n  /*    strid   :: The entry in `name' table (another GX version of        */\r\n  /*               `name').                                                */\r\n  /*               Not meaningful for MM.                                  */\r\n  /*                                                                       */\r\n  typedef struct  FT_Var_Axis_\r\n  {\r\n    FT_String*  name;\r\n\r\n    FT_Fixed    minimum;\r\n    FT_Fixed    def;\r\n    FT_Fixed    maximum;\r\n\r\n    FT_ULong    tag;\r\n    FT_UInt     strid;\r\n\r\n  } FT_Var_Axis;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Var_Named_Style                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A simple structure used to model a named style in a GX var font.   */\r\n  /*                                                                       */\r\n  /*    This structure can't be used for MM fonts.                         */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    coords :: The design coordinates for this style.                   */\r\n  /*              This is an array with one entry for each axis.           */\r\n  /*                                                                       */\r\n  /*    strid  :: The entry in `name' table identifying this style.        */\r\n  /*                                                                       */\r\n  typedef struct  FT_Var_Named_Style_\r\n  {\r\n    FT_Fixed*  coords;\r\n    FT_UInt    strid;\r\n\r\n  } FT_Var_Named_Style;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_MM_Var                                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to model the axes and space of a Multiple Masters */\r\n  /*    or GX var distortable font.                                        */\r\n  /*                                                                       */\r\n  /*    Some fields are specific to one format and not to the other.       */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    num_axis        :: The number of axes.  The maximum value is~4 for */\r\n  /*                       MM; no limit in GX.                             */\r\n  /*                                                                       */\r\n  /*    num_designs     :: The number of designs; should be normally       */\r\n  /*                       2^num_axis for MM fonts.  Not meaningful for GX */\r\n  /*                       (where every glyph could have a different       */\r\n  /*                       number of designs).                             */\r\n  /*                                                                       */\r\n  /*    num_namedstyles :: The number of named styles; only meaningful for */\r\n  /*                       GX which allows certain design coordinates to   */\r\n  /*                       have a string ID (in the `name' table)          */\r\n  /*                       associated with them.  The font can tell the    */\r\n  /*                       user that, for example, Weight=1.5 is `Bold'.   */\r\n  /*                                                                       */\r\n  /*    axis            :: A table of axis descriptors.                    */\r\n  /*                       GX fonts contain slightly more data than MM.    */\r\n  /*                                                                       */\r\n  /*    namedstyles     :: A table of named styles.                        */\r\n  /*                       Only meaningful with GX.                        */\r\n  /*                                                                       */\r\n  typedef struct  FT_MM_Var_\r\n  {\r\n    FT_UInt              num_axis;\r\n    FT_UInt              num_designs;\r\n    FT_UInt              num_namedstyles;\r\n    FT_Var_Axis*         axis;\r\n    FT_Var_Named_Style*  namedstyle;\r\n\r\n  } FT_MM_Var;\r\n\r\n\r\n  /* */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Get_Multi_Master                                                */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Retrieve the Multiple Master descriptor of a given font.           */\r\n  /*                                                                       */\r\n  /*    This function can't be used with GX fonts.                         */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face    :: A handle to the source face.                            */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    amaster :: The Multiple Masters descriptor.                        */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Get_Multi_Master( FT_Face           face,\r\n                       FT_Multi_Master  *amaster );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Get_MM_Var                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Retrieve the Multiple Master/GX var descriptor of a given font.    */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face    :: A handle to the source face.                            */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    amaster :: The Multiple Masters/GX var descriptor.                 */\r\n  /*               Allocates a data structure, which the user must free    */\r\n  /*               (a single call to FT_FREE will do it).                  */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Get_MM_Var( FT_Face      face,\r\n                 FT_MM_Var*  *amaster );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Set_MM_Design_Coordinates                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    For Multiple Masters fonts, choose an interpolated font design     */\r\n  /*    through design coordinates.                                        */\r\n  /*                                                                       */\r\n  /*    This function can't be used with GX fonts.                         */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    face       :: A handle to the source face.                         */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    num_coords :: The number of design coordinates (must be equal to   */\r\n  /*                  the number of axes in the font).                     */\r\n  /*                                                                       */\r\n  /*    coords     :: An array of design coordinates.                      */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Set_MM_Design_Coordinates( FT_Face   face,\r\n                                FT_UInt   num_coords,\r\n                                FT_Long*  coords );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Set_Var_Design_Coordinates                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    For Multiple Master or GX Var fonts, choose an interpolated font   */\r\n  /*    design through design coordinates.                                 */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    face       :: A handle to the source face.                         */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    num_coords :: The number of design coordinates (must be equal to   */\r\n  /*                  the number of axes in the font).                     */\r\n  /*                                                                       */\r\n  /*    coords     :: An array of design coordinates.                      */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Set_Var_Design_Coordinates( FT_Face    face,\r\n                                 FT_UInt    num_coords,\r\n                                 FT_Fixed*  coords );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Set_MM_Blend_Coordinates                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    For Multiple Masters and GX var fonts, choose an interpolated font */\r\n  /*    design through normalized blend coordinates.                       */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    face       :: A handle to the source face.                         */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    num_coords :: The number of design coordinates (must be equal to   */\r\n  /*                  the number of axes in the font).                     */\r\n  /*                                                                       */\r\n  /*    coords     :: The design coordinates array (each element must be   */\r\n  /*                  between 0 and 1.0).                                  */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Set_MM_Blend_Coordinates( FT_Face    face,\r\n                               FT_UInt    num_coords,\r\n                               FT_Fixed*  coords );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Set_Var_Blend_Coordinates                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This is another name of @FT_Set_MM_Blend_Coordinates.              */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Set_Var_Blend_Coordinates( FT_Face    face,\r\n                                FT_UInt    num_coords,\r\n                                FT_Fixed*  coords );\r\n\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTMM_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftmodapi.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftmodapi.h                                                             */\r\n/*                                                                         */\r\n/*    FreeType modules public interface (specification).                   */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2002, 2003, 2006, 2008, 2009, 2010 by             */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTMODAPI_H__\r\n#define __FTMODAPI_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    module_management                                                  */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    Module Management                                                  */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    How to add, upgrade, and remove modules from FreeType.             */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    The definitions below are used to manage modules within FreeType.  */\r\n  /*    Modules can be added, upgraded, and removed at runtime.            */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /* module bit flags */\r\n#define FT_MODULE_FONT_DRIVER         1  /* this module is a font driver  */\r\n#define FT_MODULE_RENDERER            2  /* this module is a renderer     */\r\n#define FT_MODULE_HINTER              4  /* this module is a glyph hinter */\r\n#define FT_MODULE_STYLER              8  /* this module is a styler       */\r\n\r\n#define FT_MODULE_DRIVER_SCALABLE     0x100   /* the driver supports      */\r\n                                              /* scalable fonts           */\r\n#define FT_MODULE_DRIVER_NO_OUTLINES  0x200   /* the driver does not      */\r\n                                              /* support vector outlines  */\r\n#define FT_MODULE_DRIVER_HAS_HINTER   0x400   /* the driver provides its  */\r\n                                              /* own hinter               */\r\n\r\n\r\n  /* deprecated values */\r\n#define ft_module_font_driver         FT_MODULE_FONT_DRIVER\r\n#define ft_module_renderer            FT_MODULE_RENDERER\r\n#define ft_module_hinter              FT_MODULE_HINTER\r\n#define ft_module_styler              FT_MODULE_STYLER\r\n\r\n#define ft_module_driver_scalable     FT_MODULE_DRIVER_SCALABLE\r\n#define ft_module_driver_no_outlines  FT_MODULE_DRIVER_NO_OUTLINES\r\n#define ft_module_driver_has_hinter   FT_MODULE_DRIVER_HAS_HINTER\r\n\r\n\r\n  typedef FT_Pointer  FT_Module_Interface;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_Module_Constructor                                              */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A function used to initialize (not create) a new module object.    */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    module :: The module to initialize.                                */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*FT_Module_Constructor)( FT_Module  module );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_Module_Destructor                                               */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A function used to finalize (not destroy) a given module object.   */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    module :: The module to finalize.                                  */\r\n  /*                                                                       */\r\n  typedef void\r\n  (*FT_Module_Destructor)( FT_Module  module );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_Module_Requester                                                */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A function used to query a given module for a specific interface.  */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    module :: The module to finalize.                                  */\r\n  /*                                                                       */\r\n  /*    name ::   The name of the interface in the module.                 */\r\n  /*                                                                       */\r\n  typedef FT_Module_Interface\r\n  (*FT_Module_Requester)( FT_Module    module,\r\n                          const char*  name );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Module_Class                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    The module class descriptor.                                       */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    module_flags    :: Bit flags describing the module.                */\r\n  /*                                                                       */\r\n  /*    module_size     :: The size of one module object/instance in       */\r\n  /*                       bytes.                                          */\r\n  /*                                                                       */\r\n  /*    module_name     :: The name of the module.                         */\r\n  /*                                                                       */\r\n  /*    module_version  :: The version, as a 16.16 fixed number            */\r\n  /*                       (major.minor).                                  */\r\n  /*                                                                       */\r\n  /*    module_requires :: The version of FreeType this module requires,   */\r\n  /*                       as a 16.16 fixed number (major.minor).  Starts  */\r\n  /*                       at version 2.0, i.e., 0x20000.                  */\r\n  /*                                                                       */\r\n  /*    module_init     :: The initializing function.                      */\r\n  /*                                                                       */\r\n  /*    module_done     :: The finalizing function.                        */\r\n  /*                                                                       */\r\n  /*    get_interface   :: The interface requesting function.              */\r\n  /*                                                                       */\r\n  typedef struct  FT_Module_Class_\r\n  {\r\n    FT_ULong               module_flags;\r\n    FT_Long                module_size;\r\n    const FT_String*       module_name;\r\n    FT_Fixed               module_version;\r\n    FT_Fixed               module_requires;\r\n\r\n    const void*            module_interface;\r\n\r\n    FT_Module_Constructor  module_init;\r\n    FT_Module_Destructor   module_done;\r\n    FT_Module_Requester    get_interface;\r\n\r\n  } FT_Module_Class;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Add_Module                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Add a new module to a given library instance.                      */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    library :: A handle to the library object.                         */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    clazz   :: A pointer to class descriptor for the module.           */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    An error will be returned if a module already exists by that name, */\r\n  /*    or if the module requires a version of FreeType that is too great. */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Add_Module( FT_Library              library,\r\n                 const FT_Module_Class*  clazz );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Get_Module                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Find a module by its name.                                         */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    library     :: A handle to the library object.                     */\r\n  /*                                                                       */\r\n  /*    module_name :: The module's name (as an ASCII string).             */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    A module handle.  0~if none was found.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    FreeType's internal modules aren't documented very well, and you   */\r\n  /*    should look up the source code for details.                        */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Module )\r\n  FT_Get_Module( FT_Library   library,\r\n                 const char*  module_name );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Remove_Module                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Remove a given module from a library instance.                     */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    library :: A handle to a library object.                           */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    module  :: A handle to a module object.                            */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The module object is destroyed by the function in case of success. */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Remove_Module( FT_Library  library,\r\n                    FT_Module   module );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Reference_Library                                               */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A counter gets initialized to~1 at the time an @FT_Library         */\r\n  /*    structure is created.  This function increments the counter.       */\r\n  /*    @FT_Done_Library then only destroys a library if the counter is~1, */\r\n  /*    otherwise it simply decrements the counter.                        */\r\n  /*                                                                       */\r\n  /*    This function helps in managing life-cycles of structures which    */\r\n  /*    reference @FT_Library objects.                                     */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    library :: A handle to a target library object.                    */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Since>                                                               */\r\n  /*    2.4.2                                                              */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Reference_Library( FT_Library  library );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_New_Library                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This function is used to create a new FreeType library instance    */\r\n  /*    from a given memory object.  It is thus possible to use libraries  */\r\n  /*    with distinct memory allocators within the same program.           */\r\n  /*                                                                       */\r\n  /*    Normally, you would call this function (followed by a call to      */\r\n  /*    @FT_Add_Default_Modules or a series of calls to @FT_Add_Module)    */\r\n  /*    instead of @FT_Init_FreeType to initialize the FreeType library.   */\r\n  /*                                                                       */\r\n  /*    Don't use @FT_Done_FreeType but @FT_Done_Library to destroy a      */\r\n  /*    library instance.                                                  */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    memory   :: A handle to the original memory object.                */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    alibrary :: A pointer to handle of a new library object.           */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    See the discussion of reference counters in the description of     */\r\n  /*    @FT_Reference_Library.                                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_New_Library( FT_Memory    memory,\r\n                  FT_Library  *alibrary );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Done_Library                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Discard a given library object.  This closes all drivers and       */\r\n  /*    discards all resource objects.                                     */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    library :: A handle to the target library.                         */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    See the discussion of reference counters in the description of     */\r\n  /*    @FT_Reference_Library.                                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Done_Library( FT_Library  library );\r\n\r\n/* */\r\n\r\n  typedef void\r\n  (*FT_DebugHook_Func)( void*  arg );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Set_Debug_Hook                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Set a debug hook function for debugging the interpreter of a font  */\r\n  /*    format.                                                            */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    library    :: A handle to the library object.                      */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    hook_index :: The index of the debug hook.  You should use the     */\r\n  /*                  values defined in `ftobjs.h', e.g.,                  */\r\n  /*                  `FT_DEBUG_HOOK_TRUETYPE'.                            */\r\n  /*                                                                       */\r\n  /*    debug_hook :: The function used to debug the interpreter.          */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    Currently, four debug hook slots are available, but only two (for  */\r\n  /*    the TrueType and the Type~1 interpreter) are defined.              */\r\n  /*                                                                       */\r\n  /*    Since the internal headers of FreeType are no longer installed,    */\r\n  /*    the symbol `FT_DEBUG_HOOK_TRUETYPE' isn't available publicly.      */\r\n  /*    This is a bug and will be fixed in a forthcoming release.          */\r\n  /*                                                                       */\r\n  FT_EXPORT( void )\r\n  FT_Set_Debug_Hook( FT_Library         library,\r\n                     FT_UInt            hook_index,\r\n                     FT_DebugHook_Func  debug_hook );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Add_Default_Modules                                             */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Add the set of default drivers to a given library object.          */\r\n  /*    This is only useful when you create a library object with          */\r\n  /*    @FT_New_Library (usually to plug a custom memory manager).         */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    library :: A handle to a new library object.                       */\r\n  /*                                                                       */\r\n  FT_EXPORT( void )\r\n  FT_Add_Default_Modules( FT_Library  library );\r\n\r\n\r\n\r\n  /**************************************************************************\r\n   *\r\n   * @section:\r\n   *   truetype_engine\r\n   *\r\n   * @title:\r\n   *   The TrueType Engine\r\n   *\r\n   * @abstract:\r\n   *   TrueType bytecode support.\r\n   *\r\n   * @description:\r\n   *   This section contains a function used to query the level of TrueType\r\n   *   bytecode support compiled in this version of the library.\r\n   *\r\n   */\r\n\r\n\r\n  /**************************************************************************\r\n   *\r\n   *  @enum:\r\n   *     FT_TrueTypeEngineType\r\n   *\r\n   *  @description:\r\n   *     A list of values describing which kind of TrueType bytecode\r\n   *     engine is implemented in a given FT_Library instance.  It is used\r\n   *     by the @FT_Get_TrueType_Engine_Type function.\r\n   *\r\n   *  @values:\r\n   *     FT_TRUETYPE_ENGINE_TYPE_NONE ::\r\n   *       The library doesn't implement any kind of bytecode interpreter.\r\n   *\r\n   *     FT_TRUETYPE_ENGINE_TYPE_UNPATENTED ::\r\n   *       The library implements a bytecode interpreter that doesn't\r\n   *       support the patented operations of the TrueType virtual machine.\r\n   *\r\n   *       Its main use is to load certain Asian fonts which position and\r\n   *       scale glyph components with bytecode instructions.  It produces\r\n   *       bad output for most other fonts.\r\n   *\r\n   *    FT_TRUETYPE_ENGINE_TYPE_PATENTED ::\r\n   *       The library implements a bytecode interpreter that covers\r\n   *       the full instruction set of the TrueType virtual machine (this\r\n   *       was governed by patents until May 2010, hence the name).\r\n   *\r\n   *  @since:\r\n   *       2.2\r\n   *\r\n   */\r\n  typedef enum  FT_TrueTypeEngineType_\r\n  {\r\n    FT_TRUETYPE_ENGINE_TYPE_NONE = 0,\r\n    FT_TRUETYPE_ENGINE_TYPE_UNPATENTED,\r\n    FT_TRUETYPE_ENGINE_TYPE_PATENTED\r\n\r\n  } FT_TrueTypeEngineType;\r\n\r\n\r\n  /**************************************************************************\r\n   *\r\n   *  @func:\r\n   *     FT_Get_TrueType_Engine_Type\r\n   *\r\n   *  @description:\r\n   *     Return an @FT_TrueTypeEngineType value to indicate which level of\r\n   *     the TrueType virtual machine a given library instance supports.\r\n   *\r\n   *  @input:\r\n   *     library ::\r\n   *       A library instance.\r\n   *\r\n   *  @return:\r\n   *     A value indicating which level is supported.\r\n   *\r\n   *  @since:\r\n   *     2.2\r\n   *\r\n   */\r\n  FT_EXPORT( FT_TrueTypeEngineType )\r\n  FT_Get_TrueType_Engine_Type( FT_Library  library );\r\n\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTMODAPI_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftmoderr.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftmoderr.h                                                             */\r\n/*                                                                         */\r\n/*    FreeType module error offsets (specification).                       */\r\n/*                                                                         */\r\n/*  Copyright 2001, 2002, 2003, 2004, 2005, 2010 by                        */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* This file is used to define the FreeType module error offsets.        */\r\n  /*                                                                       */\r\n  /* The lower byte gives the error code, the higher byte gives the        */\r\n  /* module.  The base module has error offset 0.  For example, the error  */\r\n  /* `FT_Err_Invalid_File_Format' has value 0x003, the error               */\r\n  /* `TT_Err_Invalid_File_Format' has value 0x1103, the error              */\r\n  /* `T1_Err_Invalid_File_Format' has value 0x1203, etc.                   */\r\n  /*                                                                       */\r\n  /* Undefine the macro FT_CONFIG_OPTION_USE_MODULE_ERRORS in ftoption.h   */\r\n  /* to make the higher byte always zero (disabling the module error       */\r\n  /* mechanism).                                                           */\r\n  /*                                                                       */\r\n  /* It can also be used to create a module error message table easily     */\r\n  /* with something like                                                   */\r\n  /*                                                                       */\r\n  /*   {                                                                   */\r\n  /*     #undef __FTMODERR_H__                                             */\r\n  /*     #define FT_MODERRDEF( e, v, s )  { FT_Mod_Err_ ## e, s },         */\r\n  /*     #define FT_MODERR_START_LIST     {                                */\r\n  /*     #define FT_MODERR_END_LIST       { 0, 0 } };                      */\r\n  /*                                                                       */\r\n  /*     const struct                                                      */\r\n  /*     {                                                                 */\r\n  /*       int          mod_err_offset;                                    */\r\n  /*       const char*  mod_err_msg                                        */\r\n  /*     } ft_mod_errors[] =                                               */\r\n  /*                                                                       */\r\n  /*     #include FT_MODULE_ERRORS_H                                       */\r\n  /*   }                                                                   */\r\n  /*                                                                       */\r\n  /* To use such a table, all errors must be ANDed with 0xFF00 to remove   */\r\n  /* the error code.                                                       */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n#ifndef __FTMODERR_H__\r\n#define __FTMODERR_H__\r\n\r\n\r\n  /*******************************************************************/\r\n  /*******************************************************************/\r\n  /*****                                                         *****/\r\n  /*****                       SETUP MACROS                      *****/\r\n  /*****                                                         *****/\r\n  /*******************************************************************/\r\n  /*******************************************************************/\r\n\r\n\r\n#undef  FT_NEED_EXTERN_C\r\n\r\n#ifndef FT_MODERRDEF\r\n\r\n#ifdef FT_CONFIG_OPTION_USE_MODULE_ERRORS\r\n#define FT_MODERRDEF( e, v, s )  FT_Mod_Err_ ## e = v,\r\n#else\r\n#define FT_MODERRDEF( e, v, s )  FT_Mod_Err_ ## e = 0,\r\n#endif\r\n\r\n#define FT_MODERR_START_LIST  enum {\r\n#define FT_MODERR_END_LIST    FT_Mod_Err_Max };\r\n\r\n#ifdef __cplusplus\r\n#define FT_NEED_EXTERN_C\r\n  extern \"C\" {\r\n#endif\r\n\r\n#endif /* !FT_MODERRDEF */\r\n\r\n\r\n  /*******************************************************************/\r\n  /*******************************************************************/\r\n  /*****                                                         *****/\r\n  /*****               LIST MODULE ERROR BASES                   *****/\r\n  /*****                                                         *****/\r\n  /*******************************************************************/\r\n  /*******************************************************************/\r\n\r\n\r\n#ifdef FT_MODERR_START_LIST\r\n  FT_MODERR_START_LIST\r\n#endif\r\n\r\n\r\n  FT_MODERRDEF( Base,      0x000, \"base module\" )\r\n  FT_MODERRDEF( Autofit,   0x100, \"autofitter module\" )\r\n  FT_MODERRDEF( BDF,       0x200, \"BDF module\" )\r\n  FT_MODERRDEF( Bzip2,     0x300, \"Bzip2 module\" )\r\n  FT_MODERRDEF( Cache,     0x400, \"cache module\" )\r\n  FT_MODERRDEF( CFF,       0x500, \"CFF module\" )\r\n  FT_MODERRDEF( CID,       0x600, \"CID module\" )\r\n  FT_MODERRDEF( Gzip,      0x700, \"Gzip module\" )\r\n  FT_MODERRDEF( LZW,       0x800, \"LZW module\" )\r\n  FT_MODERRDEF( OTvalid,   0x900, \"OpenType validation module\" )\r\n  FT_MODERRDEF( PCF,       0xA00, \"PCF module\" )\r\n  FT_MODERRDEF( PFR,       0xB00, \"PFR module\" )\r\n  FT_MODERRDEF( PSaux,     0xC00, \"PS auxiliary module\" )\r\n  FT_MODERRDEF( PShinter,  0xD00, \"PS hinter module\" )\r\n  FT_MODERRDEF( PSnames,   0xE00, \"PS names module\" )\r\n  FT_MODERRDEF( Raster,    0xF00, \"raster module\" )\r\n  FT_MODERRDEF( SFNT,     0x1000, \"SFNT module\" )\r\n  FT_MODERRDEF( Smooth,   0x1100, \"smooth raster module\" )\r\n  FT_MODERRDEF( TrueType, 0x1200, \"TrueType module\" )\r\n  FT_MODERRDEF( Type1,    0x1300, \"Type 1 module\" )\r\n  FT_MODERRDEF( Type42,   0x1400, \"Type 42 module\" )\r\n  FT_MODERRDEF( Winfonts, 0x1500, \"Windows FON/FNT module\" )\r\n\r\n\r\n#ifdef FT_MODERR_END_LIST\r\n  FT_MODERR_END_LIST\r\n#endif\r\n\r\n\r\n  /*******************************************************************/\r\n  /*******************************************************************/\r\n  /*****                                                         *****/\r\n  /*****                      CLEANUP                            *****/\r\n  /*****                                                         *****/\r\n  /*******************************************************************/\r\n  /*******************************************************************/\r\n\r\n\r\n#ifdef FT_NEED_EXTERN_C\r\n  }\r\n#endif\r\n\r\n#undef FT_MODERR_START_LIST\r\n#undef FT_MODERR_END_LIST\r\n#undef FT_MODERRDEF\r\n#undef FT_NEED_EXTERN_C\r\n\r\n\r\n#endif /* __FTMODERR_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftotval.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftotval.h                                                              */\r\n/*                                                                         */\r\n/*    FreeType API for validating OpenType tables (specification).         */\r\n/*                                                                         */\r\n/*  Copyright 2004, 2005, 2006, 2007 by                                    */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n/***************************************************************************/\r\n/*                                                                         */\r\n/*                                                                         */\r\n/* Warning: This module might be moved to a different library in the       */\r\n/*          future to avoid a tight dependency between FreeType and the    */\r\n/*          OpenType specification.                                        */\r\n/*                                                                         */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTOTVAL_H__\r\n#define __FTOTVAL_H__\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    ot_validation                                                      */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    OpenType Validation                                                */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    An API to validate OpenType tables.                                */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This section contains the declaration of functions to validate     */\r\n  /*    some OpenType tables (BASE, GDEF, GPOS, GSUB, JSTF, MATH).         */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n /**********************************************************************\r\n  *\r\n  * @enum:\r\n  *    FT_VALIDATE_OTXXX\r\n  *\r\n  * @description:\r\n  *    A list of bit-field constants used with @FT_OpenType_Validate to\r\n  *    indicate which OpenType tables should be validated.\r\n  *\r\n  * @values:\r\n  *    FT_VALIDATE_BASE ::\r\n  *      Validate BASE table.\r\n  *\r\n  *    FT_VALIDATE_GDEF ::\r\n  *      Validate GDEF table.\r\n  *\r\n  *    FT_VALIDATE_GPOS ::\r\n  *      Validate GPOS table.\r\n  *\r\n  *    FT_VALIDATE_GSUB ::\r\n  *      Validate GSUB table.\r\n  *\r\n  *    FT_VALIDATE_JSTF ::\r\n  *      Validate JSTF table.\r\n  *\r\n  *    FT_VALIDATE_MATH ::\r\n  *      Validate MATH table.\r\n  *\r\n  *    FT_VALIDATE_OT ::\r\n  *      Validate all OpenType tables (BASE, GDEF, GPOS, GSUB, JSTF, MATH).\r\n  *\r\n  */\r\n#define FT_VALIDATE_BASE  0x0100\r\n#define FT_VALIDATE_GDEF  0x0200\r\n#define FT_VALIDATE_GPOS  0x0400\r\n#define FT_VALIDATE_GSUB  0x0800\r\n#define FT_VALIDATE_JSTF  0x1000\r\n#define FT_VALIDATE_MATH  0x2000\r\n\r\n#define FT_VALIDATE_OT  FT_VALIDATE_BASE | \\\r\n                        FT_VALIDATE_GDEF | \\\r\n                        FT_VALIDATE_GPOS | \\\r\n                        FT_VALIDATE_GSUB | \\\r\n                        FT_VALIDATE_JSTF | \\\r\n                        FT_VALIDATE_MATH\r\n\r\n  /* */\r\n\r\n /**********************************************************************\r\n  *\r\n  * @function:\r\n  *    FT_OpenType_Validate\r\n  *\r\n  * @description:\r\n  *    Validate various OpenType tables to assure that all offsets and\r\n  *    indices are valid.  The idea is that a higher-level library which\r\n  *    actually does the text layout can access those tables without\r\n  *    error checking (which can be quite time consuming).\r\n  *\r\n  * @input:\r\n  *    face ::\r\n  *       A handle to the input face.\r\n  *\r\n  *    validation_flags ::\r\n  *       A bit field which specifies the tables to be validated.  See\r\n  *       @FT_VALIDATE_OTXXX for possible values.\r\n  *\r\n  * @output:\r\n  *    BASE_table ::\r\n  *       A pointer to the BASE table.\r\n  *\r\n  *    GDEF_table ::\r\n  *       A pointer to the GDEF table.\r\n  *\r\n  *    GPOS_table ::\r\n  *       A pointer to the GPOS table.\r\n  *\r\n  *    GSUB_table ::\r\n  *       A pointer to the GSUB table.\r\n  *\r\n  *    JSTF_table ::\r\n  *       A pointer to the JSTF table.\r\n  *\r\n  * @return:\r\n  *   FreeType error code.  0~means success.\r\n  *\r\n  * @note:\r\n  *   This function only works with OpenType fonts, returning an error\r\n  *   otherwise.\r\n  *\r\n  *   After use, the application should deallocate the five tables with\r\n  *   @FT_OpenType_Free.  A NULL value indicates that the table either\r\n  *   doesn't exist in the font, or the application hasn't asked for\r\n  *   validation.\r\n  */\r\n  FT_EXPORT( FT_Error )\r\n  FT_OpenType_Validate( FT_Face    face,\r\n                        FT_UInt    validation_flags,\r\n                        FT_Bytes  *BASE_table,\r\n                        FT_Bytes  *GDEF_table,\r\n                        FT_Bytes  *GPOS_table,\r\n                        FT_Bytes  *GSUB_table,\r\n                        FT_Bytes  *JSTF_table );\r\n\r\n  /* */\r\n\r\n /**********************************************************************\r\n  *\r\n  * @function:\r\n  *    FT_OpenType_Free\r\n  *\r\n  * @description:\r\n  *    Free the buffer allocated by OpenType validator.\r\n  *\r\n  * @input:\r\n  *    face ::\r\n  *       A handle to the input face.\r\n  *\r\n  *    table ::\r\n  *       The pointer to the buffer that is allocated by\r\n  *       @FT_OpenType_Validate.\r\n  *\r\n  * @note:\r\n  *   This function must be used to free the buffer allocated by\r\n  *   @FT_OpenType_Validate only.\r\n  */\r\n  FT_EXPORT( void )\r\n  FT_OpenType_Free( FT_Face   face,\r\n                    FT_Bytes  table );\r\n\r\n\r\n /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTOTVAL_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftoutln.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftoutln.h                                                              */\r\n/*                                                                         */\r\n/*    Support for the FT_Outline type used to store glyph shapes of        */\r\n/*    most scalable font formats (specification).                          */\r\n/*                                                                         */\r\n/*  Copyright 1996-2003, 2005-2011 by                                      */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTOUTLN_H__\r\n#define __FTOUTLN_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    outline_processing                                                 */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    Outline Processing                                                 */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    Functions to create, transform, and render vectorial glyph images. */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This section contains routines used to create and destroy scalable */\r\n  /*    glyph images known as `outlines'.  These can also be measured,     */\r\n  /*    transformed, and converted into bitmaps and pixmaps.               */\r\n  /*                                                                       */\r\n  /* <Order>                                                               */\r\n  /*    FT_Outline                                                         */\r\n  /*    FT_OUTLINE_FLAGS                                                   */\r\n  /*    FT_Outline_New                                                     */\r\n  /*    FT_Outline_Done                                                    */\r\n  /*    FT_Outline_Copy                                                    */\r\n  /*    FT_Outline_Translate                                               */\r\n  /*    FT_Outline_Transform                                               */\r\n  /*    FT_Outline_Embolden                                                */\r\n  /*    FT_Outline_Reverse                                                 */\r\n  /*    FT_Outline_Check                                                   */\r\n  /*                                                                       */\r\n  /*    FT_Outline_Get_CBox                                                */\r\n  /*    FT_Outline_Get_BBox                                                */\r\n  /*                                                                       */\r\n  /*    FT_Outline_Get_Bitmap                                              */\r\n  /*    FT_Outline_Render                                                  */\r\n  /*                                                                       */\r\n  /*    FT_Outline_Decompose                                               */\r\n  /*    FT_Outline_Funcs                                                   */\r\n  /*    FT_Outline_MoveTo_Func                                             */\r\n  /*    FT_Outline_LineTo_Func                                             */\r\n  /*    FT_Outline_ConicTo_Func                                            */\r\n  /*    FT_Outline_CubicTo_Func                                            */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Outline_Decompose                                               */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Walk over an outline's structure to decompose it into individual   */\r\n  /*    segments and Bézier arcs.  This function also emits `move to'      */\r\n  /*    operations to indicate the start of new contours in the outline.   */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    outline        :: A pointer to the source target.                  */\r\n  /*                                                                       */\r\n  /*    func_interface :: A table of `emitters', i.e., function pointers   */\r\n  /*                      called during decomposition to indicate path     */\r\n  /*                      operations.                                      */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    user           :: A typeless pointer which is passed to each       */\r\n  /*                      emitter during the decomposition.  It can be     */\r\n  /*                      used to store the state during the               */\r\n  /*                      decomposition.                                   */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Outline_Decompose( FT_Outline*              outline,\r\n                        const FT_Outline_Funcs*  func_interface,\r\n                        void*                    user );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Outline_New                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Create a new outline of a given size.                              */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    library     :: A handle to the library object from where the       */\r\n  /*                   outline is allocated.  Note however that the new    */\r\n  /*                   outline will *not* necessarily be *freed*, when     */\r\n  /*                   destroying the library, by @FT_Done_FreeType.       */\r\n  /*                                                                       */\r\n  /*    numPoints   :: The maximal number of points within the outline.    */\r\n  /*                                                                       */\r\n  /*    numContours :: The maximal number of contours within the outline.  */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    anoutline   :: A handle to the new outline.                        */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The reason why this function takes a `library' parameter is simply */\r\n  /*    to use the library's memory allocator.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Outline_New( FT_Library   library,\r\n                  FT_UInt      numPoints,\r\n                  FT_Int       numContours,\r\n                  FT_Outline  *anoutline );\r\n\r\n\r\n  FT_EXPORT( FT_Error )\r\n  FT_Outline_New_Internal( FT_Memory    memory,\r\n                           FT_UInt      numPoints,\r\n                           FT_Int       numContours,\r\n                           FT_Outline  *anoutline );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Outline_Done                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Destroy an outline created with @FT_Outline_New.                   */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    library :: A handle of the library object used to allocate the     */\r\n  /*               outline.                                                */\r\n  /*                                                                       */\r\n  /*    outline :: A pointer to the outline object to be discarded.        */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    If the outline's `owner' field is not set, only the outline        */\r\n  /*    descriptor will be released.                                       */\r\n  /*                                                                       */\r\n  /*    The reason why this function takes an `library' parameter is       */\r\n  /*    simply to use ft_mem_free().                                       */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Outline_Done( FT_Library   library,\r\n                   FT_Outline*  outline );\r\n\r\n\r\n  FT_EXPORT( FT_Error )\r\n  FT_Outline_Done_Internal( FT_Memory    memory,\r\n                            FT_Outline*  outline );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Outline_Check                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Check the contents of an outline descriptor.                       */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    outline :: A handle to a source outline.                           */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Outline_Check( FT_Outline*  outline );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Outline_Get_CBox                                                */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Return an outline's `control box'.  The control box encloses all   */\r\n  /*    the outline's points, including Bézier control points.  Though it  */\r\n  /*    coincides with the exact bounding box for most glyphs, it can be   */\r\n  /*    slightly larger in some situations (like when rotating an outline  */\r\n  /*    which contains Bézier outside arcs).                               */\r\n  /*                                                                       */\r\n  /*    Computing the control box is very fast, while getting the bounding */\r\n  /*    box can take much more time as it needs to walk over all segments  */\r\n  /*    and arcs in the outline.  To get the latter, you can use the       */\r\n  /*    `ftbbox' component which is dedicated to this single task.         */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    outline :: A pointer to the source outline descriptor.             */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    acbox   :: The outline's control box.                              */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    See @FT_Glyph_Get_CBox for a discussion of tricky fonts.           */\r\n  /*                                                                       */\r\n  FT_EXPORT( void )\r\n  FT_Outline_Get_CBox( const FT_Outline*  outline,\r\n                       FT_BBox           *acbox );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Outline_Translate                                               */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Apply a simple translation to the points of an outline.            */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    outline :: A pointer to the target outline descriptor.             */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    xOffset :: The horizontal offset.                                  */\r\n  /*                                                                       */\r\n  /*    yOffset :: The vertical offset.                                    */\r\n  /*                                                                       */\r\n  FT_EXPORT( void )\r\n  FT_Outline_Translate( const FT_Outline*  outline,\r\n                        FT_Pos             xOffset,\r\n                        FT_Pos             yOffset );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Outline_Copy                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Copy an outline into another one.  Both objects must have the      */\r\n  /*    same sizes (number of points & number of contours) when this       */\r\n  /*    function is called.                                                */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    source :: A handle to the source outline.                          */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    target :: A handle to the target outline.                          */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Outline_Copy( const FT_Outline*  source,\r\n                   FT_Outline        *target );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Outline_Transform                                               */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Apply a simple 2x2 matrix to all of an outline's points.  Useful   */\r\n  /*    for applying rotations, slanting, flipping, etc.                   */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    outline :: A pointer to the target outline descriptor.             */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    matrix  :: A pointer to the transformation matrix.                 */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    You can use @FT_Outline_Translate if you need to translate the     */\r\n  /*    outline's points.                                                  */\r\n  /*                                                                       */\r\n  FT_EXPORT( void )\r\n  FT_Outline_Transform( const FT_Outline*  outline,\r\n                        const FT_Matrix*   matrix );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Outline_Embolden                                                */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Embolden an outline.  The new outline will be at most 4~times      */\r\n  /*    `strength' pixels wider and higher.  You may think of the left and */\r\n  /*    bottom borders as unchanged.                                       */\r\n  /*                                                                       */\r\n  /*    Negative `strength' values to reduce the outline thickness are     */\r\n  /*    possible also.                                                     */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    outline  :: A handle to the target outline.                        */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    strength :: How strong the glyph is emboldened.  Expressed in      */\r\n  /*                26.6 pixel format.                                     */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The used algorithm to increase or decrease the thickness of the    */\r\n  /*    glyph doesn't change the number of points; this means that certain */\r\n  /*    situations like acute angles or intersections are sometimes        */\r\n  /*    handled incorrectly.                                               */\r\n  /*                                                                       */\r\n  /*    If you need `better' metrics values you should call                */\r\n  /*    @FT_Outline_Get_CBox or @FT_Outline_Get_BBox.                      */\r\n  /*                                                                       */\r\n  /*    Example call:                                                      */\r\n  /*                                                                       */\r\n  /*    {                                                                  */\r\n  /*      FT_Load_Glyph( face, index, FT_LOAD_DEFAULT );                   */\r\n  /*      if ( face->slot->format == FT_GLYPH_FORMAT_OUTLINE )             */\r\n  /*        FT_Outline_Embolden( &face->slot->outline, strength );         */\r\n  /*    }                                                                  */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Outline_Embolden( FT_Outline*  outline,\r\n                       FT_Pos       strength );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Outline_Reverse                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Reverse the drawing direction of an outline.  This is used to      */\r\n  /*    ensure consistent fill conventions for mirrored glyphs.            */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    outline :: A pointer to the target outline descriptor.             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    This function toggles the bit flag @FT_OUTLINE_REVERSE_FILL in     */\r\n  /*    the outline's `flags' field.                                       */\r\n  /*                                                                       */\r\n  /*    It shouldn't be used by a normal client application, unless it     */\r\n  /*    knows what it is doing.                                            */\r\n  /*                                                                       */\r\n  FT_EXPORT( void )\r\n  FT_Outline_Reverse( FT_Outline*  outline );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Outline_Get_Bitmap                                              */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Render an outline within a bitmap.  The outline's image is simply  */\r\n  /*    OR-ed to the target bitmap.                                        */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    library :: A handle to a FreeType library object.                  */\r\n  /*                                                                       */\r\n  /*    outline :: A pointer to the source outline descriptor.             */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    abitmap :: A pointer to the target bitmap descriptor.              */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    This function does NOT CREATE the bitmap, it only renders an       */\r\n  /*    outline image within the one you pass to it!  Consequently, the    */\r\n  /*    various fields in `abitmap' should be set accordingly.             */\r\n  /*                                                                       */\r\n  /*    It will use the raster corresponding to the default glyph format.  */\r\n  /*                                                                       */\r\n  /*    The value of the `num_grays' field in `abitmap' is ignored.  If    */\r\n  /*    you select the gray-level rasterizer, and you want less than 256   */\r\n  /*    gray levels, you have to use @FT_Outline_Render directly.          */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Outline_Get_Bitmap( FT_Library        library,\r\n                         FT_Outline*       outline,\r\n                         const FT_Bitmap  *abitmap );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Outline_Render                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Render an outline within a bitmap using the current scan-convert.  */\r\n  /*    This function uses an @FT_Raster_Params structure as an argument,  */\r\n  /*    allowing advanced features like direct composition, translucency,  */\r\n  /*    etc.                                                               */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    library :: A handle to a FreeType library object.                  */\r\n  /*                                                                       */\r\n  /*    outline :: A pointer to the source outline descriptor.             */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    params  :: A pointer to an @FT_Raster_Params structure used to     */\r\n  /*               describe the rendering operation.                       */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    You should know what you are doing and how @FT_Raster_Params works */\r\n  /*    to use this function.                                              */\r\n  /*                                                                       */\r\n  /*    The field `params.source' will be set to `outline' before the scan */\r\n  /*    converter is called, which means that the value you give to it is  */\r\n  /*    actually ignored.                                                  */\r\n  /*                                                                       */\r\n  /*    The gray-level rasterizer always uses 256 gray levels.  If you     */\r\n  /*    want less gray levels, you have to provide your own span callback. */\r\n  /*    See the @FT_RASTER_FLAG_DIRECT value of the `flags' field in the   */\r\n  /*    @FT_Raster_Params structure for more details.                      */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Outline_Render( FT_Library         library,\r\n                     FT_Outline*        outline,\r\n                     FT_Raster_Params*  params );\r\n\r\n\r\n /**************************************************************************\r\n  *\r\n  * @enum:\r\n  *   FT_Orientation\r\n  *\r\n  * @description:\r\n  *   A list of values used to describe an outline's contour orientation.\r\n  *\r\n  *   The TrueType and PostScript specifications use different conventions\r\n  *   to determine whether outline contours should be filled or unfilled.\r\n  *\r\n  * @values:\r\n  *   FT_ORIENTATION_TRUETYPE ::\r\n  *     According to the TrueType specification, clockwise contours must\r\n  *     be filled, and counter-clockwise ones must be unfilled.\r\n  *\r\n  *   FT_ORIENTATION_POSTSCRIPT ::\r\n  *     According to the PostScript specification, counter-clockwise contours\r\n  *     must be filled, and clockwise ones must be unfilled.\r\n  *\r\n  *   FT_ORIENTATION_FILL_RIGHT ::\r\n  *     This is identical to @FT_ORIENTATION_TRUETYPE, but is used to\r\n  *     remember that in TrueType, everything that is to the right of\r\n  *     the drawing direction of a contour must be filled.\r\n  *\r\n  *   FT_ORIENTATION_FILL_LEFT ::\r\n  *     This is identical to @FT_ORIENTATION_POSTSCRIPT, but is used to\r\n  *     remember that in PostScript, everything that is to the left of\r\n  *     the drawing direction of a contour must be filled.\r\n  *\r\n  *   FT_ORIENTATION_NONE ::\r\n  *     The orientation cannot be determined.  That is, different parts of\r\n  *     the glyph have different orientation.\r\n  *\r\n  */\r\n  typedef enum  FT_Orientation_\r\n  {\r\n    FT_ORIENTATION_TRUETYPE   = 0,\r\n    FT_ORIENTATION_POSTSCRIPT = 1,\r\n    FT_ORIENTATION_FILL_RIGHT = FT_ORIENTATION_TRUETYPE,\r\n    FT_ORIENTATION_FILL_LEFT  = FT_ORIENTATION_POSTSCRIPT,\r\n    FT_ORIENTATION_NONE\r\n\r\n  } FT_Orientation;\r\n\r\n\r\n /**************************************************************************\r\n  *\r\n  * @function:\r\n  *   FT_Outline_Get_Orientation\r\n  *\r\n  * @description:\r\n  *   This function analyzes a glyph outline and tries to compute its\r\n  *   fill orientation (see @FT_Orientation).  This is done by computing\r\n  *   the direction of each global horizontal and/or vertical extrema\r\n  *   within the outline.\r\n  *\r\n  *   Note that this will return @FT_ORIENTATION_TRUETYPE for empty\r\n  *   outlines.\r\n  *\r\n  * @input:\r\n  *   outline ::\r\n  *     A handle to the source outline.\r\n  *\r\n  * @return:\r\n  *   The orientation.\r\n  *\r\n  */\r\n  FT_EXPORT( FT_Orientation )\r\n  FT_Outline_Get_Orientation( FT_Outline*  outline );\r\n\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTOUTLN_H__ */\r\n\r\n\r\n/* END */\r\n\r\n\r\n/* Local Variables: */\r\n/* coding: utf-8    */\r\n/* End:             */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftpfr.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftpfr.h                                                                */\r\n/*                                                                         */\r\n/*    FreeType API for accessing PFR-specific data (specification only).   */\r\n/*                                                                         */\r\n/*  Copyright 2002, 2003, 2004, 2006, 2008, 2009 by                        */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTPFR_H__\r\n#define __FTPFR_H__\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    pfr_fonts                                                          */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    PFR Fonts                                                          */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    PFR/TrueDoc specific API.                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This section contains the declaration of PFR-specific functions.   */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n /**********************************************************************\r\n  *\r\n  * @function:\r\n  *    FT_Get_PFR_Metrics\r\n  *\r\n  * @description:\r\n  *    Return the outline and metrics resolutions of a given PFR face.\r\n  *\r\n  * @input:\r\n  *    face :: Handle to the input face.  It can be a non-PFR face.\r\n  *\r\n  * @output:\r\n  *    aoutline_resolution ::\r\n  *      Outline resolution.  This is equivalent to `face->units_per_EM'\r\n  *      for non-PFR fonts.  Optional (parameter can be NULL).\r\n  *\r\n  *    ametrics_resolution ::\r\n  *      Metrics resolution.  This is equivalent to `outline_resolution'\r\n  *      for non-PFR fonts.  Optional (parameter can be NULL).\r\n  *\r\n  *    ametrics_x_scale ::\r\n  *      A 16.16 fixed-point number used to scale distance expressed\r\n  *      in metrics units to device sub-pixels.  This is equivalent to\r\n  *      `face->size->x_scale', but for metrics only.  Optional (parameter\r\n  *      can be NULL).\r\n  *\r\n  *    ametrics_y_scale ::\r\n  *      Same as `ametrics_x_scale' but for the vertical direction.\r\n  *      optional (parameter can be NULL).\r\n  *\r\n  * @return:\r\n  *    FreeType error code.  0~means success.\r\n  *\r\n  * @note:\r\n  *   If the input face is not a PFR, this function will return an error.\r\n  *   However, in all cases, it will return valid values.\r\n  */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Get_PFR_Metrics( FT_Face    face,\r\n                      FT_UInt   *aoutline_resolution,\r\n                      FT_UInt   *ametrics_resolution,\r\n                      FT_Fixed  *ametrics_x_scale,\r\n                      FT_Fixed  *ametrics_y_scale );\r\n\r\n\r\n /**********************************************************************\r\n  *\r\n  * @function:\r\n  *    FT_Get_PFR_Kerning\r\n  *\r\n  * @description:\r\n  *    Return the kerning pair corresponding to two glyphs in a PFR face.\r\n  *    The distance is expressed in metrics units, unlike the result of\r\n  *    @FT_Get_Kerning.\r\n  *\r\n  * @input:\r\n  *    face  :: A handle to the input face.\r\n  *\r\n  *    left  :: Index of the left glyph.\r\n  *\r\n  *    right :: Index of the right glyph.\r\n  *\r\n  * @output:\r\n  *    avector :: A kerning vector.\r\n  *\r\n  * @return:\r\n  *    FreeType error code.  0~means success.\r\n  *\r\n  * @note:\r\n  *    This function always return distances in original PFR metrics\r\n  *    units.  This is unlike @FT_Get_Kerning with the @FT_KERNING_UNSCALED\r\n  *    mode, which always returns distances converted to outline units.\r\n  *\r\n  *    You can use the value of the `x_scale' and `y_scale' parameters\r\n  *    returned by @FT_Get_PFR_Metrics to scale these to device sub-pixels.\r\n  */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Get_PFR_Kerning( FT_Face     face,\r\n                      FT_UInt     left,\r\n                      FT_UInt     right,\r\n                      FT_Vector  *avector );\r\n\r\n\r\n /**********************************************************************\r\n  *\r\n  * @function:\r\n  *    FT_Get_PFR_Advance\r\n  *\r\n  * @description:\r\n  *    Return a given glyph advance, expressed in original metrics units,\r\n  *    from a PFR font.\r\n  *\r\n  * @input:\r\n  *    face   :: A handle to the input face.\r\n  *\r\n  *    gindex :: The glyph index.\r\n  *\r\n  * @output:\r\n  *    aadvance :: The glyph advance in metrics units.\r\n  *\r\n  * @return:\r\n  *    FreeType error code.  0~means success.\r\n  *\r\n  * @note:\r\n  *    You can use the `x_scale' or `y_scale' results of @FT_Get_PFR_Metrics\r\n  *    to convert the advance to device sub-pixels (i.e., 1/64th of pixels).\r\n  */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Get_PFR_Advance( FT_Face   face,\r\n                      FT_UInt   gindex,\r\n                      FT_Pos   *aadvance );\r\n\r\n /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTPFR_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftrender.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftrender.h                                                             */\r\n/*                                                                         */\r\n/*    FreeType renderer modules public interface (specification).          */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2005, 2006, 2010 by                               */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTRENDER_H__\r\n#define __FTRENDER_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_MODULE_H\r\n#include FT_GLYPH_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    module_management                                                  */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /* create a new glyph object */\r\n  typedef FT_Error\r\n  (*FT_Glyph_InitFunc)( FT_Glyph      glyph,\r\n                        FT_GlyphSlot  slot );\r\n\r\n  /* destroys a given glyph object */\r\n  typedef void\r\n  (*FT_Glyph_DoneFunc)( FT_Glyph  glyph );\r\n\r\n  typedef void\r\n  (*FT_Glyph_TransformFunc)( FT_Glyph          glyph,\r\n                             const FT_Matrix*  matrix,\r\n                             const FT_Vector*  delta );\r\n\r\n  typedef void\r\n  (*FT_Glyph_GetBBoxFunc)( FT_Glyph  glyph,\r\n                           FT_BBox*  abbox );\r\n\r\n  typedef FT_Error\r\n  (*FT_Glyph_CopyFunc)( FT_Glyph   source,\r\n                        FT_Glyph   target );\r\n\r\n  typedef FT_Error\r\n  (*FT_Glyph_PrepareFunc)( FT_Glyph      glyph,\r\n                           FT_GlyphSlot  slot );\r\n\r\n/* deprecated */\r\n#define FT_Glyph_Init_Func       FT_Glyph_InitFunc\r\n#define FT_Glyph_Done_Func       FT_Glyph_DoneFunc\r\n#define FT_Glyph_Transform_Func  FT_Glyph_TransformFunc\r\n#define FT_Glyph_BBox_Func       FT_Glyph_GetBBoxFunc\r\n#define FT_Glyph_Copy_Func       FT_Glyph_CopyFunc\r\n#define FT_Glyph_Prepare_Func    FT_Glyph_PrepareFunc\r\n\r\n\r\n  struct  FT_Glyph_Class_\r\n  {\r\n    FT_Long                 glyph_size;\r\n    FT_Glyph_Format         glyph_format;\r\n    FT_Glyph_InitFunc       glyph_init;\r\n    FT_Glyph_DoneFunc       glyph_done;\r\n    FT_Glyph_CopyFunc       glyph_copy;\r\n    FT_Glyph_TransformFunc  glyph_transform;\r\n    FT_Glyph_GetBBoxFunc    glyph_bbox;\r\n    FT_Glyph_PrepareFunc    glyph_prepare;\r\n  };\r\n\r\n\r\n  typedef FT_Error\r\n  (*FT_Renderer_RenderFunc)( FT_Renderer       renderer,\r\n                             FT_GlyphSlot      slot,\r\n                             FT_UInt           mode,\r\n                             const FT_Vector*  origin );\r\n\r\n  typedef FT_Error\r\n  (*FT_Renderer_TransformFunc)( FT_Renderer       renderer,\r\n                                FT_GlyphSlot      slot,\r\n                                const FT_Matrix*  matrix,\r\n                                const FT_Vector*  delta );\r\n\r\n\r\n  typedef void\r\n  (*FT_Renderer_GetCBoxFunc)( FT_Renderer   renderer,\r\n                              FT_GlyphSlot  slot,\r\n                              FT_BBox*      cbox );\r\n\r\n\r\n  typedef FT_Error\r\n  (*FT_Renderer_SetModeFunc)( FT_Renderer  renderer,\r\n                              FT_ULong     mode_tag,\r\n                              FT_Pointer   mode_ptr );\r\n\r\n/* deprecated identifiers */\r\n#define FTRenderer_render  FT_Renderer_RenderFunc\r\n#define FTRenderer_transform  FT_Renderer_TransformFunc\r\n#define FTRenderer_getCBox  FT_Renderer_GetCBoxFunc\r\n#define FTRenderer_setMode  FT_Renderer_SetModeFunc\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Renderer_Class                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    The renderer module class descriptor.                              */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    root            :: The root @FT_Module_Class fields.               */\r\n  /*                                                                       */\r\n  /*    glyph_format    :: The glyph image format this renderer handles.   */\r\n  /*                                                                       */\r\n  /*    render_glyph    :: A method used to render the image that is in a  */\r\n  /*                       given glyph slot into a bitmap.                 */\r\n  /*                                                                       */\r\n  /*    transform_glyph :: A method used to transform the image that is in */\r\n  /*                       a given glyph slot.                             */\r\n  /*                                                                       */\r\n  /*    get_glyph_cbox  :: A method used to access the glyph's cbox.       */\r\n  /*                                                                       */\r\n  /*    set_mode        :: A method used to pass additional parameters.    */\r\n  /*                                                                       */\r\n  /*    raster_class    :: For @FT_GLYPH_FORMAT_OUTLINE renderers only.    */\r\n  /*                       This is a pointer to its raster's class.        */\r\n  /*                                                                       */\r\n  typedef struct  FT_Renderer_Class_\r\n  {\r\n    FT_Module_Class            root;\r\n\r\n    FT_Glyph_Format            glyph_format;\r\n\r\n    FT_Renderer_RenderFunc     render_glyph;\r\n    FT_Renderer_TransformFunc  transform_glyph;\r\n    FT_Renderer_GetCBoxFunc    get_glyph_cbox;\r\n    FT_Renderer_SetModeFunc    set_mode;\r\n\r\n    FT_Raster_Funcs*           raster_class;\r\n\r\n  } FT_Renderer_Class;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Get_Renderer                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Retrieve the current renderer for a given glyph format.            */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    library :: A handle to the library object.                         */\r\n  /*                                                                       */\r\n  /*    format  :: The glyph format.                                       */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    A renderer handle.  0~if none found.                               */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    An error will be returned if a module already exists by that name, */\r\n  /*    or if the module requires a version of FreeType that is too great. */\r\n  /*                                                                       */\r\n  /*    To add a new renderer, simply use @FT_Add_Module.  To retrieve a   */\r\n  /*    renderer by its name, use @FT_Get_Module.                          */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Renderer )\r\n  FT_Get_Renderer( FT_Library       library,\r\n                   FT_Glyph_Format  format );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Set_Renderer                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Set the current renderer to use, and set additional mode.          */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    library    :: A handle to the library object.                      */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    renderer   :: A handle to the renderer object.                     */\r\n  /*                                                                       */\r\n  /*    num_params :: The number of additional parameters.                 */\r\n  /*                                                                       */\r\n  /*    parameters :: Additional parameters.                               */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    In case of success, the renderer will be used to convert glyph     */\r\n  /*    images in the renderer's known format into bitmaps.                */\r\n  /*                                                                       */\r\n  /*    This doesn't change the current renderer for other formats.        */\r\n  /*                                                                       */\r\n  /*    Currently, only the B/W renderer, if compiled with                 */\r\n  /*    FT_RASTER_OPTION_ANTI_ALIASING (providing a 5-levels               */\r\n  /*    anti-aliasing mode; this option must be set directly in            */\r\n  /*    `ftraster.c' and is undefined by default) accepts a single tag     */\r\n  /*    `pal5' to set its gray palette as a character string with          */\r\n  /*    5~elements.  Consequently, the third and fourth argument are zero  */\r\n  /*    normally.                                                          */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Set_Renderer( FT_Library     library,\r\n                   FT_Renderer    renderer,\r\n                   FT_UInt        num_params,\r\n                   FT_Parameter*  parameters );\r\n\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTRENDER_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftsizes.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftsizes.h                                                              */\r\n/*                                                                         */\r\n/*    FreeType size objects management (specification).                    */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2003, 2004, 2006, 2009 by                         */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Typical application would normally not need to use these functions.   */\r\n  /* However, they have been placed in a public API for the rare cases     */\r\n  /* where they are needed.                                                */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n#ifndef __FTSIZES_H__\r\n#define __FTSIZES_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    sizes_management                                                   */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    Size Management                                                    */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    Managing multiple sizes per face.                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    When creating a new face object (e.g., with @FT_New_Face), an      */\r\n  /*    @FT_Size object is automatically created and used to store all     */\r\n  /*    pixel-size dependent information, available in the `face->size'    */\r\n  /*    field.                                                             */\r\n  /*                                                                       */\r\n  /*    It is however possible to create more sizes for a given face,      */\r\n  /*    mostly in order to manage several character pixel sizes of the     */\r\n  /*    same font family and style.  See @FT_New_Size and @FT_Done_Size.   */\r\n  /*                                                                       */\r\n  /*    Note that @FT_Set_Pixel_Sizes and @FT_Set_Char_Size only           */\r\n  /*    modify the contents of the current `active' size; you thus need    */\r\n  /*    to use @FT_Activate_Size to change it.                             */\r\n  /*                                                                       */\r\n  /*    99% of applications won't need the functions provided here,        */\r\n  /*    especially if they use the caching sub-system, so be cautious      */\r\n  /*    when using these.                                                  */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_New_Size                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Create a new size object from a given face object.                 */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face :: A handle to a parent face object.                          */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    asize :: A handle to a new size object.                            */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    You need to call @FT_Activate_Size in order to select the new size */\r\n  /*    for upcoming calls to @FT_Set_Pixel_Sizes, @FT_Set_Char_Size,      */\r\n  /*    @FT_Load_Glyph, @FT_Load_Char, etc.                                */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_New_Size( FT_Face   face,\r\n               FT_Size*  size );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Done_Size                                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Discard a given size object.  Note that @FT_Done_Face              */\r\n  /*    automatically discards all size objects allocated with             */\r\n  /*    @FT_New_Size.                                                      */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    size :: A handle to a target size object.                          */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Done_Size( FT_Size  size );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Activate_Size                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Even though it is possible to create several size objects for a    */\r\n  /*    given face (see @FT_New_Size for details), functions like          */\r\n  /*    @FT_Load_Glyph or @FT_Load_Char only use the one which has been    */\r\n  /*    activated last to determine the `current character pixel size'.    */\r\n  /*                                                                       */\r\n  /*    This function can be used to `activate' a previously created size  */\r\n  /*    object.                                                            */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    size :: A handle to a target size object.                          */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    If `face' is the size's parent face object, this function changes  */\r\n  /*    the value of `face->size' to the input size handle.                */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Activate_Size( FT_Size  size );\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTSIZES_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftsnames.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftsnames.h                                                             */\r\n/*                                                                         */\r\n/*    Simple interface to access SFNT name tables (which are used          */\r\n/*    to hold font names, copyright info, notices, etc.) (specification).  */\r\n/*                                                                         */\r\n/*    This is _not_ used to retrieve glyph names!                          */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2002, 2003, 2006, 2009, 2010 by                   */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FT_SFNT_NAMES_H__\r\n#define __FT_SFNT_NAMES_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    sfnt_names                                                         */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    SFNT Names                                                         */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    Access the names embedded in TrueType and OpenType files.          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    The TrueType and OpenType specifications allow the inclusion of    */\r\n  /*    a special `names table' in font files.  This table contains        */\r\n  /*    textual (and internationalized) information regarding the font,    */\r\n  /*    like family name, copyright, version, etc.                         */\r\n  /*                                                                       */\r\n  /*    The definitions below are used to access them if available.        */\r\n  /*                                                                       */\r\n  /*    Note that this has nothing to do with glyph names!                 */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_SfntName                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to model an SFNT `name' table entry.              */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    platform_id :: The platform ID for `string'.                       */\r\n  /*                                                                       */\r\n  /*    encoding_id :: The encoding ID for `string'.                       */\r\n  /*                                                                       */\r\n  /*    language_id :: The language ID for `string'.                       */\r\n  /*                                                                       */\r\n  /*    name_id     :: An identifier for `string'.                         */\r\n  /*                                                                       */\r\n  /*    string      :: The `name' string.  Note that its format differs    */\r\n  /*                   depending on the (platform,encoding) pair.  It can  */\r\n  /*                   be a Pascal String, a UTF-16 one, etc.              */\r\n  /*                                                                       */\r\n  /*                   Generally speaking, the string is not               */\r\n  /*                   zero-terminated.  Please refer to the TrueType      */\r\n  /*                   specification for details.                          */\r\n  /*                                                                       */\r\n  /*    string_len  :: The length of `string' in bytes.                    */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    Possible values for `platform_id', `encoding_id', `language_id',   */\r\n  /*    and `name_id' are given in the file `ttnameid.h'.  For details     */\r\n  /*    please refer to the TrueType or OpenType specification.            */\r\n  /*                                                                       */\r\n  /*    See also @TT_PLATFORM_XXX, @TT_APPLE_ID_XXX, @TT_MAC_ID_XXX,       */\r\n  /*    @TT_ISO_ID_XXX, and @TT_MS_ID_XXX.                                 */\r\n  /*                                                                       */\r\n  typedef struct  FT_SfntName_\r\n  {\r\n    FT_UShort  platform_id;\r\n    FT_UShort  encoding_id;\r\n    FT_UShort  language_id;\r\n    FT_UShort  name_id;\r\n\r\n    FT_Byte*   string;      /* this string is *not* null-terminated! */\r\n    FT_UInt    string_len;  /* in bytes */\r\n\r\n  } FT_SfntName;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Get_Sfnt_Name_Count                                             */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Retrieve the number of name strings in the SFNT `name' table.      */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face :: A handle to the source face.                               */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    The number of strings in the `name' table.                         */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_UInt )\r\n  FT_Get_Sfnt_Name_Count( FT_Face  face );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Get_Sfnt_Name                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Retrieve a string of the SFNT `name' table for a given index.      */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face  :: A handle to the source face.                              */\r\n  /*                                                                       */\r\n  /*    idx   :: The index of the `name' string.                           */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    aname :: The indexed @FT_SfntName structure.                       */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0~means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The `string' array returned in the `aname' structure is not        */\r\n  /*    null-terminated.  The application should deallocate it if it is no */\r\n  /*    longer in use.                                                     */\r\n  /*                                                                       */\r\n  /*    Use @FT_Get_Sfnt_Name_Count to get the total number of available   */\r\n  /*    `name' table entries, then do a loop until you get the right       */\r\n  /*    platform, encoding, and name ID.                                   */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Get_Sfnt_Name( FT_Face       face,\r\n                    FT_UInt       idx,\r\n                    FT_SfntName  *aname );\r\n\r\n\r\n  /***************************************************************************\r\n   *\r\n   * @constant:\r\n   *   FT_PARAM_TAG_IGNORE_PREFERRED_FAMILY\r\n   *\r\n   * @description:\r\n   *   A constant used as the tag of @FT_Parameter structures to make\r\n   *   FT_Open_Face() ignore preferred family subfamily names in `name'\r\n   *   table since OpenType version 1.4.  For backwards compatibility with\r\n   *   legacy systems which has 4-face-per-family restriction.\r\n   *\r\n   */\r\n#define FT_PARAM_TAG_IGNORE_PREFERRED_FAMILY  FT_MAKE_TAG( 'i', 'g', 'p', 'f' )\r\n\r\n\r\n  /***************************************************************************\r\n   *\r\n   * @constant:\r\n   *   FT_PARAM_TAG_IGNORE_PREFERRED_SUBFAMILY\r\n   *\r\n   * @description:\r\n   *   A constant used as the tag of @FT_Parameter structures to make\r\n   *   FT_Open_Face() ignore preferred subfamily names in `name' table since\r\n   *   OpenType version 1.4.  For backwards compatibility with legacy\r\n   *   systems which has 4-face-per-family restriction.\r\n   *\r\n   */\r\n#define FT_PARAM_TAG_IGNORE_PREFERRED_SUBFAMILY  FT_MAKE_TAG( 'i', 'g', 'p', 's' )\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FT_SFNT_NAMES_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftstroke.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftstroke.h                                                             */\r\n/*                                                                         */\r\n/*    FreeType path stroker (specification).                               */\r\n/*                                                                         */\r\n/*  Copyright 2002-2006, 2008, 2009, 2011 by                               */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FT_STROKE_H__\r\n#define __FT_STROKE_H__\r\n\r\n#include <ft2build.h>\r\n#include FT_OUTLINE_H\r\n#include FT_GLYPH_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n /************************************************************************\r\n  *\r\n  * @section:\r\n  *    glyph_stroker\r\n  *\r\n  * @title:\r\n  *    Glyph Stroker\r\n  *\r\n  * @abstract:\r\n  *    Generating bordered and stroked glyphs.\r\n  *\r\n  * @description:\r\n  *    This component generates stroked outlines of a given vectorial\r\n  *    glyph.  It also allows you to retrieve the `outside' and/or the\r\n  *    `inside' borders of the stroke.\r\n  *\r\n  *    This can be useful to generate `bordered' glyph, i.e., glyphs\r\n  *    displayed with a coloured (and anti-aliased) border around their\r\n  *    shape.\r\n  */\r\n\r\n\r\n /**************************************************************\r\n  *\r\n  * @type:\r\n  *   FT_Stroker\r\n  *\r\n  * @description:\r\n  *   Opaque handler to a path stroker object.\r\n  */\r\n  typedef struct FT_StrokerRec_*  FT_Stroker;\r\n\r\n\r\n  /**************************************************************\r\n   *\r\n   * @enum:\r\n   *   FT_Stroker_LineJoin\r\n   *\r\n   * @description:\r\n   *   These values determine how two joining lines are rendered\r\n   *   in a stroker.\r\n   *\r\n   * @values:\r\n   *   FT_STROKER_LINEJOIN_ROUND ::\r\n   *     Used to render rounded line joins.  Circular arcs are used\r\n   *     to join two lines smoothly.\r\n   *\r\n   *   FT_STROKER_LINEJOIN_BEVEL ::\r\n   *     Used to render beveled line joins.  The outer corner of\r\n   *     the joined lines is filled by enclosing the triangular\r\n   *     region of the corner with a straight line between the\r\n   *     outer corners of each stroke.\r\n   *\r\n   *   FT_STROKER_LINEJOIN_MITER_FIXED ::\r\n   *     Used to render mitered line joins, with fixed bevels if the\r\n   *     miter limit is exceeded.  The outer edges of the strokes\r\n   *     for the two segments are extended until they meet at an\r\n   *     angle.  If the segments meet at too sharp an angle (such\r\n   *     that the miter would extend from the intersection of the \r\n   *     segments a distance greater than the product of the miter \r\n   *     limit value and the border radius), then a bevel join (see \r\n   *     above) is used instead.  This prevents long spikes being \r\n   *     created.  FT_STROKER_LINEJOIN_MITER_FIXED generates a miter \r\n   *     line join as used in PostScript and PDF.\r\n   *\r\n   *   FT_STROKER_LINEJOIN_MITER_VARIABLE ::\r\n   *   FT_STROKER_LINEJOIN_MITER ::\r\n   *     Used to render mitered line joins, with variable bevels if\r\n   *     the miter limit is exceeded.  The intersection of the \r\n   *     strokes is clipped at a line perpendicular to the bisector \r\n   *     of the angle between the strokes, at the distance from the \r\n   *     intersection of the segments equal to the product of the \r\n   *     miter limit value and the border radius.  This prevents \r\n   *     long spikes being created.  \r\n   *     FT_STROKER_LINEJOIN_MITER_VARIABLE generates a mitered line \r\n   *     join as used in XPS.  FT_STROKER_LINEJOIN_MITER is an alias \r\n   *     for FT_STROKER_LINEJOIN_MITER_VARIABLE, retained for \r\n   *     backwards compatibility.\r\n   */\r\n  typedef enum  FT_Stroker_LineJoin_\r\n  {\r\n    FT_STROKER_LINEJOIN_ROUND          = 0,\r\n    FT_STROKER_LINEJOIN_BEVEL          = 1,\r\n    FT_STROKER_LINEJOIN_MITER_VARIABLE = 2,\r\n    FT_STROKER_LINEJOIN_MITER          = FT_STROKER_LINEJOIN_MITER_VARIABLE,\r\n    FT_STROKER_LINEJOIN_MITER_FIXED    = 3\r\n\r\n  } FT_Stroker_LineJoin;\r\n\r\n\r\n  /**************************************************************\r\n   *\r\n   * @enum:\r\n   *   FT_Stroker_LineCap\r\n   *\r\n   * @description:\r\n   *   These values determine how the end of opened sub-paths are\r\n   *   rendered in a stroke.\r\n   *\r\n   * @values:\r\n   *   FT_STROKER_LINECAP_BUTT ::\r\n   *     The end of lines is rendered as a full stop on the last\r\n   *     point itself.\r\n   *\r\n   *   FT_STROKER_LINECAP_ROUND ::\r\n   *     The end of lines is rendered as a half-circle around the\r\n   *     last point.\r\n   *\r\n   *   FT_STROKER_LINECAP_SQUARE ::\r\n   *     The end of lines is rendered as a square around the\r\n   *     last point.\r\n   */\r\n  typedef enum  FT_Stroker_LineCap_\r\n  {\r\n    FT_STROKER_LINECAP_BUTT = 0,\r\n    FT_STROKER_LINECAP_ROUND,\r\n    FT_STROKER_LINECAP_SQUARE\r\n\r\n  } FT_Stroker_LineCap;\r\n\r\n\r\n  /**************************************************************\r\n   *\r\n   * @enum:\r\n   *   FT_StrokerBorder\r\n   *\r\n   * @description:\r\n   *   These values are used to select a given stroke border\r\n   *   in @FT_Stroker_GetBorderCounts and @FT_Stroker_ExportBorder.\r\n   *\r\n   * @values:\r\n   *   FT_STROKER_BORDER_LEFT ::\r\n   *     Select the left border, relative to the drawing direction.\r\n   *\r\n   *   FT_STROKER_BORDER_RIGHT ::\r\n   *     Select the right border, relative to the drawing direction.\r\n   *\r\n   * @note:\r\n   *   Applications are generally interested in the `inside' and `outside'\r\n   *   borders.  However, there is no direct mapping between these and the\r\n   *   `left' and `right' ones, since this really depends on the glyph's\r\n   *   drawing orientation, which varies between font formats.\r\n   *\r\n   *   You can however use @FT_Outline_GetInsideBorder and\r\n   *   @FT_Outline_GetOutsideBorder to get these.\r\n   */\r\n  typedef enum  FT_StrokerBorder_\r\n  {\r\n    FT_STROKER_BORDER_LEFT = 0,\r\n    FT_STROKER_BORDER_RIGHT\r\n\r\n  } FT_StrokerBorder;\r\n\r\n\r\n  /**************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Outline_GetInsideBorder\r\n   *\r\n   * @description:\r\n   *   Retrieve the @FT_StrokerBorder value corresponding to the\r\n   *   `inside' borders of a given outline.\r\n   *\r\n   * @input:\r\n   *   outline ::\r\n   *     The source outline handle.\r\n   *\r\n   * @return:\r\n   *   The border index.  @FT_STROKER_BORDER_RIGHT for empty or invalid\r\n   *   outlines.\r\n   */\r\n  FT_EXPORT( FT_StrokerBorder )\r\n  FT_Outline_GetInsideBorder( FT_Outline*  outline );\r\n\r\n\r\n  /**************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Outline_GetOutsideBorder\r\n   *\r\n   * @description:\r\n   *   Retrieve the @FT_StrokerBorder value corresponding to the\r\n   *   `outside' borders of a given outline.\r\n   *\r\n   * @input:\r\n   *   outline ::\r\n   *     The source outline handle.\r\n   *\r\n   * @return:\r\n   *   The border index.  @FT_STROKER_BORDER_LEFT for empty or invalid\r\n   *   outlines.\r\n   */\r\n  FT_EXPORT( FT_StrokerBorder )\r\n  FT_Outline_GetOutsideBorder( FT_Outline*  outline );\r\n\r\n\r\n  /**************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Stroker_New\r\n   *\r\n   * @description:\r\n   *   Create a new stroker object.\r\n   *\r\n   * @input:\r\n   *   library ::\r\n   *     FreeType library handle.\r\n   *\r\n   * @output:\r\n   *   astroker ::\r\n   *     A new stroker object handle.  NULL in case of error.\r\n   *\r\n   * @return:\r\n   *    FreeType error code.  0~means success.\r\n   */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Stroker_New( FT_Library   library,\r\n                  FT_Stroker  *astroker );\r\n\r\n\r\n  /**************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Stroker_Set\r\n   *\r\n   * @description:\r\n   *   Reset a stroker object's attributes.\r\n   *\r\n   * @input:\r\n   *   stroker ::\r\n   *     The target stroker handle.\r\n   *\r\n   *   radius ::\r\n   *     The border radius.\r\n   *\r\n   *   line_cap ::\r\n   *     The line cap style.\r\n   *\r\n   *   line_join ::\r\n   *     The line join style.\r\n   *\r\n   *   miter_limit ::\r\n   *     The miter limit for the FT_STROKER_LINEJOIN_MITER_FIXED and\r\n   *     FT_STROKER_LINEJOIN_MITER_VARIABLE line join styles,\r\n   *     expressed as 16.16 fixed point value.\r\n   *\r\n   * @note:\r\n   *   The radius is expressed in the same units as the outline\r\n   *   coordinates.\r\n   */\r\n  FT_EXPORT( void )\r\n  FT_Stroker_Set( FT_Stroker           stroker,\r\n                  FT_Fixed             radius,\r\n                  FT_Stroker_LineCap   line_cap,\r\n                  FT_Stroker_LineJoin  line_join,\r\n                  FT_Fixed             miter_limit );\r\n\r\n\r\n  /**************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Stroker_Rewind\r\n   *\r\n   * @description:\r\n   *   Reset a stroker object without changing its attributes.\r\n   *   You should call this function before beginning a new\r\n   *   series of calls to @FT_Stroker_BeginSubPath or\r\n   *   @FT_Stroker_EndSubPath.\r\n   *\r\n   * @input:\r\n   *   stroker ::\r\n   *     The target stroker handle.\r\n   */\r\n  FT_EXPORT( void )\r\n  FT_Stroker_Rewind( FT_Stroker  stroker );\r\n\r\n\r\n  /**************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Stroker_ParseOutline\r\n   *\r\n   * @description:\r\n   *   A convenience function used to parse a whole outline with\r\n   *   the stroker.  The resulting outline(s) can be retrieved\r\n   *   later by functions like @FT_Stroker_GetCounts and @FT_Stroker_Export.\r\n   *\r\n   * @input:\r\n   *   stroker ::\r\n   *     The target stroker handle.\r\n   *\r\n   *   outline ::\r\n   *     The source outline.\r\n   *\r\n   *   opened ::\r\n   *     A boolean.  If~1, the outline is treated as an open path instead\r\n   *     of a closed one.\r\n   *\r\n   * @return:\r\n   *   FreeType error code.  0~means success.\r\n   *\r\n   * @note:\r\n   *   If `opened' is~0 (the default), the outline is treated as a closed\r\n   *   path, and the stroker generates two distinct `border' outlines.\r\n   *\r\n   *   If `opened' is~1, the outline is processed as an open path, and the\r\n   *   stroker generates a single `stroke' outline.\r\n   *\r\n   *   This function calls @FT_Stroker_Rewind automatically.\r\n   */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Stroker_ParseOutline( FT_Stroker   stroker,\r\n                           FT_Outline*  outline,\r\n                           FT_Bool      opened );\r\n\r\n\r\n  /**************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Stroker_BeginSubPath\r\n   *\r\n   * @description:\r\n   *   Start a new sub-path in the stroker.\r\n   *\r\n   * @input:\r\n   *   stroker ::\r\n   *     The target stroker handle.\r\n   *\r\n   *   to ::\r\n   *     A pointer to the start vector.\r\n   *\r\n   *   open ::\r\n   *     A boolean.  If~1, the sub-path is treated as an open one.\r\n   *\r\n   * @return:\r\n   *   FreeType error code.  0~means success.\r\n   *\r\n   * @note:\r\n   *   This function is useful when you need to stroke a path that is\r\n   *   not stored as an @FT_Outline object.\r\n   */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Stroker_BeginSubPath( FT_Stroker  stroker,\r\n                           FT_Vector*  to,\r\n                           FT_Bool     open );\r\n\r\n\r\n  /**************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Stroker_EndSubPath\r\n   *\r\n   * @description:\r\n   *   Close the current sub-path in the stroker.\r\n   *\r\n   * @input:\r\n   *   stroker ::\r\n   *     The target stroker handle.\r\n   *\r\n   * @return:\r\n   *   FreeType error code.  0~means success.\r\n   *\r\n   * @note:\r\n   *   You should call this function after @FT_Stroker_BeginSubPath.\r\n   *   If the subpath was not `opened', this function `draws' a\r\n   *   single line segment to the start position when needed.\r\n   */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Stroker_EndSubPath( FT_Stroker  stroker );\r\n\r\n\r\n  /**************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Stroker_LineTo\r\n   *\r\n   * @description:\r\n   *   `Draw' a single line segment in the stroker's current sub-path,\r\n   *   from the last position.\r\n   *\r\n   * @input:\r\n   *   stroker ::\r\n   *     The target stroker handle.\r\n   *\r\n   *   to ::\r\n   *     A pointer to the destination point.\r\n   *\r\n   * @return:\r\n   *   FreeType error code.  0~means success.\r\n   *\r\n   * @note:\r\n   *   You should call this function between @FT_Stroker_BeginSubPath and\r\n   *   @FT_Stroker_EndSubPath.\r\n   */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Stroker_LineTo( FT_Stroker  stroker,\r\n                     FT_Vector*  to );\r\n\r\n\r\n  /**************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Stroker_ConicTo\r\n   *\r\n   * @description:\r\n   *   `Draw' a single quadratic Bézier in the stroker's current sub-path,\r\n   *   from the last position.\r\n   *\r\n   * @input:\r\n   *   stroker ::\r\n   *     The target stroker handle.\r\n   *\r\n   *   control ::\r\n   *     A pointer to a Bézier control point.\r\n   *\r\n   *   to ::\r\n   *     A pointer to the destination point.\r\n   *\r\n   * @return:\r\n   *   FreeType error code.  0~means success.\r\n   *\r\n   * @note:\r\n   *   You should call this function between @FT_Stroker_BeginSubPath and\r\n   *   @FT_Stroker_EndSubPath.\r\n   */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Stroker_ConicTo( FT_Stroker  stroker,\r\n                      FT_Vector*  control,\r\n                      FT_Vector*  to );\r\n\r\n\r\n  /**************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Stroker_CubicTo\r\n   *\r\n   * @description:\r\n   *   `Draw' a single cubic Bézier in the stroker's current sub-path,\r\n   *   from the last position.\r\n   *\r\n   * @input:\r\n   *   stroker ::\r\n   *     The target stroker handle.\r\n   *\r\n   *   control1 ::\r\n   *     A pointer to the first Bézier control point.\r\n   *\r\n   *   control2 ::\r\n   *     A pointer to second Bézier control point.\r\n   *\r\n   *   to ::\r\n   *     A pointer to the destination point.\r\n   *\r\n   * @return:\r\n   *   FreeType error code.  0~means success.\r\n   *\r\n   * @note:\r\n   *   You should call this function between @FT_Stroker_BeginSubPath and\r\n   *   @FT_Stroker_EndSubPath.\r\n   */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Stroker_CubicTo( FT_Stroker  stroker,\r\n                      FT_Vector*  control1,\r\n                      FT_Vector*  control2,\r\n                      FT_Vector*  to );\r\n\r\n\r\n  /**************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Stroker_GetBorderCounts\r\n   *\r\n   * @description:\r\n   *   Call this function once you have finished parsing your paths\r\n   *   with the stroker.  It returns the number of points and\r\n   *   contours necessary to export one of the `border' or `stroke'\r\n   *   outlines generated by the stroker.\r\n   *\r\n   * @input:\r\n   *   stroker ::\r\n   *     The target stroker handle.\r\n   *\r\n   *   border ::\r\n   *     The border index.\r\n   *\r\n   * @output:\r\n   *   anum_points ::\r\n   *     The number of points.\r\n   *\r\n   *   anum_contours ::\r\n   *     The number of contours.\r\n   *\r\n   * @return:\r\n   *   FreeType error code.  0~means success.\r\n   *\r\n   * @note:\r\n   *   When an outline, or a sub-path, is `closed', the stroker generates\r\n   *   two independent `border' outlines, named `left' and `right'.\r\n   *\r\n   *   When the outline, or a sub-path, is `opened', the stroker merges\r\n   *   the `border' outlines with caps.  The `left' border receives all\r\n   *   points, while the `right' border becomes empty.\r\n   *\r\n   *   Use the function @FT_Stroker_GetCounts instead if you want to\r\n   *   retrieve the counts associated to both borders.\r\n   */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Stroker_GetBorderCounts( FT_Stroker        stroker,\r\n                              FT_StrokerBorder  border,\r\n                              FT_UInt          *anum_points,\r\n                              FT_UInt          *anum_contours );\r\n\r\n\r\n  /**************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Stroker_ExportBorder\r\n   *\r\n   * @description:\r\n   *   Call this function after @FT_Stroker_GetBorderCounts to\r\n   *   export the corresponding border to your own @FT_Outline\r\n   *   structure.\r\n   *\r\n   *   Note that this function appends the border points and\r\n   *   contours to your outline, but does not try to resize its\r\n   *   arrays.\r\n   *\r\n   * @input:\r\n   *   stroker ::\r\n   *     The target stroker handle.\r\n   *\r\n   *   border ::\r\n   *     The border index.\r\n   *\r\n   *   outline ::\r\n   *     The target outline handle.\r\n   *\r\n   * @note:\r\n   *   Always call this function after @FT_Stroker_GetBorderCounts to\r\n   *   get sure that there is enough room in your @FT_Outline object to\r\n   *   receive all new data.\r\n   *\r\n   *   When an outline, or a sub-path, is `closed', the stroker generates\r\n   *   two independent `border' outlines, named `left' and `right'\r\n   *\r\n   *   When the outline, or a sub-path, is `opened', the stroker merges\r\n   *   the `border' outlines with caps. The `left' border receives all\r\n   *   points, while the `right' border becomes empty.\r\n   *\r\n   *   Use the function @FT_Stroker_Export instead if you want to\r\n   *   retrieve all borders at once.\r\n   */\r\n  FT_EXPORT( void )\r\n  FT_Stroker_ExportBorder( FT_Stroker        stroker,\r\n                           FT_StrokerBorder  border,\r\n                           FT_Outline*       outline );\r\n\r\n\r\n  /**************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Stroker_GetCounts\r\n   *\r\n   * @description:\r\n   *   Call this function once you have finished parsing your paths\r\n   *   with the stroker.  It returns the number of points and\r\n   *   contours necessary to export all points/borders from the stroked\r\n   *   outline/path.\r\n   *\r\n   * @input:\r\n   *   stroker ::\r\n   *     The target stroker handle.\r\n   *\r\n   * @output:\r\n   *   anum_points ::\r\n   *     The number of points.\r\n   *\r\n   *   anum_contours ::\r\n   *     The number of contours.\r\n   *\r\n   * @return:\r\n   *   FreeType error code.  0~means success.\r\n   */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Stroker_GetCounts( FT_Stroker  stroker,\r\n                        FT_UInt    *anum_points,\r\n                        FT_UInt    *anum_contours );\r\n\r\n\r\n  /**************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Stroker_Export\r\n   *\r\n   * @description:\r\n   *   Call this function after @FT_Stroker_GetBorderCounts to\r\n   *   export all borders to your own @FT_Outline structure.\r\n   *\r\n   *   Note that this function appends the border points and\r\n   *   contours to your outline, but does not try to resize its\r\n   *   arrays.\r\n   *\r\n   * @input:\r\n   *   stroker ::\r\n   *     The target stroker handle.\r\n   *\r\n   *   outline ::\r\n   *     The target outline handle.\r\n   */\r\n  FT_EXPORT( void )\r\n  FT_Stroker_Export( FT_Stroker   stroker,\r\n                     FT_Outline*  outline );\r\n\r\n\r\n  /**************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Stroker_Done\r\n   *\r\n   * @description:\r\n   *   Destroy a stroker object.\r\n   *\r\n   * @input:\r\n   *   stroker ::\r\n   *     A stroker handle.  Can be NULL.\r\n   */\r\n  FT_EXPORT( void )\r\n  FT_Stroker_Done( FT_Stroker  stroker );\r\n\r\n\r\n  /**************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Glyph_Stroke\r\n   *\r\n   * @description:\r\n   *   Stroke a given outline glyph object with a given stroker.\r\n   *\r\n   * @inout:\r\n   *   pglyph ::\r\n   *     Source glyph handle on input, new glyph handle on output.\r\n   *\r\n   * @input:\r\n   *   stroker ::\r\n   *     A stroker handle.\r\n   *\r\n   *   destroy ::\r\n   *     A Boolean.  If~1, the source glyph object is destroyed\r\n   *     on success.\r\n   *\r\n   * @return:\r\n   *    FreeType error code.  0~means success.\r\n   *\r\n   * @note:\r\n   *   The source glyph is untouched in case of error.\r\n   */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Glyph_Stroke( FT_Glyph    *pglyph,\r\n                   FT_Stroker   stroker,\r\n                   FT_Bool      destroy );\r\n\r\n\r\n  /**************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Glyph_StrokeBorder\r\n   *\r\n   * @description:\r\n   *   Stroke a given outline glyph object with a given stroker, but\r\n   *   only return either its inside or outside border.\r\n   *\r\n   * @inout:\r\n   *   pglyph ::\r\n   *     Source glyph handle on input, new glyph handle on output.\r\n   *\r\n   * @input:\r\n   *   stroker ::\r\n   *     A stroker handle.\r\n   *\r\n   *   inside ::\r\n   *     A Boolean.  If~1, return the inside border, otherwise\r\n   *     the outside border.\r\n   *\r\n   *   destroy ::\r\n   *     A Boolean.  If~1, the source glyph object is destroyed\r\n   *     on success.\r\n   *\r\n   * @return:\r\n   *    FreeType error code.  0~means success.\r\n   *\r\n   * @note:\r\n   *   The source glyph is untouched in case of error.\r\n   */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Glyph_StrokeBorder( FT_Glyph    *pglyph,\r\n                         FT_Stroker   stroker,\r\n                         FT_Bool      inside,\r\n                         FT_Bool      destroy );\r\n\r\n /* */\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FT_STROKE_H__ */\r\n\r\n\r\n/* END */\r\n\r\n\r\n/* Local Variables: */\r\n/* coding: utf-8    */\r\n/* End:             */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftsynth.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftsynth.h                                                              */\r\n/*                                                                         */\r\n/*    FreeType synthesizing code for emboldening and slanting              */\r\n/*    (specification).                                                     */\r\n/*                                                                         */\r\n/*  Copyright 2000-2001, 2003, 2006, 2008 by                               */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*********                                                       *********/\r\n  /*********        WARNING, THIS IS ALPHA CODE!  THIS API         *********/\r\n  /*********    IS DUE TO CHANGE UNTIL STRICTLY NOTIFIED BY THE    *********/\r\n  /*********            FREETYPE DEVELOPMENT TEAM                  *********/\r\n  /*********                                                       *********/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /* Main reason for not lifting the functions in this module to a  */\r\n  /* `standard' API is that the used parameters for emboldening and */\r\n  /* slanting are not configurable.  Consider the functions as a    */\r\n  /* code resource which should be copied into the application and  */\r\n  /* adapted to the particular needs.                               */\r\n\r\n\r\n#ifndef __FTSYNTH_H__\r\n#define __FTSYNTH_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n  /* Embolden a glyph by a `reasonable' value (which is highly a matter of */\r\n  /* taste).  This function is actually a convenience function, providing  */\r\n  /* a wrapper for @FT_Outline_Embolden and @FT_Bitmap_Embolden.           */\r\n  /*                                                                       */\r\n  /* For emboldened outlines the metrics are estimates only; if you need   */\r\n  /* precise values you should call @FT_Outline_Get_CBox.                  */\r\n  FT_EXPORT( void )\r\n  FT_GlyphSlot_Embolden( FT_GlyphSlot  slot );\r\n\r\n  /* Slant an outline glyph to the right by about 12 degrees. */\r\n  FT_EXPORT( void )\r\n  FT_GlyphSlot_Oblique( FT_GlyphSlot  slot );\r\n\r\n  /* */\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTSYNTH_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftsystem.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftsystem.h                                                             */\r\n/*                                                                         */\r\n/*    FreeType low-level system interface definition (specification).      */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2002, 2005, 2010 by                               */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTSYSTEM_H__\r\n#define __FTSYSTEM_H__\r\n\r\n\r\n#include <ft2build.h>\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*   system_interface                                                    */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*   System Interface                                                    */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*   How FreeType manages memory and i/o.                                */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*   This section contains various definitions related to memory         */\r\n  /*   management and i/o access.  You need to understand this             */\r\n  /*   information if you want to use a custom memory manager or you own   */\r\n  /*   i/o streams.                                                        */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /*                  M E M O R Y   M A N A G E M E N T                    */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @type:\r\n   *   FT_Memory\r\n   *\r\n   * @description:\r\n   *   A handle to a given memory manager object, defined with an\r\n   *   @FT_MemoryRec structure.\r\n   *\r\n   */\r\n  typedef struct FT_MemoryRec_*  FT_Memory;\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @functype:\r\n   *   FT_Alloc_Func\r\n   *\r\n   * @description:\r\n   *   A function used to allocate `size' bytes from `memory'.\r\n   *\r\n   * @input:\r\n   *   memory ::\r\n   *     A handle to the source memory manager.\r\n   *\r\n   *   size ::\r\n   *     The size in bytes to allocate.\r\n   *\r\n   * @return:\r\n   *   Address of new memory block.  0~in case of failure.\r\n   *\r\n   */\r\n  typedef void*\r\n  (*FT_Alloc_Func)( FT_Memory  memory,\r\n                    long       size );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @functype:\r\n   *   FT_Free_Func\r\n   *\r\n   * @description:\r\n   *   A function used to release a given block of memory.\r\n   *\r\n   * @input:\r\n   *   memory ::\r\n   *     A handle to the source memory manager.\r\n   *\r\n   *   block ::\r\n   *     The address of the target memory block.\r\n   *\r\n   */\r\n  typedef void\r\n  (*FT_Free_Func)( FT_Memory  memory,\r\n                   void*      block );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @functype:\r\n   *   FT_Realloc_Func\r\n   *\r\n   * @description:\r\n   *   A function used to re-allocate a given block of memory.\r\n   *\r\n   * @input:\r\n   *   memory ::\r\n   *     A handle to the source memory manager.\r\n   *\r\n   *   cur_size ::\r\n   *     The block's current size in bytes.\r\n   *\r\n   *   new_size ::\r\n   *     The block's requested new size.\r\n   *\r\n   *   block ::\r\n   *     The block's current address.\r\n   *\r\n   * @return:\r\n   *   New block address.  0~in case of memory shortage.\r\n   *\r\n   * @note:\r\n   *   In case of error, the old block must still be available.\r\n   *\r\n   */\r\n  typedef void*\r\n  (*FT_Realloc_Func)( FT_Memory  memory,\r\n                      long       cur_size,\r\n                      long       new_size,\r\n                      void*      block );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @struct:\r\n   *   FT_MemoryRec\r\n   *\r\n   * @description:\r\n   *   A structure used to describe a given memory manager to FreeType~2.\r\n   *\r\n   * @fields:\r\n   *   user ::\r\n   *     A generic typeless pointer for user data.\r\n   *\r\n   *   alloc ::\r\n   *     A pointer type to an allocation function.\r\n   *\r\n   *   free ::\r\n   *     A pointer type to an memory freeing function.\r\n   *\r\n   *   realloc ::\r\n   *     A pointer type to a reallocation function.\r\n   *\r\n   */\r\n  struct  FT_MemoryRec_\r\n  {\r\n    void*            user;\r\n    FT_Alloc_Func    alloc;\r\n    FT_Free_Func     free;\r\n    FT_Realloc_Func  realloc;\r\n  };\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /*                       I / O   M A N A G E M E N T                     */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @type:\r\n   *   FT_Stream\r\n   *\r\n   * @description:\r\n   *   A handle to an input stream.\r\n   *\r\n   */\r\n  typedef struct FT_StreamRec_*  FT_Stream;\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @struct:\r\n   *   FT_StreamDesc\r\n   *\r\n   * @description:\r\n   *   A union type used to store either a long or a pointer.  This is used\r\n   *   to store a file descriptor or a `FILE*' in an input stream.\r\n   *\r\n   */\r\n  typedef union  FT_StreamDesc_\r\n  {\r\n    long   value;\r\n    void*  pointer;\r\n\r\n  } FT_StreamDesc;\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @functype:\r\n   *   FT_Stream_IoFunc\r\n   *\r\n   * @description:\r\n   *   A function used to seek and read data from a given input stream.\r\n   *\r\n   * @input:\r\n   *   stream ::\r\n   *     A handle to the source stream.\r\n   *\r\n   *   offset ::\r\n   *     The offset of read in stream (always from start).\r\n   *\r\n   *   buffer ::\r\n   *     The address of the read buffer.\r\n   *\r\n   *   count ::\r\n   *     The number of bytes to read from the stream.\r\n   *\r\n   * @return:\r\n   *   The number of bytes effectively read by the stream.\r\n   *\r\n   * @note:\r\n   *   This function might be called to perform a seek or skip operation\r\n   *   with a `count' of~0.  A non-zero return value then indicates an\r\n   *   error.\r\n   *\r\n   */\r\n  typedef unsigned long\r\n  (*FT_Stream_IoFunc)( FT_Stream       stream,\r\n                       unsigned long   offset,\r\n                       unsigned char*  buffer,\r\n                       unsigned long   count );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @functype:\r\n   *   FT_Stream_CloseFunc\r\n   *\r\n   * @description:\r\n   *   A function used to close a given input stream.\r\n   *\r\n   * @input:\r\n   *  stream ::\r\n   *     A handle to the target stream.\r\n   *\r\n   */\r\n  typedef void\r\n  (*FT_Stream_CloseFunc)( FT_Stream  stream );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @struct:\r\n   *   FT_StreamRec\r\n   *\r\n   * @description:\r\n   *   A structure used to describe an input stream.\r\n   *\r\n   * @input:\r\n   *   base ::\r\n   *     For memory-based streams, this is the address of the first stream\r\n   *     byte in memory.  This field should always be set to NULL for\r\n   *     disk-based streams.\r\n   *\r\n   *   size ::\r\n   *     The stream size in bytes.\r\n   *\r\n   *   pos ::\r\n   *     The current position within the stream.\r\n   *\r\n   *   descriptor ::\r\n   *     This field is a union that can hold an integer or a pointer.  It is\r\n   *     used by stream implementations to store file descriptors or `FILE*'\r\n   *     pointers.\r\n   *\r\n   *   pathname ::\r\n   *     This field is completely ignored by FreeType.  However, it is often\r\n   *     useful during debugging to use it to store the stream's filename\r\n   *     (where available).\r\n   *\r\n   *   read ::\r\n   *     The stream's input function.\r\n   *\r\n   *   close ::\r\n   *     The stream's close function.\r\n   *\r\n   *   memory ::\r\n   *     The memory manager to use to preload frames.  This is set\r\n   *     internally by FreeType and shouldn't be touched by stream\r\n   *     implementations.\r\n   *\r\n   *   cursor ::\r\n   *     This field is set and used internally by FreeType when parsing\r\n   *     frames.\r\n   *\r\n   *   limit ::\r\n   *     This field is set and used internally by FreeType when parsing\r\n   *     frames.\r\n   *\r\n   */\r\n  typedef struct  FT_StreamRec_\r\n  {\r\n    unsigned char*       base;\r\n    unsigned long        size;\r\n    unsigned long        pos;\r\n\r\n    FT_StreamDesc        descriptor;\r\n    FT_StreamDesc        pathname;\r\n    FT_Stream_IoFunc     read;\r\n    FT_Stream_CloseFunc  close;\r\n\r\n    FT_Memory            memory;\r\n    unsigned char*       cursor;\r\n    unsigned char*       limit;\r\n\r\n  } FT_StreamRec;\r\n\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTSYSTEM_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/fttrigon.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  fttrigon.h                                                             */\r\n/*                                                                         */\r\n/*    FreeType trigonometric functions (specification).                    */\r\n/*                                                                         */\r\n/*  Copyright 2001, 2003, 2005, 2007 by                                    */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTTRIGON_H__\r\n#define __FTTRIGON_H__\r\n\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*   computations                                                        */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @type:\r\n   *   FT_Angle\r\n   *\r\n   * @description:\r\n   *   This type is used to model angle values in FreeType.  Note that the\r\n   *   angle is a 16.16 fixed float value expressed in degrees.\r\n   *\r\n   */\r\n  typedef FT_Fixed  FT_Angle;\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_ANGLE_PI\r\n   *\r\n   * @description:\r\n   *   The angle pi expressed in @FT_Angle units.\r\n   *\r\n   */\r\n#define FT_ANGLE_PI  ( 180L << 16 )\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_ANGLE_2PI\r\n   *\r\n   * @description:\r\n   *   The angle 2*pi expressed in @FT_Angle units.\r\n   *\r\n   */\r\n#define FT_ANGLE_2PI  ( FT_ANGLE_PI * 2 )\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_ANGLE_PI2\r\n   *\r\n   * @description:\r\n   *   The angle pi/2 expressed in @FT_Angle units.\r\n   *\r\n   */\r\n#define FT_ANGLE_PI2  ( FT_ANGLE_PI / 2 )\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @macro:\r\n   *   FT_ANGLE_PI4\r\n   *\r\n   * @description:\r\n   *   The angle pi/4 expressed in @FT_Angle units.\r\n   *\r\n   */\r\n#define FT_ANGLE_PI4  ( FT_ANGLE_PI / 4 )\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Sin\r\n   *\r\n   * @description:\r\n   *   Return the sinus of a given angle in fixed point format.\r\n   *\r\n   * @input:\r\n   *   angle ::\r\n   *     The input angle.\r\n   *\r\n   * @return:\r\n   *   The sinus value.\r\n   *\r\n   * @note:\r\n   *   If you need both the sinus and cosinus for a given angle, use the\r\n   *   function @FT_Vector_Unit.\r\n   *\r\n   */\r\n  FT_EXPORT( FT_Fixed )\r\n  FT_Sin( FT_Angle  angle );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Cos\r\n   *\r\n   * @description:\r\n   *   Return the cosinus of a given angle in fixed point format.\r\n   *\r\n   * @input:\r\n   *   angle ::\r\n   *     The input angle.\r\n   *\r\n   * @return:\r\n   *   The cosinus value.\r\n   *\r\n   * @note:\r\n   *   If you need both the sinus and cosinus for a given angle, use the\r\n   *   function @FT_Vector_Unit.\r\n   *\r\n   */\r\n  FT_EXPORT( FT_Fixed )\r\n  FT_Cos( FT_Angle  angle );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Tan\r\n   *\r\n   * @description:\r\n   *   Return the tangent of a given angle in fixed point format.\r\n   *\r\n   * @input:\r\n   *   angle ::\r\n   *     The input angle.\r\n   *\r\n   * @return:\r\n   *   The tangent value.\r\n   *\r\n   */\r\n  FT_EXPORT( FT_Fixed )\r\n  FT_Tan( FT_Angle  angle );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Atan2\r\n   *\r\n   * @description:\r\n   *   Return the arc-tangent corresponding to a given vector (x,y) in\r\n   *   the 2d plane.\r\n   *\r\n   * @input:\r\n   *   x ::\r\n   *     The horizontal vector coordinate.\r\n   *\r\n   *   y ::\r\n   *     The vertical vector coordinate.\r\n   *\r\n   * @return:\r\n   *   The arc-tangent value (i.e. angle).\r\n   *\r\n   */\r\n  FT_EXPORT( FT_Angle )\r\n  FT_Atan2( FT_Fixed  x,\r\n            FT_Fixed  y );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Angle_Diff\r\n   *\r\n   * @description:\r\n   *   Return the difference between two angles.  The result is always\r\n   *   constrained to the ]-PI..PI] interval.\r\n   *\r\n   * @input:\r\n   *   angle1 ::\r\n   *     First angle.\r\n   *\r\n   *   angle2 ::\r\n   *     Second angle.\r\n   *\r\n   * @return:\r\n   *   Constrained value of `value2-value1'.\r\n   *\r\n   */\r\n  FT_EXPORT( FT_Angle )\r\n  FT_Angle_Diff( FT_Angle  angle1,\r\n                 FT_Angle  angle2 );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Vector_Unit\r\n   *\r\n   * @description:\r\n   *   Return the unit vector corresponding to a given angle.  After the\r\n   *   call, the value of `vec.x' will be `sin(angle)', and the value of\r\n   *   `vec.y' will be `cos(angle)'.\r\n   *\r\n   *   This function is useful to retrieve both the sinus and cosinus of a\r\n   *   given angle quickly.\r\n   *\r\n   * @output:\r\n   *   vec ::\r\n   *     The address of target vector.\r\n   *\r\n   * @input:\r\n   *   angle ::\r\n   *     The address of angle.\r\n   *\r\n   */\r\n  FT_EXPORT( void )\r\n  FT_Vector_Unit( FT_Vector*  vec,\r\n                  FT_Angle    angle );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Vector_Rotate\r\n   *\r\n   * @description:\r\n   *   Rotate a vector by a given angle.\r\n   *\r\n   * @inout:\r\n   *   vec ::\r\n   *     The address of target vector.\r\n   *\r\n   * @input:\r\n   *   angle ::\r\n   *     The address of angle.\r\n   *\r\n   */\r\n  FT_EXPORT( void )\r\n  FT_Vector_Rotate( FT_Vector*  vec,\r\n                    FT_Angle    angle );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Vector_Length\r\n   *\r\n   * @description:\r\n   *   Return the length of a given vector.\r\n   *\r\n   * @input:\r\n   *   vec ::\r\n   *     The address of target vector.\r\n   *\r\n   * @return:\r\n   *   The vector length, expressed in the same units that the original\r\n   *   vector coordinates.\r\n   *\r\n   */\r\n  FT_EXPORT( FT_Fixed )\r\n  FT_Vector_Length( FT_Vector*  vec );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Vector_Polarize\r\n   *\r\n   * @description:\r\n   *   Compute both the length and angle of a given vector.\r\n   *\r\n   * @input:\r\n   *   vec ::\r\n   *     The address of source vector.\r\n   *\r\n   * @output:\r\n   *   length ::\r\n   *     The vector length.\r\n   *\r\n   *   angle ::\r\n   *     The vector angle.\r\n   *\r\n   */\r\n  FT_EXPORT( void )\r\n  FT_Vector_Polarize( FT_Vector*  vec,\r\n                      FT_Fixed   *length,\r\n                      FT_Angle   *angle );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @function:\r\n   *   FT_Vector_From_Polar\r\n   *\r\n   * @description:\r\n   *   Compute vector coordinates from a length and angle.\r\n   *\r\n   * @output:\r\n   *   vec ::\r\n   *     The address of source vector.\r\n   *\r\n   * @input:\r\n   *   length ::\r\n   *     The vector length.\r\n   *\r\n   *   angle ::\r\n   *     The vector angle.\r\n   *\r\n   */\r\n  FT_EXPORT( void )\r\n  FT_Vector_From_Polar( FT_Vector*  vec,\r\n                        FT_Fixed    length,\r\n                        FT_Angle    angle );\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTTRIGON_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/fttypes.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  fttypes.h                                                              */\r\n/*                                                                         */\r\n/*    FreeType simple types definitions (specification only).              */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2002, 2004, 2006, 2007, 2008 by                   */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTTYPES_H__\r\n#define __FTTYPES_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_CONFIG_CONFIG_H\r\n#include FT_SYSTEM_H\r\n#include FT_IMAGE_H\r\n\r\n#include <stddef.h>\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    basic_types                                                        */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    Basic Data Types                                                   */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    The basic data types defined by the library.                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This section contains the basic data types defined by FreeType~2,  */\r\n  /*    ranging from simple scalar types to bitmap descriptors.  More      */\r\n  /*    font-specific structures are defined in a different section.       */\r\n  /*                                                                       */\r\n  /* <Order>                                                               */\r\n  /*    FT_Byte                                                            */\r\n  /*    FT_Bytes                                                           */\r\n  /*    FT_Char                                                            */\r\n  /*    FT_Int                                                             */\r\n  /*    FT_UInt                                                            */\r\n  /*    FT_Int16                                                           */\r\n  /*    FT_UInt16                                                          */\r\n  /*    FT_Int32                                                           */\r\n  /*    FT_UInt32                                                          */\r\n  /*    FT_Short                                                           */\r\n  /*    FT_UShort                                                          */\r\n  /*    FT_Long                                                            */\r\n  /*    FT_ULong                                                           */\r\n  /*    FT_Bool                                                            */\r\n  /*    FT_Offset                                                          */\r\n  /*    FT_PtrDist                                                         */\r\n  /*    FT_String                                                          */\r\n  /*    FT_Tag                                                             */\r\n  /*    FT_Error                                                           */\r\n  /*    FT_Fixed                                                           */\r\n  /*    FT_Pointer                                                         */\r\n  /*    FT_Pos                                                             */\r\n  /*    FT_Vector                                                          */\r\n  /*    FT_BBox                                                            */\r\n  /*    FT_Matrix                                                          */\r\n  /*    FT_FWord                                                           */\r\n  /*    FT_UFWord                                                          */\r\n  /*    FT_F2Dot14                                                         */\r\n  /*    FT_UnitVector                                                      */\r\n  /*    FT_F26Dot6                                                         */\r\n  /*                                                                       */\r\n  /*                                                                       */\r\n  /*    FT_Generic                                                         */\r\n  /*    FT_Generic_Finalizer                                               */\r\n  /*                                                                       */\r\n  /*    FT_Bitmap                                                          */\r\n  /*    FT_Pixel_Mode                                                      */\r\n  /*    FT_Palette_Mode                                                    */\r\n  /*    FT_Glyph_Format                                                    */\r\n  /*    FT_IMAGE_TAG                                                       */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Bool                                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A typedef of unsigned char, used for simple booleans.  As usual,   */\r\n  /*    values 1 and~0 represent true and false, respectively.             */\r\n  /*                                                                       */\r\n  typedef unsigned char  FT_Bool;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_FWord                                                           */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A signed 16-bit integer used to store a distance in original font  */\r\n  /*    units.                                                             */\r\n  /*                                                                       */\r\n  typedef signed short  FT_FWord;   /* distance in FUnits */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_UFWord                                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    An unsigned 16-bit integer used to store a distance in original    */\r\n  /*    font units.                                                        */\r\n  /*                                                                       */\r\n  typedef unsigned short  FT_UFWord;  /* unsigned distance */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Char                                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A simple typedef for the _signed_ char type.                       */\r\n  /*                                                                       */\r\n  typedef signed char  FT_Char;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Byte                                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A simple typedef for the _unsigned_ char type.                     */\r\n  /*                                                                       */\r\n  typedef unsigned char  FT_Byte;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Bytes                                                           */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A typedef for constant memory areas.                               */\r\n  /*                                                                       */\r\n  typedef const FT_Byte*  FT_Bytes;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Tag                                                             */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A typedef for 32-bit tags (as used in the SFNT format).            */\r\n  /*                                                                       */\r\n  typedef FT_UInt32  FT_Tag;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_String                                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A simple typedef for the char type, usually used for strings.      */\r\n  /*                                                                       */\r\n  typedef char  FT_String;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Short                                                           */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A typedef for signed short.                                        */\r\n  /*                                                                       */\r\n  typedef signed short  FT_Short;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_UShort                                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A typedef for unsigned short.                                      */\r\n  /*                                                                       */\r\n  typedef unsigned short  FT_UShort;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Int                                                             */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A typedef for the int type.                                        */\r\n  /*                                                                       */\r\n  typedef signed int  FT_Int;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_UInt                                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A typedef for the unsigned int type.                               */\r\n  /*                                                                       */\r\n  typedef unsigned int  FT_UInt;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Long                                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A typedef for signed long.                                         */\r\n  /*                                                                       */\r\n  typedef signed long  FT_Long;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_ULong                                                           */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A typedef for unsigned long.                                       */\r\n  /*                                                                       */\r\n  typedef unsigned long  FT_ULong;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_F2Dot14                                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A signed 2.14 fixed float type used for unit vectors.              */\r\n  /*                                                                       */\r\n  typedef signed short  FT_F2Dot14;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_F26Dot6                                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A signed 26.6 fixed float type used for vectorial pixel            */\r\n  /*    coordinates.                                                       */\r\n  /*                                                                       */\r\n  typedef signed long  FT_F26Dot6;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Fixed                                                           */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This type is used to store 16.16 fixed float values, like scaling  */\r\n  /*    values or matrix coefficients.                                     */\r\n  /*                                                                       */\r\n  typedef signed long  FT_Fixed;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Error                                                           */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    The FreeType error code type.  A value of~0 is always interpreted  */\r\n  /*    as a successful operation.                                         */\r\n  /*                                                                       */\r\n  typedef int  FT_Error;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Pointer                                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A simple typedef for a typeless pointer.                           */\r\n  /*                                                                       */\r\n  typedef void*  FT_Pointer;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_Offset                                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This is equivalent to the ANSI~C `size_t' type, i.e., the largest  */\r\n  /*    _unsigned_ integer type used to express a file size or position,   */\r\n  /*    or a memory block size.                                            */\r\n  /*                                                                       */\r\n  typedef size_t  FT_Offset;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_PtrDist                                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This is equivalent to the ANSI~C `ptrdiff_t' type, i.e., the       */\r\n  /*    largest _signed_ integer type used to express the distance         */\r\n  /*    between two pointers.                                              */\r\n  /*                                                                       */\r\n  typedef ft_ptrdiff_t  FT_PtrDist;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_UnitVector                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A simple structure used to store a 2D vector unit vector.  Uses    */\r\n  /*    FT_F2Dot14 types.                                                  */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    x :: Horizontal coordinate.                                        */\r\n  /*                                                                       */\r\n  /*    y :: Vertical coordinate.                                          */\r\n  /*                                                                       */\r\n  typedef struct  FT_UnitVector_\r\n  {\r\n    FT_F2Dot14  x;\r\n    FT_F2Dot14  y;\r\n\r\n  } FT_UnitVector;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Matrix                                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A simple structure used to store a 2x2 matrix.  Coefficients are   */\r\n  /*    in 16.16 fixed float format.  The computation performed is:        */\r\n  /*                                                                       */\r\n  /*       {                                                               */\r\n  /*          x' = x*xx + y*xy                                             */\r\n  /*          y' = x*yx + y*yy                                             */\r\n  /*       }                                                               */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    xx :: Matrix coefficient.                                          */\r\n  /*                                                                       */\r\n  /*    xy :: Matrix coefficient.                                          */\r\n  /*                                                                       */\r\n  /*    yx :: Matrix coefficient.                                          */\r\n  /*                                                                       */\r\n  /*    yy :: Matrix coefficient.                                          */\r\n  /*                                                                       */\r\n  typedef struct  FT_Matrix_\r\n  {\r\n    FT_Fixed  xx, xy;\r\n    FT_Fixed  yx, yy;\r\n\r\n  } FT_Matrix;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Data                                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Read-only binary data represented as a pointer and a length.       */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    pointer :: The data.                                               */\r\n  /*                                                                       */\r\n  /*    length  :: The length of the data in bytes.                        */\r\n  /*                                                                       */\r\n  typedef struct  FT_Data_\r\n  {\r\n    const FT_Byte*  pointer;\r\n    FT_Int          length;\r\n\r\n  } FT_Data;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_Generic_Finalizer                                               */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Describe a function used to destroy the `client' data of any       */\r\n  /*    FreeType object.  See the description of the @FT_Generic type for  */\r\n  /*    details of usage.                                                  */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    The address of the FreeType object which is under finalization.    */\r\n  /*    Its client data is accessed through its `generic' field.           */\r\n  /*                                                                       */\r\n  typedef void  (*FT_Generic_Finalizer)(void*  object);\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Generic                                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Client applications often need to associate their own data to a    */\r\n  /*    variety of FreeType core objects.  For example, a text layout API  */\r\n  /*    might want to associate a glyph cache to a given size object.      */\r\n  /*                                                                       */\r\n  /*    Most FreeType object contains a `generic' field, of type           */\r\n  /*    FT_Generic, which usage is left to client applications and font    */\r\n  /*    servers.                                                           */\r\n  /*                                                                       */\r\n  /*    It can be used to store a pointer to client-specific data, as well */\r\n  /*    as the address of a `finalizer' function, which will be called by  */\r\n  /*    FreeType when the object is destroyed (for example, the previous   */\r\n  /*    client example would put the address of the glyph cache destructor */\r\n  /*    in the `finalizer' field).                                         */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    data      :: A typeless pointer to any client-specified data. This */\r\n  /*                 field is completely ignored by the FreeType library.  */\r\n  /*                                                                       */\r\n  /*    finalizer :: A pointer to a `generic finalizer' function, which    */\r\n  /*                 will be called when the object is destroyed.  If this */\r\n  /*                 field is set to NULL, no code will be called.         */\r\n  /*                                                                       */\r\n  typedef struct  FT_Generic_\r\n  {\r\n    void*                 data;\r\n    FT_Generic_Finalizer  finalizer;\r\n\r\n  } FT_Generic;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Macro>                                                               */\r\n  /*    FT_MAKE_TAG                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This macro converts four-letter tags which are used to label       */\r\n  /*    TrueType tables into an unsigned long to be used within FreeType.  */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The produced values *must* be 32-bit integers.  Don't redefine     */\r\n  /*    this macro.                                                        */\r\n  /*                                                                       */\r\n#define FT_MAKE_TAG( _x1, _x2, _x3, _x4 ) \\\r\n          (FT_Tag)                        \\\r\n          ( ( (FT_ULong)_x1 << 24 ) |     \\\r\n            ( (FT_ULong)_x2 << 16 ) |     \\\r\n            ( (FT_ULong)_x3 <<  8 ) |     \\\r\n              (FT_ULong)_x4         )\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /*                    L I S T   M A N A G E M E N T                      */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    list_processing                                                    */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_ListNode                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*     Many elements and objects in FreeType are listed through an       */\r\n  /*     @FT_List record (see @FT_ListRec).  As its name suggests, an      */\r\n  /*     FT_ListNode is a handle to a single list element.                 */\r\n  /*                                                                       */\r\n  typedef struct FT_ListNodeRec_*  FT_ListNode;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    FT_List                                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle to a list record (see @FT_ListRec).                       */\r\n  /*                                                                       */\r\n  typedef struct FT_ListRec_*  FT_List;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_ListNodeRec                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to hold a single list element.                    */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    prev :: The previous element in the list.  NULL if first.          */\r\n  /*                                                                       */\r\n  /*    next :: The next element in the list.  NULL if last.               */\r\n  /*                                                                       */\r\n  /*    data :: A typeless pointer to the listed object.                   */\r\n  /*                                                                       */\r\n  typedef struct  FT_ListNodeRec_\r\n  {\r\n    FT_ListNode  prev;\r\n    FT_ListNode  next;\r\n    void*        data;\r\n\r\n  } FT_ListNodeRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_ListRec                                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to hold a simple doubly-linked list.  These are   */\r\n  /*    used in many parts of FreeType.                                    */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    head :: The head (first element) of doubly-linked list.            */\r\n  /*                                                                       */\r\n  /*    tail :: The tail (last element) of doubly-linked list.             */\r\n  /*                                                                       */\r\n  typedef struct  FT_ListRec_\r\n  {\r\n    FT_ListNode  head;\r\n    FT_ListNode  tail;\r\n\r\n  } FT_ListRec;\r\n\r\n\r\n  /* */\r\n\r\n#define FT_IS_EMPTY( list )  ( (list).head == 0 )\r\n\r\n  /* return base error code (without module-specific prefix) */\r\n#define FT_ERROR_BASE( x )    ( (x) & 0xFF )\r\n\r\n  /* return module error code */\r\n#define FT_ERROR_MODULE( x )  ( (x) & 0xFF00U )\r\n\r\n#define FT_BOOL( x )  ( (FT_Bool)( x ) )\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTTYPES_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftwinfnt.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftwinfnt.h                                                             */\r\n/*                                                                         */\r\n/*    FreeType API for accessing Windows fnt-specific data.                */\r\n/*                                                                         */\r\n/*  Copyright 2003, 2004, 2008 by                                          */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTWINFNT_H__\r\n#define __FTWINFNT_H__\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    winfnt_fonts                                                       */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    Window FNT Files                                                   */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    Windows FNT specific API.                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This section contains the declaration of Windows FNT specific      */\r\n  /*    functions.                                                         */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @enum:\r\n   *   FT_WinFNT_ID_XXX\r\n   *\r\n   * @description:\r\n   *   A list of valid values for the `charset' byte in\r\n   *   @FT_WinFNT_HeaderRec.  Exact mapping tables for the various cpXXXX\r\n   *   encodings (except for cp1361) can be found at ftp://ftp.unicode.org\r\n   *   in the MAPPINGS/VENDORS/MICSFT/WINDOWS subdirectory.  cp1361 is\r\n   *   roughly a superset of MAPPINGS/OBSOLETE/EASTASIA/KSC/JOHAB.TXT.\r\n   *\r\n   * @values:\r\n   *   FT_WinFNT_ID_DEFAULT ::\r\n   *     This is used for font enumeration and font creation as a\r\n   *     `don't care' value.  Valid font files don't contain this value.\r\n   *     When querying for information about the character set of the font\r\n   *     that is currently selected into a specified device context, this\r\n   *     return value (of the related Windows API) simply denotes failure.\r\n   *\r\n   *   FT_WinFNT_ID_SYMBOL ::\r\n   *     There is no known mapping table available.\r\n   *\r\n   *   FT_WinFNT_ID_MAC ::\r\n   *     Mac Roman encoding.\r\n   *\r\n   *   FT_WinFNT_ID_OEM ::\r\n   *     From Michael Pöttgen <michael@poettgen.de>:\r\n   *\r\n   *       The `Windows Font Mapping' article says that FT_WinFNT_ID_OEM\r\n   *       is used for the charset of vector fonts, like `modern.fon',\r\n   *       `roman.fon', and `script.fon' on Windows.\r\n   *\r\n   *       The `CreateFont' documentation says: The FT_WinFNT_ID_OEM value\r\n   *       specifies a character set that is operating-system dependent.\r\n   *\r\n   *       The `IFIMETRICS' documentation from the `Windows Driver\r\n   *       Development Kit' says: This font supports an OEM-specific\r\n   *       character set.  The OEM character set is system dependent.\r\n   *\r\n   *       In general OEM, as opposed to ANSI (i.e., cp1252), denotes the\r\n   *       second default codepage that most international versions of\r\n   *       Windows have.  It is one of the OEM codepages from\r\n   *\r\n   *         http://www.microsoft.com/globaldev/reference/cphome.mspx,\r\n   *\r\n   *       and is used for the `DOS boxes', to support legacy applications.\r\n   *       A German Windows version for example usually uses ANSI codepage\r\n   *       1252 and OEM codepage 850.\r\n   *\r\n   *   FT_WinFNT_ID_CP874 ::\r\n   *     A superset of Thai TIS 620 and ISO 8859-11.\r\n   *\r\n   *   FT_WinFNT_ID_CP932 ::\r\n   *     A superset of Japanese Shift-JIS (with minor deviations).\r\n   *\r\n   *   FT_WinFNT_ID_CP936 ::\r\n   *     A superset of simplified Chinese GB 2312-1980 (with different\r\n   *     ordering and minor deviations).\r\n   *\r\n   *   FT_WinFNT_ID_CP949 ::\r\n   *     A superset of Korean Hangul KS~C 5601-1987 (with different\r\n   *     ordering and minor deviations).\r\n   *\r\n   *   FT_WinFNT_ID_CP950 ::\r\n   *     A superset of traditional Chinese Big~5 ETen (with different\r\n   *     ordering and minor deviations).\r\n   *\r\n   *   FT_WinFNT_ID_CP1250 ::\r\n   *     A superset of East European ISO 8859-2 (with slightly different\r\n   *     ordering).\r\n   *\r\n   *   FT_WinFNT_ID_CP1251 ::\r\n   *     A superset of Russian ISO 8859-5 (with different ordering).\r\n   *\r\n   *   FT_WinFNT_ID_CP1252 ::\r\n   *     ANSI encoding.  A superset of ISO 8859-1.\r\n   *\r\n   *   FT_WinFNT_ID_CP1253 ::\r\n   *     A superset of Greek ISO 8859-7 (with minor modifications).\r\n   *\r\n   *   FT_WinFNT_ID_CP1254 ::\r\n   *     A superset of Turkish ISO 8859-9.\r\n   *\r\n   *   FT_WinFNT_ID_CP1255 ::\r\n   *     A superset of Hebrew ISO 8859-8 (with some modifications).\r\n   *\r\n   *   FT_WinFNT_ID_CP1256 ::\r\n   *     A superset of Arabic ISO 8859-6 (with different ordering).\r\n   *\r\n   *   FT_WinFNT_ID_CP1257 ::\r\n   *     A superset of Baltic ISO 8859-13 (with some deviations).\r\n   *\r\n   *   FT_WinFNT_ID_CP1258 ::\r\n   *     For Vietnamese.  This encoding doesn't cover all necessary\r\n   *     characters.\r\n   *\r\n   *   FT_WinFNT_ID_CP1361 ::\r\n   *     Korean (Johab).\r\n   */\r\n\r\n#define FT_WinFNT_ID_CP1252    0\r\n#define FT_WinFNT_ID_DEFAULT   1\r\n#define FT_WinFNT_ID_SYMBOL    2\r\n#define FT_WinFNT_ID_MAC      77\r\n#define FT_WinFNT_ID_CP932   128\r\n#define FT_WinFNT_ID_CP949   129\r\n#define FT_WinFNT_ID_CP1361  130\r\n#define FT_WinFNT_ID_CP936   134\r\n#define FT_WinFNT_ID_CP950   136\r\n#define FT_WinFNT_ID_CP1253  161\r\n#define FT_WinFNT_ID_CP1254  162\r\n#define FT_WinFNT_ID_CP1258  163\r\n#define FT_WinFNT_ID_CP1255  177\r\n#define FT_WinFNT_ID_CP1256  178\r\n#define FT_WinFNT_ID_CP1257  186\r\n#define FT_WinFNT_ID_CP1251  204\r\n#define FT_WinFNT_ID_CP874   222\r\n#define FT_WinFNT_ID_CP1250  238\r\n#define FT_WinFNT_ID_OEM     255\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_WinFNT_HeaderRec                                                */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Windows FNT Header info.                                           */\r\n  /*                                                                       */\r\n  typedef struct  FT_WinFNT_HeaderRec_\r\n  {\r\n    FT_UShort  version;\r\n    FT_ULong   file_size;\r\n    FT_Byte    copyright[60];\r\n    FT_UShort  file_type;\r\n    FT_UShort  nominal_point_size;\r\n    FT_UShort  vertical_resolution;\r\n    FT_UShort  horizontal_resolution;\r\n    FT_UShort  ascent;\r\n    FT_UShort  internal_leading;\r\n    FT_UShort  external_leading;\r\n    FT_Byte    italic;\r\n    FT_Byte    underline;\r\n    FT_Byte    strike_out;\r\n    FT_UShort  weight;\r\n    FT_Byte    charset;\r\n    FT_UShort  pixel_width;\r\n    FT_UShort  pixel_height;\r\n    FT_Byte    pitch_and_family;\r\n    FT_UShort  avg_width;\r\n    FT_UShort  max_width;\r\n    FT_Byte    first_char;\r\n    FT_Byte    last_char;\r\n    FT_Byte    default_char;\r\n    FT_Byte    break_char;\r\n    FT_UShort  bytes_per_row;\r\n    FT_ULong   device_offset;\r\n    FT_ULong   face_name_offset;\r\n    FT_ULong   bits_pointer;\r\n    FT_ULong   bits_offset;\r\n    FT_Byte    reserved;\r\n    FT_ULong   flags;\r\n    FT_UShort  A_space;\r\n    FT_UShort  B_space;\r\n    FT_UShort  C_space;\r\n    FT_UShort  color_table_offset;\r\n    FT_ULong   reserved1[4];\r\n\r\n  } FT_WinFNT_HeaderRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_WinFNT_Header                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle to an @FT_WinFNT_HeaderRec structure.                     */\r\n  /*                                                                       */\r\n  typedef struct FT_WinFNT_HeaderRec_*  FT_WinFNT_Header;\r\n\r\n\r\n  /**********************************************************************\r\n   *\r\n   * @function:\r\n   *    FT_Get_WinFNT_Header\r\n   *\r\n   * @description:\r\n   *    Retrieve a Windows FNT font info header.\r\n   *\r\n   * @input:\r\n   *    face    :: A handle to the input face.\r\n   *\r\n   * @output:\r\n   *    aheader :: The WinFNT header.\r\n   *\r\n   * @return:\r\n   *   FreeType error code.  0~means success.\r\n   *\r\n   * @note:\r\n   *   This function only works with Windows FNT faces, returning an error\r\n   *   otherwise.\r\n   */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Get_WinFNT_Header( FT_Face               face,\r\n                        FT_WinFNT_HeaderRec  *aheader );\r\n\r\n\r\n  /* */\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTWINFNT_H__ */\r\n\r\n\r\n/* END */\r\n\r\n\r\n/* Local Variables: */\r\n/* coding: utf-8    */\r\n/* End:             */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ftxf86.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftxf86.h                                                               */\r\n/*                                                                         */\r\n/*    Support functions for X11.                                           */\r\n/*                                                                         */\r\n/*  Copyright 2002, 2003, 2004, 2006, 2007 by                              */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTXF86_H__\r\n#define __FTXF86_H__\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*   font_formats                                                        */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*   Font Formats                                                        */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*   Getting the font format.                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*   The single function in this section can be used to get the font     */\r\n  /*   format.  Note that this information is not needed normally;         */\r\n  /*   however, there are special cases (like in PDF devices) where it is  */\r\n  /*   important to differentiate, in spite of FreeType's uniform API.     */\r\n  /*                                                                       */\r\n  /*   This function is in the X11/xf86 namespace for historical reasons   */\r\n  /*   and in no way depends on that windowing system.                     */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*   FT_Get_X11_Font_Format                                              */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*   Return a string describing the format of a given face, using values */\r\n  /*   which can be used as an X11 FONT_PROPERTY.  Possible values are     */\r\n  /*   `TrueType', `Type~1', `BDF', `PCF', `Type~42', `CID~Type~1', `CFF', */\r\n  /*   `PFR', and `Windows~FNT'.                                           */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*   face ::                                                             */\r\n  /*     Input face handle.                                                */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*   Font format string.  NULL in case of error.                         */\r\n  /*                                                                       */\r\n  FT_EXPORT( const char* )\r\n  FT_Get_X11_Font_Format( FT_Face  face );\r\n\r\n /* */\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTXF86_H__ */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/autohint.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  autohint.h                                                             */\r\n/*                                                                         */\r\n/*    High-level `autohint' module-specific interface (specification).     */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2002, 2007 by                                     */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* The auto-hinter is used to load and automatically hint glyphs if a    */\r\n  /* format-specific hinter isn't available.                               */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n#ifndef __AUTOHINT_H__\r\n#define __AUTOHINT_H__\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* A small technical note regarding automatic hinting in order to        */\r\n  /* clarify this module interface.                                        */\r\n  /*                                                                       */\r\n  /* An automatic hinter might compute two kinds of data for a given face: */\r\n  /*                                                                       */\r\n  /* - global hints: Usually some metrics that describe global properties  */\r\n  /*                 of the face.  It is computed by scanning more or less */\r\n  /*                 aggressively the glyphs in the face, and thus can be  */\r\n  /*                 very slow to compute (even if the size of global      */\r\n  /*                 hints is really small).                               */\r\n  /*                                                                       */\r\n  /* - glyph hints:  These describe some important features of the glyph   */\r\n  /*                 outline, as well as how to align them.  They are      */\r\n  /*                 generally much faster to compute than global hints.   */\r\n  /*                                                                       */\r\n  /* The current FreeType auto-hinter does a pretty good job while         */\r\n  /* performing fast computations for both global and glyph hints.         */\r\n  /* However, we might be interested in introducing more complex and       */\r\n  /* powerful algorithms in the future, like the one described in the John */\r\n  /* D. Hobby paper, which unfortunately requires a lot more horsepower.   */\r\n  /*                                                                       */\r\n  /* Because a sufficiently sophisticated font management system would     */\r\n  /* typically implement an LRU cache of opened face objects to reduce     */\r\n  /* memory usage, it is a good idea to be able to avoid recomputing       */\r\n  /* global hints every time the same face is re-opened.                   */\r\n  /*                                                                       */\r\n  /* We thus provide the ability to cache global hints outside of the face */\r\n  /* object, in order to speed up font re-opening time.  Of course, this   */\r\n  /* feature is purely optional, so most client programs won't even notice */\r\n  /* it.                                                                   */\r\n  /*                                                                       */\r\n  /* I initially thought that it would be a good idea to cache the glyph   */\r\n  /* hints too.  However, my general idea now is that if you really need   */\r\n  /* to cache these too, you are simply in need of a new font format,      */\r\n  /* where all this information could be stored within the font file and   */\r\n  /* decoded on the fly.                                                   */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  typedef struct FT_AutoHinterRec_  *FT_AutoHinter;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_AutoHinter_GlobalGetFunc                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Retrieves the global hints computed for a given face object the    */\r\n  /*    resulting data is dissociated from the face and will survive a     */\r\n  /*    call to FT_Done_Face().  It must be discarded through the API      */\r\n  /*    FT_AutoHinter_GlobalDoneFunc().                                    */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    hinter        :: A handle to the source auto-hinter.               */\r\n  /*                                                                       */\r\n  /*    face          :: A handle to the source face object.               */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    global_hints  :: A typeless pointer to the global hints.           */\r\n  /*                                                                       */\r\n  /*    global_len    :: The size in bytes of the global hints.            */\r\n  /*                                                                       */\r\n  typedef void\r\n  (*FT_AutoHinter_GlobalGetFunc)( FT_AutoHinter  hinter,\r\n                                  FT_Face        face,\r\n                                  void**         global_hints,\r\n                                  long*          global_len );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_AutoHinter_GlobalDoneFunc                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Discards the global hints retrieved through                        */\r\n  /*    FT_AutoHinter_GlobalGetFunc().  This is the only way these hints   */\r\n  /*    are freed from memory.                                             */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    hinter :: A handle to the auto-hinter module.                      */\r\n  /*                                                                       */\r\n  /*    global :: A pointer to retrieved global hints to discard.          */\r\n  /*                                                                       */\r\n  typedef void\r\n  (*FT_AutoHinter_GlobalDoneFunc)( FT_AutoHinter  hinter,\r\n                                   void*          global );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_AutoHinter_GlobalResetFunc                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This function is used to recompute the global metrics in a given   */\r\n  /*    font.  This is useful when global font data changes (e.g. Multiple */\r\n  /*    Masters fonts where blend coordinates change).                     */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    hinter :: A handle to the source auto-hinter.                      */\r\n  /*                                                                       */\r\n  /*    face   :: A handle to the face.                                    */\r\n  /*                                                                       */\r\n  typedef void\r\n  (*FT_AutoHinter_GlobalResetFunc)( FT_AutoHinter  hinter,\r\n                                    FT_Face        face );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_AutoHinter_GlyphLoadFunc                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This function is used to load, scale, and automatically hint a     */\r\n  /*    glyph from a given face.                                           */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face        :: A handle to the face.                               */\r\n  /*                                                                       */\r\n  /*    glyph_index :: The glyph index.                                    */\r\n  /*                                                                       */\r\n  /*    load_flags  :: The load flags.                                     */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    This function is capable of loading composite glyphs by hinting    */\r\n  /*    each sub-glyph independently (which improves quality).             */\r\n  /*                                                                       */\r\n  /*    It will call the font driver with FT_Load_Glyph(), with            */\r\n  /*    FT_LOAD_NO_SCALE set.                                              */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*FT_AutoHinter_GlyphLoadFunc)( FT_AutoHinter  hinter,\r\n                                  FT_GlyphSlot   slot,\r\n                                  FT_Size        size,\r\n                                  FT_UInt        glyph_index,\r\n                                  FT_Int32       load_flags );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_AutoHinter_ServiceRec                                           */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    The auto-hinter module's interface.                                */\r\n  /*                                                                       */\r\n  typedef struct  FT_AutoHinter_ServiceRec_\r\n  {\r\n    FT_AutoHinter_GlobalResetFunc  reset_face;\r\n    FT_AutoHinter_GlobalGetFunc    get_global_hints;\r\n    FT_AutoHinter_GlobalDoneFunc   done_global_hints;\r\n    FT_AutoHinter_GlyphLoadFunc    load_glyph;\r\n\r\n  } FT_AutoHinter_ServiceRec, *FT_AutoHinter_Service;\r\n\r\n#ifndef FT_CONFIG_OPTION_PIC\r\n\r\n#define FT_DEFINE_AUTOHINTER_SERVICE(class_, reset_face_, get_global_hints_, \\\r\n                                     done_global_hints_, load_glyph_)        \\\r\n  FT_CALLBACK_TABLE_DEF                                                      \\\r\n  const FT_AutoHinter_ServiceRec class_ =                                    \\\r\n  {                                                                          \\\r\n    reset_face_, get_global_hints_, done_global_hints_, load_glyph_          \\\r\n  };\r\n\r\n#else /* FT_CONFIG_OPTION_PIC */ \r\n\r\n#define FT_DEFINE_AUTOHINTER_SERVICE(class_, reset_face_, get_global_hints_, \\\r\n                                     done_global_hints_, load_glyph_)        \\\r\n  void                                                                       \\\r\n  FT_Init_Class_##class_( FT_Library library,                                \\\r\n                          FT_AutoHinter_ServiceRec* clazz)                   \\\r\n  {                                                                          \\\r\n    FT_UNUSED(library);                                                      \\\r\n    clazz->reset_face = reset_face_;                                         \\\r\n    clazz->get_global_hints = get_global_hints_;                             \\\r\n    clazz->done_global_hints = done_global_hints_;                           \\\r\n    clazz->load_glyph = load_glyph_;                                         \\\r\n  } \r\n\r\n#endif /* FT_CONFIG_OPTION_PIC */ \r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __AUTOHINT_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/ftcalc.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftcalc.h                                                               */\r\n/*                                                                         */\r\n/*    Arithmetic computations (specification).                             */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2008, 2009 by       */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTCALC_H__\r\n#define __FTCALC_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_FixedSqrt                                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Computes the square root of a 16.16 fixed point value.             */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    x :: The value to compute the root for.                            */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    The result of `sqrt(x)'.                                           */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    This function is not very fast.                                    */\r\n  /*                                                                       */\r\n  FT_BASE( FT_Int32 )\r\n  FT_SqrtFixed( FT_Int32  x );\r\n\r\n\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Sqrt32                                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Computes the square root of an Int32 integer (which will be        */\r\n  /*    handled as an unsigned long value).                                */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    x :: The value to compute the root for.                            */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    The result of `sqrt(x)'.                                           */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Int32 )\r\n  FT_Sqrt32( FT_Int32  x );\r\n\r\n#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* FT_MulDiv() and FT_MulFix() are declared in freetype.h.               */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n#ifdef TT_USE_BYTECODE_INTERPRETER\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_MulDiv_No_Round                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A very simple function used to perform the computation `(a*b)/c'   */\r\n  /*    (without rounding) with maximal accuracy (it uses a 64-bit         */\r\n  /*    intermediate integer whenever necessary).                          */\r\n  /*                                                                       */\r\n  /*    This function isn't necessarily as fast as some processor specific */\r\n  /*    operations, but is at least completely portable.                   */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    a :: The first multiplier.                                         */\r\n  /*    b :: The second multiplier.                                        */\r\n  /*    c :: The divisor.                                                  */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    The result of `(a*b)/c'.  This function never traps when trying to */\r\n  /*    divide by zero; it simply returns `MaxInt' or `MinInt' depending   */\r\n  /*    on the signs of `a' and `b'.                                       */\r\n  /*                                                                       */\r\n  FT_BASE( FT_Long )\r\n  FT_MulDiv_No_Round( FT_Long  a,\r\n                      FT_Long  b,\r\n                      FT_Long  c );\r\n\r\n#endif /* TT_USE_BYTECODE_INTERPRETER */\r\n\r\n\r\n  /*\r\n   *  A variant of FT_Matrix_Multiply which scales its result afterwards.\r\n   *  The idea is that both `a' and `b' are scaled by factors of 10 so that\r\n   *  the values are as precise as possible to get a correct result during\r\n   *  the 64bit multiplication.  Let `sa' and `sb' be the scaling factors of\r\n   *  `a' and `b', respectively, then the scaling factor of the result is\r\n   *  `sa*sb'.\r\n   */\r\n  FT_BASE( void )\r\n  FT_Matrix_Multiply_Scaled( const FT_Matrix*  a,\r\n                             FT_Matrix        *b,\r\n                             FT_Long           scaling );\r\n\r\n\r\n  /*\r\n   *  A variant of FT_Vector_Transform.  See comments for\r\n   *  FT_Matrix_Multiply_Scaled.\r\n   */\r\n\r\n  FT_BASE( void )\r\n  FT_Vector_Transform_Scaled( FT_Vector*        vector,\r\n                              const FT_Matrix*  matrix,\r\n                              FT_Long           scaling );\r\n\r\n\r\n  /*\r\n   *  Return -1, 0, or +1, depending on the orientation of a given corner.\r\n   *  We use the Cartesian coordinate system, with positive vertical values\r\n   *  going upwards.  The function returns +1 if the corner turns to the\r\n   *  left, -1 to the right, and 0 for undecidable cases.\r\n   */\r\n  FT_BASE( FT_Int )\r\n  ft_corner_orientation( FT_Pos  in_x,\r\n                         FT_Pos  in_y,\r\n                         FT_Pos  out_x,\r\n                         FT_Pos  out_y );\r\n\r\n  /*\r\n   *  Return TRUE if a corner is flat or nearly flat.  This is equivalent to\r\n   *  saying that the angle difference between the `in' and `out' vectors is\r\n   *  very small.\r\n   */\r\n  FT_BASE( FT_Int )\r\n  ft_corner_is_flat( FT_Pos  in_x,\r\n                     FT_Pos  in_y,\r\n                     FT_Pos  out_x,\r\n                     FT_Pos  out_y );\r\n\r\n\r\n#define INT_TO_F26DOT6( x )    ( (FT_Long)(x) << 6  )\r\n#define INT_TO_F2DOT14( x )    ( (FT_Long)(x) << 14 )\r\n#define INT_TO_FIXED( x )      ( (FT_Long)(x) << 16 )\r\n#define F2DOT14_TO_FIXED( x )  ( (FT_Long)(x) << 2  )\r\n#define FLOAT_TO_FIXED( x )    ( (FT_Long)( x * 65536.0 ) )\r\n#define FIXED_TO_INT( x )      ( FT_RoundFix( x ) >> 16 )\r\n\r\n#define ROUND_F26DOT6( x )     ( x >= 0 ? (    ( (x) + 32 ) & -64 )     \\\r\n                                        : ( -( ( 32 - (x) ) & -64 ) ) )\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTCALC_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/ftdebug.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftdebug.h                                                              */\r\n/*                                                                         */\r\n/*    Debugging and logging component (specification).                     */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2002, 2004, 2006, 2007, 2008, 2009 by             */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/*                                                                         */\r\n/*  IMPORTANT: A description of FreeType's debugging support can be        */\r\n/*             found in `docs/DEBUG.TXT'.  Read it if you need to use or   */\r\n/*             understand this code.                                       */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTDEBUG_H__\r\n#define __FTDEBUG_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_CONFIG_CONFIG_H\r\n#include FT_FREETYPE_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /* force the definition of FT_DEBUG_LEVEL_ERROR if FT_DEBUG_LEVEL_TRACE */\r\n  /* is already defined; this simplifies the following #ifdefs            */\r\n  /*                                                                      */\r\n#ifdef FT_DEBUG_LEVEL_TRACE\r\n#undef  FT_DEBUG_LEVEL_ERROR\r\n#define FT_DEBUG_LEVEL_ERROR\r\n#endif\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Define the trace enums as well as the trace levels array when they    */\r\n  /* are needed.                                                           */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n#ifdef FT_DEBUG_LEVEL_TRACE\r\n\r\n#define FT_TRACE_DEF( x )  trace_ ## x ,\r\n\r\n  /* defining the enumeration */\r\n  typedef enum  FT_Trace_\r\n  {\r\n#include FT_INTERNAL_TRACE_H\r\n    trace_count\r\n\r\n  } FT_Trace;\r\n\r\n\r\n  /* defining the array of trace levels, provided by `src/base/ftdebug.c' */\r\n  extern int  ft_trace_levels[trace_count];\r\n\r\n#undef FT_TRACE_DEF\r\n\r\n#endif /* FT_DEBUG_LEVEL_TRACE */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Define the FT_TRACE macro                                             */\r\n  /*                                                                       */\r\n  /* IMPORTANT!                                                            */\r\n  /*                                                                       */\r\n  /* Each component must define the macro FT_COMPONENT to a valid FT_Trace */\r\n  /* value before using any TRACE macro.                                   */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n#ifdef FT_DEBUG_LEVEL_TRACE\r\n\r\n#define FT_TRACE( level, varformat )                      \\\r\n          do                                              \\\r\n          {                                               \\\r\n            if ( ft_trace_levels[FT_COMPONENT] >= level ) \\\r\n              FT_Message varformat;                       \\\r\n          } while ( 0 )\r\n\r\n#else /* !FT_DEBUG_LEVEL_TRACE */\r\n\r\n#define FT_TRACE( level, varformat )  do { } while ( 0 )      /* nothing */\r\n\r\n#endif /* !FT_DEBUG_LEVEL_TRACE */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Trace_Get_Count                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Return the number of available trace components.                   */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    The number of trace components.  0 if FreeType 2 is not built with */\r\n  /*    FT_DEBUG_LEVEL_TRACE definition.                                   */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    This function may be useful if you want to access elements of      */\r\n  /*    the internal `ft_trace_levels' array by an index.                  */\r\n  /*                                                                       */\r\n  FT_BASE( FT_Int )\r\n  FT_Trace_Get_Count( void );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Trace_Get_Name                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Return the name of a trace component.                              */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    The index of the trace component.                                  */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    The name of the trace component.  This is a statically allocated   */\r\n  /*    C string, so do not free it after use.  NULL if FreeType 2 is not  */\r\n  /*    built with FT_DEBUG_LEVEL_TRACE definition.                        */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    Use @FT_Trace_Get_Count to get the number of available trace       */\r\n  /*    components.                                                        */\r\n  /*                                                                       */\r\n  /*    This function may be useful if you want to control FreeType 2's    */\r\n  /*    debug level in your application.                                   */\r\n  /*                                                                       */\r\n  FT_BASE( const char * )\r\n  FT_Trace_Get_Name( FT_Int  idx );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* You need two opening and closing parentheses!                         */\r\n  /*                                                                       */\r\n  /* Example: FT_TRACE0(( \"Value is %i\", foo ))                            */\r\n  /*                                                                       */\r\n  /* Output of the FT_TRACEX macros is sent to stderr.                     */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n#define FT_TRACE0( varformat )  FT_TRACE( 0, varformat )\r\n#define FT_TRACE1( varformat )  FT_TRACE( 1, varformat )\r\n#define FT_TRACE2( varformat )  FT_TRACE( 2, varformat )\r\n#define FT_TRACE3( varformat )  FT_TRACE( 3, varformat )\r\n#define FT_TRACE4( varformat )  FT_TRACE( 4, varformat )\r\n#define FT_TRACE5( varformat )  FT_TRACE( 5, varformat )\r\n#define FT_TRACE6( varformat )  FT_TRACE( 6, varformat )\r\n#define FT_TRACE7( varformat )  FT_TRACE( 7, varformat )\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Define the FT_ERROR macro.                                            */\r\n  /*                                                                       */\r\n  /* Output of this macro is sent to stderr.                               */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n#ifdef FT_DEBUG_LEVEL_ERROR\r\n\r\n#define FT_ERROR( varformat )  FT_Message  varformat\r\n\r\n#else  /* !FT_DEBUG_LEVEL_ERROR */\r\n\r\n#define FT_ERROR( varformat )  do { } while ( 0 )      /* nothing */\r\n\r\n#endif /* !FT_DEBUG_LEVEL_ERROR */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Define the FT_ASSERT macro.                                           */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n#ifdef FT_DEBUG_LEVEL_ERROR\r\n\r\n#define FT_ASSERT( condition )                                      \\\r\n          do                                                        \\\r\n          {                                                         \\\r\n            if ( !( condition ) )                                   \\\r\n              FT_Panic( \"assertion failed on line %d of file %s\\n\", \\\r\n                        __LINE__, __FILE__ );                       \\\r\n          } while ( 0 )\r\n\r\n#else /* !FT_DEBUG_LEVEL_ERROR */\r\n\r\n#define FT_ASSERT( condition )  do { } while ( 0 )\r\n\r\n#endif /* !FT_DEBUG_LEVEL_ERROR */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Define `FT_Message' and `FT_Panic' when needed.                       */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n#ifdef FT_DEBUG_LEVEL_ERROR\r\n\r\n#include \"stdio.h\"  /* for vfprintf() */\r\n\r\n  /* print a message */\r\n  FT_BASE( void )\r\n  FT_Message( const char*  fmt,\r\n              ... );\r\n\r\n  /* print a message and exit */\r\n  FT_BASE( void )\r\n  FT_Panic( const char*  fmt,\r\n            ... );\r\n\r\n#endif /* FT_DEBUG_LEVEL_ERROR */\r\n\r\n\r\n  FT_BASE( void )\r\n  ft_debug_init( void );\r\n\r\n\r\n#if defined( _MSC_VER )      /* Visual C++ (and Intel C++) */\r\n\r\n  /* We disable the warning `conditional expression is constant' here */\r\n  /* in order to compile cleanly with the maximum level of warnings.  */\r\n#pragma warning( disable : 4127 )\r\n\r\n#endif /* _MSC_VER */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTDEBUG_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/ftdriver.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftdriver.h                                                             */\r\n/*                                                                         */\r\n/*    FreeType font driver interface (specification).                      */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2002, 2003, 2006, 2008 by                         */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTDRIVER_H__\r\n#define __FTDRIVER_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_MODULE_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  typedef FT_Error\r\n  (*FT_Face_InitFunc)( FT_Stream      stream,\r\n                       FT_Face        face,\r\n                       FT_Int         typeface_index,\r\n                       FT_Int         num_params,\r\n                       FT_Parameter*  parameters );\r\n\r\n  typedef void\r\n  (*FT_Face_DoneFunc)( FT_Face  face );\r\n\r\n\r\n  typedef FT_Error\r\n  (*FT_Size_InitFunc)( FT_Size  size );\r\n\r\n  typedef void\r\n  (*FT_Size_DoneFunc)( FT_Size  size );\r\n\r\n\r\n  typedef FT_Error\r\n  (*FT_Slot_InitFunc)( FT_GlyphSlot  slot );\r\n\r\n  typedef void\r\n  (*FT_Slot_DoneFunc)( FT_GlyphSlot  slot );\r\n\r\n\r\n  typedef FT_Error\r\n  (*FT_Size_RequestFunc)( FT_Size          size,\r\n                          FT_Size_Request  req );\r\n\r\n  typedef FT_Error\r\n  (*FT_Size_SelectFunc)( FT_Size   size,\r\n                         FT_ULong  size_index );\r\n\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n\r\n  typedef FT_Error\r\n  (*FT_Size_ResetPointsFunc)( FT_Size     size,\r\n                              FT_F26Dot6  char_width,\r\n                              FT_F26Dot6  char_height,\r\n                              FT_UInt     horz_resolution,\r\n                              FT_UInt     vert_resolution );\r\n\r\n  typedef FT_Error\r\n  (*FT_Size_ResetPixelsFunc)( FT_Size  size,\r\n                              FT_UInt  pixel_width,\r\n                              FT_UInt  pixel_height );\r\n\r\n#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */\r\n\r\n  typedef FT_Error\r\n  (*FT_Slot_LoadFunc)( FT_GlyphSlot  slot,\r\n                       FT_Size       size,\r\n                       FT_UInt       glyph_index,\r\n                       FT_Int32      load_flags );\r\n\r\n\r\n  typedef FT_UInt\r\n  (*FT_CharMap_CharIndexFunc)( FT_CharMap  charmap,\r\n                               FT_Long     charcode );\r\n\r\n  typedef FT_Long\r\n  (*FT_CharMap_CharNextFunc)( FT_CharMap  charmap,\r\n                              FT_Long     charcode );\r\n\r\n\r\n  typedef FT_Error\r\n  (*FT_Face_GetKerningFunc)( FT_Face     face,\r\n                             FT_UInt     left_glyph,\r\n                             FT_UInt     right_glyph,\r\n                             FT_Vector*  kerning );\r\n\r\n\r\n  typedef FT_Error\r\n  (*FT_Face_AttachFunc)( FT_Face    face,\r\n                         FT_Stream  stream );\r\n\r\n\r\n  typedef FT_Error\r\n  (*FT_Face_GetAdvancesFunc)( FT_Face    face,\r\n                              FT_UInt    first,\r\n                              FT_UInt    count,\r\n                              FT_Int32   flags,\r\n                              FT_Fixed*  advances );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Driver_ClassRec                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    The font driver class.  This structure mostly contains pointers to */\r\n  /*    driver methods.                                                    */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    root             :: The parent module.                             */\r\n  /*                                                                       */\r\n  /*    face_object_size :: The size of a face object in bytes.            */\r\n  /*                                                                       */\r\n  /*    size_object_size :: The size of a size object in bytes.            */\r\n  /*                                                                       */\r\n  /*    slot_object_size :: The size of a glyph object in bytes.           */\r\n  /*                                                                       */\r\n  /*    init_face        :: The format-specific face constructor.          */\r\n  /*                                                                       */\r\n  /*    done_face        :: The format-specific face destructor.           */\r\n  /*                                                                       */\r\n  /*    init_size        :: The format-specific size constructor.          */\r\n  /*                                                                       */\r\n  /*    done_size        :: The format-specific size destructor.           */\r\n  /*                                                                       */\r\n  /*    init_slot        :: The format-specific slot constructor.          */\r\n  /*                                                                       */\r\n  /*    done_slot        :: The format-specific slot destructor.           */\r\n  /*                                                                       */\r\n  /*                                                                       */\r\n  /*    load_glyph       :: A function handle to load a glyph to a slot.   */\r\n  /*                        This field is mandatory!                       */\r\n  /*                                                                       */\r\n  /*    get_kerning      :: A function handle to return the unscaled       */\r\n  /*                        kerning for a given pair of glyphs.  Can be    */\r\n  /*                        set to 0 if the format doesn't support         */\r\n  /*                        kerning.                                       */\r\n  /*                                                                       */\r\n  /*    attach_file      :: This function handle is used to read           */\r\n  /*                        additional data for a face from another        */\r\n  /*                        file/stream.  For example, this can be used to */\r\n  /*                        add data from AFM or PFM files on a Type 1     */\r\n  /*                        face, or a CIDMap on a CID-keyed face.         */\r\n  /*                                                                       */\r\n  /*    get_advances     :: A function handle used to return advance       */\r\n  /*                        widths of `count' glyphs (in font units),      */\r\n  /*                        starting at `first'.  The `vertical' flag must */\r\n  /*                        be set to get vertical advance heights.  The   */\r\n  /*                        `advances' buffer is caller-allocated.         */\r\n  /*                        Currently not implemented.  The idea of this   */\r\n  /*                        function is to be able to perform              */\r\n  /*                        device-independent text layout without loading */\r\n  /*                        a single glyph image.                          */\r\n  /*                                                                       */\r\n  /*    request_size     :: A handle to a function used to request the new */\r\n  /*                        character size.  Can be set to 0 if the        */\r\n  /*                        scaling done in the base layer suffices.       */\r\n  /*                                                                       */\r\n  /*    select_size      :: A handle to a function used to select a new    */\r\n  /*                        fixed size.  It is used only if                */\r\n  /*                        @FT_FACE_FLAG_FIXED_SIZES is set.  Can be set  */\r\n  /*                        to 0 if the scaling done in the base layer     */\r\n  /*                        suffices.                                      */\r\n  /* <Note>                                                                */\r\n  /*    Most function pointers, with the exception of `load_glyph', can be */\r\n  /*    set to 0 to indicate a default behaviour.                          */\r\n  /*                                                                       */\r\n  typedef struct  FT_Driver_ClassRec_\r\n  {\r\n    FT_Module_Class           root;\r\n\r\n    FT_Long                   face_object_size;\r\n    FT_Long                   size_object_size;\r\n    FT_Long                   slot_object_size;\r\n\r\n    FT_Face_InitFunc          init_face;\r\n    FT_Face_DoneFunc          done_face;\r\n\r\n    FT_Size_InitFunc          init_size;\r\n    FT_Size_DoneFunc          done_size;\r\n\r\n    FT_Slot_InitFunc          init_slot;\r\n    FT_Slot_DoneFunc          done_slot;\r\n\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n\r\n    FT_Size_ResetPointsFunc   set_char_sizes;\r\n    FT_Size_ResetPixelsFunc   set_pixel_sizes;\r\n\r\n#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */\r\n\r\n    FT_Slot_LoadFunc          load_glyph;\r\n\r\n    FT_Face_GetKerningFunc    get_kerning;\r\n    FT_Face_AttachFunc        attach_file;\r\n    FT_Face_GetAdvancesFunc   get_advances;\r\n\r\n    /* since version 2.2 */\r\n    FT_Size_RequestFunc       request_size;\r\n    FT_Size_SelectFunc        select_size;\r\n\r\n  } FT_Driver_ClassRec, *FT_Driver_Class;\r\n\r\n\r\n  /*\r\n   *  The following functions are used as stubs for `set_char_sizes' and\r\n   *  `set_pixel_sizes'; the code uses `request_size' and `select_size'\r\n   *  functions instead.\r\n   *\r\n   *  Implementation is in `src/base/ftobjs.c'.\r\n   */\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n\r\n  FT_BASE( FT_Error )\r\n  ft_stub_set_char_sizes( FT_Size     size,\r\n                          FT_F26Dot6  width,\r\n                          FT_F26Dot6  height,\r\n                          FT_UInt     horz_res,\r\n                          FT_UInt     vert_res );\r\n\r\n  FT_BASE( FT_Error )\r\n  ft_stub_set_pixel_sizes( FT_Size  size,\r\n                           FT_UInt  width,\r\n                           FT_UInt  height );\r\n\r\n#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Macro>                                                               */\r\n  /*    FT_DECLARE_DRIVER                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Used to create a forward declaration of a                          */\r\n  /*    FT_Driver_ClassRec stract instance.                                */\r\n  /*                                                                       */\r\n  /* <Macro>                                                               */\r\n  /*    FT_DEFINE_DRIVER                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Used to initialize an instance of FT_Driver_ClassRec struct.       */\r\n  /*                                                                       */\r\n  /*    When FT_CONFIG_OPTION_PIC is defined a Create funtion will need    */\r\n  /*    to called with a pointer where the allocated stracture is returned.*/\r\n  /*    And when it is no longer needed a Destroy function needs           */\r\n  /*    to be called to release that allocation.                           */\r\n  /*    fcinit.c (ft_create_default_module_classes) already contains       */\r\n  /*    a mechanism to call these functions for the default modules        */\r\n  /*    described in ftmodule.h                                            */\r\n  /*                                                                       */\r\n  /*    Notice that the created Create and Destroy functions call          */\r\n  /*    pic_init and pic_free function to allow you to manually allocate   */\r\n  /*    and initialize any additional global data, like module specific    */\r\n  /*    interface, and put them in the global pic container defined in     */\r\n  /*    ftpic.h. if you don't need them just implement the functions as    */\r\n  /*    empty to resolve the link error.                                   */\r\n  /*                                                                       */\r\n  /*    When FT_CONFIG_OPTION_PIC is not defined the struct will be        */\r\n  /*    allocated in the global scope (or the scope where the macro        */\r\n  /*    is used).                                                          */\r\n  /*                                                                       */\r\n#ifndef FT_CONFIG_OPTION_PIC\r\n\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n#define FT_DEFINE_DRIVERS_OLD_INTERNALS(a_,b_) \\\r\n  a_, b_,\r\n#else\r\n  #define FT_DEFINE_DRIVERS_OLD_INTERNALS(a_,b_)\r\n#endif\r\n\r\n#define FT_DECLARE_DRIVER(class_)    \\\r\n  FT_CALLBACK_TABLE                  \\\r\n  const FT_Driver_ClassRec  class_;  \r\n\r\n#define FT_DEFINE_DRIVER(class_,                                             \\\r\n                         flags_, size_, name_, version_, requires_,          \\\r\n                         interface_, init_, done_, get_interface_,           \\\r\n                         face_object_size_, size_object_size_,               \\\r\n                         slot_object_size_, init_face_, done_face_,          \\\r\n                         init_size_, done_size_, init_slot_, done_slot_,     \\\r\n                         old_set_char_sizes_, old_set_pixel_sizes_,          \\\r\n                         load_glyph_, get_kerning_, attach_file_,            \\\r\n                         get_advances_, request_size_, select_size_ )        \\\r\n  FT_CALLBACK_TABLE_DEF                                                      \\\r\n  const FT_Driver_ClassRec class_ =                                          \\\r\n  {                                                                          \\\r\n    FT_DEFINE_ROOT_MODULE(flags_,size_,name_,version_,requires_,interface_,  \\\r\n                          init_,done_,get_interface_)                        \\\r\n                                                                             \\\r\n    face_object_size_,                                                       \\\r\n    size_object_size_,                                                       \\\r\n    slot_object_size_,                                                       \\\r\n                                                                             \\\r\n    init_face_,                                                              \\\r\n    done_face_,                                                              \\\r\n                                                                             \\\r\n    init_size_,                                                              \\\r\n    done_size_,                                                              \\\r\n                                                                             \\\r\n    init_slot_,                                                              \\\r\n    done_slot_,                                                              \\\r\n                                                                             \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNALS(old_set_char_sizes_, old_set_pixel_sizes_) \\\r\n                                                                             \\\r\n    load_glyph_,                                                             \\\r\n                                                                             \\\r\n    get_kerning_,                                                            \\\r\n    attach_file_,                                                            \\\r\n    get_advances_,                                                           \\\r\n                                                                             \\\r\n    request_size_,                                                           \\\r\n    select_size_                                                             \\\r\n  };\r\n\r\n#else /* FT_CONFIG_OPTION_PIC */ \r\n\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n#define FT_DEFINE_DRIVERS_OLD_INTERNALS(a_,b_) \\\r\n  clazz->set_char_sizes = a_; \\\r\n  clazz->set_pixel_sizes = b_;\r\n#else\r\n  #define FT_DEFINE_DRIVERS_OLD_INTERNALS(a_,b_)\r\n#endif\r\n\r\n#define FT_DECLARE_DRIVER(class_)    FT_DECLARE_MODULE(class_)\r\n\r\n#define FT_DEFINE_DRIVER(class_,                                             \\\r\n                         flags_, size_, name_, version_, requires_,          \\\r\n                         interface_, init_, done_, get_interface_,           \\\r\n                         face_object_size_, size_object_size_,               \\\r\n                         slot_object_size_, init_face_, done_face_,          \\\r\n                         init_size_, done_size_, init_slot_, done_slot_,     \\\r\n                         old_set_char_sizes_, old_set_pixel_sizes_,          \\\r\n                         load_glyph_, get_kerning_, attach_file_,            \\\r\n                         get_advances_, request_size_, select_size_ )        \\\r\n  void class_##_pic_free( FT_Library library );                              \\\r\n  FT_Error class_##_pic_init( FT_Library library );                          \\\r\n                                                                             \\\r\n  void                                                                       \\\r\n  FT_Destroy_Class_##class_( FT_Library        library,                      \\\r\n                             FT_Module_Class*  clazz )                       \\\r\n  {                                                                          \\\r\n    FT_Memory       memory = library->memory;                                \\\r\n    FT_Driver_Class dclazz = (FT_Driver_Class)clazz;                         \\\r\n    class_##_pic_free( library );                                            \\\r\n    if ( dclazz )                                                            \\\r\n      FT_FREE( dclazz );                                                     \\\r\n  }                                                                          \\\r\n                                                                             \\\r\n  FT_Error                                                                   \\\r\n  FT_Create_Class_##class_( FT_Library        library,                       \\\r\n                            FT_Module_Class**  output_class )                \\\r\n  {                                                                          \\\r\n    FT_Driver_Class  clazz;                                                  \\\r\n    FT_Error         error;                                                  \\\r\n    FT_Memory        memory = library->memory;                               \\\r\n                                                                             \\\r\n    if ( FT_ALLOC( clazz, sizeof(*clazz) ) )                                 \\\r\n      return error;                                                          \\\r\n                                                                             \\\r\n    error = class_##_pic_init( library );                                    \\\r\n    if(error)                                                                \\\r\n    {                                                                        \\\r\n      FT_FREE( clazz );                                                      \\\r\n      return error;                                                          \\\r\n    }                                                                        \\\r\n                                                                             \\\r\n    FT_DEFINE_ROOT_MODULE(flags_,size_,name_,version_,requires_,interface_,  \\\r\n                          init_,done_,get_interface_)                        \\\r\n                                                                             \\\r\n    clazz->face_object_size    = face_object_size_;                          \\\r\n    clazz->size_object_size    = size_object_size_;                          \\\r\n    clazz->slot_object_size    = slot_object_size_;                          \\\r\n                                                                             \\\r\n    clazz->init_face           = init_face_;                                 \\\r\n    clazz->done_face           = done_face_;                                 \\\r\n                                                                             \\\r\n    clazz->init_size           = init_size_;                                 \\\r\n    clazz->done_size           = done_size_;                                 \\\r\n                                                                             \\\r\n    clazz->init_slot           = init_slot_;                                 \\\r\n    clazz->done_slot           = done_slot_;                                 \\\r\n                                                                             \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNALS(old_set_char_sizes_, old_set_pixel_sizes_) \\\r\n                                                                             \\\r\n    clazz->load_glyph          = load_glyph_;                                \\\r\n                                                                             \\\r\n    clazz->get_kerning         = get_kerning_;                               \\\r\n    clazz->attach_file         = attach_file_;                               \\\r\n    clazz->get_advances        = get_advances_;                              \\\r\n                                                                             \\\r\n    clazz->request_size        = request_size_;                              \\\r\n    clazz->select_size         = select_size_;                               \\\r\n                                                                             \\\r\n    *output_class = (FT_Module_Class*)clazz;                                 \\\r\n    return FT_Err_Ok;                                                        \\\r\n  }                \r\n\r\n\r\n#endif /* FT_CONFIG_OPTION_PIC */\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTDRIVER_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/ftgloadr.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftgloadr.h                                                             */\r\n/*                                                                         */\r\n/*    The FreeType glyph loader (specification).                           */\r\n/*                                                                         */\r\n/*  Copyright 2002, 2003, 2005, 2006 by                                    */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg                       */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTGLOADR_H__\r\n#define __FTGLOADR_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_GlyphLoader                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    The glyph loader is an internal object used to load several glyphs */\r\n  /*    together (for example, in the case of composites).                 */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The glyph loader implementation is not part of the high-level API, */\r\n  /*    hence the forward structure declaration.                           */\r\n  /*                                                                       */\r\n  typedef struct FT_GlyphLoaderRec_*  FT_GlyphLoader ;\r\n\r\n\r\n#if 0  /* moved to freetype.h in version 2.2 */\r\n#define FT_SUBGLYPH_FLAG_ARGS_ARE_WORDS          1\r\n#define FT_SUBGLYPH_FLAG_ARGS_ARE_XY_VALUES      2\r\n#define FT_SUBGLYPH_FLAG_ROUND_XY_TO_GRID        4\r\n#define FT_SUBGLYPH_FLAG_SCALE                   8\r\n#define FT_SUBGLYPH_FLAG_XY_SCALE             0x40\r\n#define FT_SUBGLYPH_FLAG_2X2                  0x80\r\n#define FT_SUBGLYPH_FLAG_USE_MY_METRICS      0x200\r\n#endif\r\n\r\n\r\n  typedef struct  FT_SubGlyphRec_\r\n  {\r\n    FT_Int     index;\r\n    FT_UShort  flags;\r\n    FT_Int     arg1;\r\n    FT_Int     arg2;\r\n    FT_Matrix  transform;\r\n\r\n  } FT_SubGlyphRec;\r\n\r\n\r\n  typedef struct  FT_GlyphLoadRec_\r\n  {\r\n    FT_Outline   outline;       /* outline                   */\r\n    FT_Vector*   extra_points;  /* extra points table        */\r\n    FT_Vector*   extra_points2; /* second extra points table */\r\n    FT_UInt      num_subglyphs; /* number of subglyphs       */\r\n    FT_SubGlyph  subglyphs;     /* subglyphs                 */\r\n\r\n  } FT_GlyphLoadRec, *FT_GlyphLoad;\r\n\r\n\r\n  typedef struct  FT_GlyphLoaderRec_\r\n  {\r\n    FT_Memory        memory;\r\n    FT_UInt          max_points;\r\n    FT_UInt          max_contours;\r\n    FT_UInt          max_subglyphs;\r\n    FT_Bool          use_extra;\r\n\r\n    FT_GlyphLoadRec  base;\r\n    FT_GlyphLoadRec  current;\r\n\r\n    void*            other;            /* for possible future extension? */\r\n\r\n  } FT_GlyphLoaderRec;\r\n\r\n\r\n  /* create new empty glyph loader */\r\n  FT_BASE( FT_Error )\r\n  FT_GlyphLoader_New( FT_Memory        memory,\r\n                      FT_GlyphLoader  *aloader );\r\n\r\n  /* add an extra points table to a glyph loader */\r\n  FT_BASE( FT_Error )\r\n  FT_GlyphLoader_CreateExtra( FT_GlyphLoader  loader );\r\n\r\n  /* destroy a glyph loader */\r\n  FT_BASE( void )\r\n  FT_GlyphLoader_Done( FT_GlyphLoader  loader );\r\n\r\n  /* reset a glyph loader (frees everything int it) */\r\n  FT_BASE( void )\r\n  FT_GlyphLoader_Reset( FT_GlyphLoader  loader );\r\n\r\n  /* rewind a glyph loader */\r\n  FT_BASE( void )\r\n  FT_GlyphLoader_Rewind( FT_GlyphLoader  loader );\r\n\r\n  /* check that there is enough space to add `n_points' and `n_contours' */\r\n  /* to the glyph loader                                                 */\r\n  FT_BASE( FT_Error )\r\n  FT_GlyphLoader_CheckPoints( FT_GlyphLoader  loader,\r\n                              FT_UInt         n_points,\r\n                              FT_UInt         n_contours );\r\n\r\n\r\n#define FT_GLYPHLOADER_CHECK_P( _loader, _count )                         \\\r\n   ( (_count) == 0 || ((_loader)->base.outline.n_points    +              \\\r\n                       (_loader)->current.outline.n_points +              \\\r\n                       (unsigned long)(_count)) <= (_loader)->max_points )\r\n\r\n#define FT_GLYPHLOADER_CHECK_C( _loader, _count )                          \\\r\n  ( (_count) == 0 || ((_loader)->base.outline.n_contours    +              \\\r\n                      (_loader)->current.outline.n_contours +              \\\r\n                      (unsigned long)(_count)) <= (_loader)->max_contours )\r\n\r\n#define FT_GLYPHLOADER_CHECK_POINTS( _loader, _points,_contours )      \\\r\n  ( ( FT_GLYPHLOADER_CHECK_P( _loader, _points )   &&                  \\\r\n      FT_GLYPHLOADER_CHECK_C( _loader, _contours ) )                   \\\r\n    ? 0                                                                \\\r\n    : FT_GlyphLoader_CheckPoints( (_loader), (_points), (_contours) ) )\r\n\r\n\r\n  /* check that there is enough space to add `n_subs' sub-glyphs to */\r\n  /* a glyph loader                                                 */\r\n  FT_BASE( FT_Error )\r\n  FT_GlyphLoader_CheckSubGlyphs( FT_GlyphLoader  loader,\r\n                                 FT_UInt         n_subs );\r\n\r\n  /* prepare a glyph loader, i.e. empty the current glyph */\r\n  FT_BASE( void )\r\n  FT_GlyphLoader_Prepare( FT_GlyphLoader  loader );\r\n\r\n  /* add the current glyph to the base glyph */\r\n  FT_BASE( void )\r\n  FT_GlyphLoader_Add( FT_GlyphLoader  loader );\r\n\r\n  /* copy points from one glyph loader to another */\r\n  FT_BASE( FT_Error )\r\n  FT_GlyphLoader_CopyPoints( FT_GlyphLoader  target,\r\n                             FT_GlyphLoader  source );\r\n\r\n /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTGLOADR_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/ftmemory.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftmemory.h                                                             */\r\n/*                                                                         */\r\n/*    The FreeType memory management macros (specification).               */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2002, 2004, 2005, 2006, 2007, 2010 by             */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg                       */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTMEMORY_H__\r\n#define __FTMEMORY_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_CONFIG_CONFIG_H\r\n#include FT_TYPES_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Macro>                                                               */\r\n  /*    FT_SET_ERROR                                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This macro is used to set an implicit `error' variable to a given  */\r\n  /*    expression's value (usually a function call), and convert it to a  */\r\n  /*    boolean which is set whenever the value is != 0.                   */\r\n  /*                                                                       */\r\n#undef  FT_SET_ERROR\r\n#define FT_SET_ERROR( expression ) \\\r\n          ( ( error = (expression) ) != 0 )\r\n\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /****                                                                 ****/\r\n  /****                                                                 ****/\r\n  /****                           M E M O R Y                           ****/\r\n  /****                                                                 ****/\r\n  /****                                                                 ****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /*\r\n   *  C++ refuses to handle statements like p = (void*)anything, with `p' a\r\n   *  typed pointer.  Since we don't have a `typeof' operator in standard\r\n   *  C++, we have to use a template to emulate it.\r\n   */\r\n\r\n#ifdef __cplusplus\r\n\r\n  extern \"C++\"\r\n  template <typename T> inline T*\r\n  cplusplus_typeof(        T*,\r\n                    void  *v )\r\n  {\r\n    return static_cast <T*> ( v );\r\n  }\r\n\r\n#define FT_ASSIGNP( p, val )  (p) = cplusplus_typeof( (p), (val) )\r\n\r\n#else\r\n\r\n#define FT_ASSIGNP( p, val )  (p) = (val)\r\n\r\n#endif\r\n\r\n\r\n\r\n#ifdef FT_DEBUG_MEMORY\r\n\r\n  FT_BASE( const char* )  _ft_debug_file;\r\n  FT_BASE( long )         _ft_debug_lineno;\r\n\r\n#define FT_DEBUG_INNER( exp )  ( _ft_debug_file   = __FILE__, \\\r\n                                 _ft_debug_lineno = __LINE__, \\\r\n                                 (exp) )\r\n\r\n#define FT_ASSIGNP_INNER( p, exp )  ( _ft_debug_file   = __FILE__, \\\r\n                                      _ft_debug_lineno = __LINE__, \\\r\n                                      FT_ASSIGNP( p, exp ) )\r\n\r\n#else /* !FT_DEBUG_MEMORY */\r\n\r\n#define FT_DEBUG_INNER( exp )       (exp)\r\n#define FT_ASSIGNP_INNER( p, exp )  FT_ASSIGNP( p, exp )\r\n\r\n#endif /* !FT_DEBUG_MEMORY */\r\n\r\n\r\n  /*\r\n   *  The allocation functions return a pointer, and the error code\r\n   *  is written to through the `p_error' parameter.  See below for\r\n   *  for documentation.\r\n   */\r\n\r\n  FT_BASE( FT_Pointer )\r\n  ft_mem_alloc( FT_Memory  memory,\r\n                FT_Long    size,\r\n                FT_Error  *p_error );\r\n\r\n  FT_BASE( FT_Pointer )\r\n  ft_mem_qalloc( FT_Memory  memory,\r\n                 FT_Long    size,\r\n                 FT_Error  *p_error );\r\n\r\n  FT_BASE( FT_Pointer )\r\n  ft_mem_realloc( FT_Memory  memory,\r\n                  FT_Long    item_size,\r\n                  FT_Long    cur_count,\r\n                  FT_Long    new_count,\r\n                  void*      block,\r\n                  FT_Error  *p_error );\r\n\r\n  FT_BASE( FT_Pointer )\r\n  ft_mem_qrealloc( FT_Memory  memory,\r\n                   FT_Long    item_size,\r\n                   FT_Long    cur_count,\r\n                   FT_Long    new_count,\r\n                   void*      block,\r\n                   FT_Error  *p_error );\r\n\r\n  FT_BASE( void )\r\n  ft_mem_free( FT_Memory    memory,\r\n               const void*  P );\r\n\r\n\r\n#define FT_MEM_ALLOC( ptr, size )                                         \\\r\n          FT_ASSIGNP_INNER( ptr, ft_mem_alloc( memory, (size), &error ) )\r\n\r\n#define FT_MEM_FREE( ptr )                \\\r\n          FT_BEGIN_STMNT                  \\\r\n            ft_mem_free( memory, (ptr) ); \\\r\n            (ptr) = NULL;                 \\\r\n          FT_END_STMNT\r\n\r\n#define FT_MEM_NEW( ptr )                        \\\r\n          FT_MEM_ALLOC( ptr, sizeof ( *(ptr) ) )\r\n\r\n#define FT_MEM_REALLOC( ptr, cursz, newsz )                        \\\r\n          FT_ASSIGNP_INNER( ptr, ft_mem_realloc( memory, 1,        \\\r\n                                                 (cursz), (newsz), \\\r\n                                                 (ptr), &error ) )\r\n\r\n#define FT_MEM_QALLOC( ptr, size )                                         \\\r\n          FT_ASSIGNP_INNER( ptr, ft_mem_qalloc( memory, (size), &error ) )\r\n\r\n#define FT_MEM_QNEW( ptr )                        \\\r\n          FT_MEM_QALLOC( ptr, sizeof ( *(ptr) ) )\r\n\r\n#define FT_MEM_QREALLOC( ptr, cursz, newsz )                         \\\r\n          FT_ASSIGNP_INNER( ptr, ft_mem_qrealloc( memory, 1,        \\\r\n                                                  (cursz), (newsz), \\\r\n                                                  (ptr), &error ) )\r\n\r\n#define FT_MEM_QRENEW_ARRAY( ptr, cursz, newsz )                             \\\r\n          FT_ASSIGNP_INNER( ptr, ft_mem_qrealloc( memory, sizeof ( *(ptr) ), \\\r\n                                                  (cursz), (newsz),          \\\r\n                                                  (ptr), &error ) )\r\n\r\n#define FT_MEM_ALLOC_MULT( ptr, count, item_size )                    \\\r\n          FT_ASSIGNP_INNER( ptr, ft_mem_realloc( memory, (item_size), \\\r\n                                                 0, (count),          \\\r\n                                                 NULL, &error ) )\r\n\r\n#define FT_MEM_REALLOC_MULT( ptr, oldcnt, newcnt, itmsz )            \\\r\n          FT_ASSIGNP_INNER( ptr, ft_mem_realloc( memory, (itmsz),    \\\r\n                                                 (oldcnt), (newcnt), \\\r\n                                                 (ptr), &error ) )\r\n\r\n#define FT_MEM_QALLOC_MULT( ptr, count, item_size )                    \\\r\n          FT_ASSIGNP_INNER( ptr, ft_mem_qrealloc( memory, (item_size), \\\r\n                                                  0, (count),          \\\r\n                                                  NULL, &error ) )\r\n\r\n#define FT_MEM_QREALLOC_MULT( ptr, oldcnt, newcnt, itmsz)             \\\r\n          FT_ASSIGNP_INNER( ptr, ft_mem_qrealloc( memory, (itmsz),    \\\r\n                                                  (oldcnt), (newcnt), \\\r\n                                                  (ptr), &error ) )\r\n\r\n\r\n#define FT_MEM_SET_ERROR( cond )  ( (cond), error != 0 )\r\n\r\n\r\n#define FT_MEM_SET( dest, byte, count )     ft_memset( dest, byte, count )\r\n\r\n#define FT_MEM_COPY( dest, source, count )  ft_memcpy( dest, source, count )\r\n\r\n#define FT_MEM_MOVE( dest, source, count )  ft_memmove( dest, source, count )\r\n\r\n\r\n#define FT_MEM_ZERO( dest, count )  FT_MEM_SET( dest, 0, count )\r\n\r\n#define FT_ZERO( p )                FT_MEM_ZERO( p, sizeof ( *(p) ) )\r\n\r\n\r\n#define FT_ARRAY_ZERO( dest, count )                        \\\r\n          FT_MEM_ZERO( dest, (count) * sizeof ( *(dest) ) )\r\n\r\n#define FT_ARRAY_COPY( dest, source, count )                        \\\r\n          FT_MEM_COPY( dest, source, (count) * sizeof ( *(dest) ) )\r\n\r\n#define FT_ARRAY_MOVE( dest, source, count )                        \\\r\n          FT_MEM_MOVE( dest, source, (count) * sizeof ( *(dest) ) )\r\n\r\n\r\n  /*\r\n   *  Return the maximum number of addressable elements in an array.\r\n   *  We limit ourselves to INT_MAX, rather than UINT_MAX, to avoid\r\n   *  any problems.\r\n   */\r\n#define FT_ARRAY_MAX( ptr )           ( FT_INT_MAX / sizeof ( *(ptr) ) )\r\n\r\n#define FT_ARRAY_CHECK( ptr, count )  ( (count) <= FT_ARRAY_MAX( ptr ) )\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* The following functions macros expect that their pointer argument is  */\r\n  /* _typed_ in order to automatically compute array element sizes.        */\r\n  /*                                                                       */\r\n\r\n#define FT_MEM_NEW_ARRAY( ptr, count )                                      \\\r\n          FT_ASSIGNP_INNER( ptr, ft_mem_realloc( memory, sizeof ( *(ptr) ), \\\r\n                                                 0, (count),                \\\r\n                                                 NULL, &error ) )\r\n\r\n#define FT_MEM_RENEW_ARRAY( ptr, cursz, newsz )                             \\\r\n          FT_ASSIGNP_INNER( ptr, ft_mem_realloc( memory, sizeof ( *(ptr) ), \\\r\n                                                 (cursz), (newsz),          \\\r\n                                                 (ptr), &error ) )\r\n\r\n#define FT_MEM_QNEW_ARRAY( ptr, count )                                      \\\r\n          FT_ASSIGNP_INNER( ptr, ft_mem_qrealloc( memory, sizeof ( *(ptr) ), \\\r\n                                                  0, (count),                \\\r\n                                                  NULL, &error ) )\r\n\r\n#define FT_MEM_QRENEW_ARRAY( ptr, cursz, newsz )                             \\\r\n          FT_ASSIGNP_INNER( ptr, ft_mem_qrealloc( memory, sizeof ( *(ptr) ), \\\r\n                                                  (cursz), (newsz),          \\\r\n                                                  (ptr), &error ) )\r\n\r\n\r\n#define FT_ALLOC( ptr, size )                           \\\r\n          FT_MEM_SET_ERROR( FT_MEM_ALLOC( ptr, size ) )\r\n\r\n#define FT_REALLOC( ptr, cursz, newsz )                           \\\r\n          FT_MEM_SET_ERROR( FT_MEM_REALLOC( ptr, cursz, newsz ) )\r\n\r\n#define FT_ALLOC_MULT( ptr, count, item_size )                           \\\r\n          FT_MEM_SET_ERROR( FT_MEM_ALLOC_MULT( ptr, count, item_size ) )\r\n\r\n#define FT_REALLOC_MULT( ptr, oldcnt, newcnt, itmsz )              \\\r\n          FT_MEM_SET_ERROR( FT_MEM_REALLOC_MULT( ptr, oldcnt,      \\\r\n                                                 newcnt, itmsz ) )\r\n\r\n#define FT_QALLOC( ptr, size )                           \\\r\n          FT_MEM_SET_ERROR( FT_MEM_QALLOC( ptr, size ) )\r\n\r\n#define FT_QREALLOC( ptr, cursz, newsz )                           \\\r\n          FT_MEM_SET_ERROR( FT_MEM_QREALLOC( ptr, cursz, newsz ) )\r\n\r\n#define FT_QALLOC_MULT( ptr, count, item_size )                           \\\r\n          FT_MEM_SET_ERROR( FT_MEM_QALLOC_MULT( ptr, count, item_size ) )\r\n\r\n#define FT_QREALLOC_MULT( ptr, oldcnt, newcnt, itmsz )              \\\r\n          FT_MEM_SET_ERROR( FT_MEM_QREALLOC_MULT( ptr, oldcnt,      \\\r\n                                                  newcnt, itmsz ) )\r\n\r\n#define FT_FREE( ptr )  FT_MEM_FREE( ptr )\r\n\r\n#define FT_NEW( ptr )  FT_MEM_SET_ERROR( FT_MEM_NEW( ptr ) )\r\n\r\n#define FT_NEW_ARRAY( ptr, count )                           \\\r\n          FT_MEM_SET_ERROR( FT_MEM_NEW_ARRAY( ptr, count ) )\r\n\r\n#define FT_RENEW_ARRAY( ptr, curcnt, newcnt )                           \\\r\n          FT_MEM_SET_ERROR( FT_MEM_RENEW_ARRAY( ptr, curcnt, newcnt ) )\r\n\r\n#define FT_QNEW( ptr )                           \\\r\n          FT_MEM_SET_ERROR( FT_MEM_QNEW( ptr ) )\r\n\r\n#define FT_QNEW_ARRAY( ptr, count )                          \\\r\n          FT_MEM_SET_ERROR( FT_MEM_NEW_ARRAY( ptr, count ) )\r\n\r\n#define FT_QRENEW_ARRAY( ptr, curcnt, newcnt )                          \\\r\n          FT_MEM_SET_ERROR( FT_MEM_RENEW_ARRAY( ptr, curcnt, newcnt ) )\r\n\r\n\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n\r\n  FT_BASE( FT_Error )\r\n  FT_Alloc( FT_Memory  memory,\r\n            FT_Long    size,\r\n            void*     *P );\r\n\r\n  FT_BASE( FT_Error )\r\n  FT_QAlloc( FT_Memory  memory,\r\n             FT_Long    size,\r\n             void*     *p );\r\n\r\n  FT_BASE( FT_Error )\r\n  FT_Realloc( FT_Memory  memory,\r\n              FT_Long    current,\r\n              FT_Long    size,\r\n              void*     *P );\r\n\r\n  FT_BASE( FT_Error )\r\n  FT_QRealloc( FT_Memory  memory,\r\n               FT_Long    current,\r\n               FT_Long    size,\r\n               void*     *p );\r\n\r\n  FT_BASE( void )\r\n  FT_Free( FT_Memory  memory,\r\n           void*     *P );\r\n\r\n#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */\r\n\r\n\r\n  FT_BASE( FT_Pointer )\r\n  ft_mem_strdup( FT_Memory    memory,\r\n                 const char*  str,\r\n                 FT_Error    *p_error );\r\n\r\n  FT_BASE( FT_Pointer )\r\n  ft_mem_dup( FT_Memory    memory,\r\n              const void*  address,\r\n              FT_ULong     size,\r\n              FT_Error    *p_error );\r\n\r\n#define FT_MEM_STRDUP( dst, str )                                            \\\r\n          (dst) = (char*)ft_mem_strdup( memory, (const char*)(str), &error )\r\n\r\n#define FT_STRDUP( dst, str )                           \\\r\n          FT_MEM_SET_ERROR( FT_MEM_STRDUP( dst, str ) )\r\n\r\n#define FT_MEM_DUP( dst, address, size )                                    \\\r\n          (dst) = ft_mem_dup( memory, (address), (FT_ULong)(size), &error )\r\n\r\n#define FT_DUP( dst, address, size )                           \\\r\n          FT_MEM_SET_ERROR( FT_MEM_DUP( dst, address, size ) )\r\n\r\n\r\n  /* Return >= 1 if a truncation occurs.            */\r\n  /* Return 0 if the source string fits the buffer. */\r\n  /* This is *not* the same as strlcpy().           */\r\n  FT_BASE( FT_Int )\r\n  ft_mem_strcpyn( char*        dst,\r\n                  const char*  src,\r\n                  FT_ULong     size );\r\n\r\n#define FT_STRCPYN( dst, src, size )                                         \\\r\n          ft_mem_strcpyn( (char*)dst, (const char*)(src), (FT_ULong)(size) )\r\n\r\n /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTMEMORY_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/ftobjs.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftobjs.h                                                               */\r\n/*                                                                         */\r\n/*    The FreeType private base classes (specification).                   */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2008, 2010 by       */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /*  This file contains the definition of all internal FreeType classes.  */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n#ifndef __FTOBJS_H__\r\n#define __FTOBJS_H__\r\n\r\n#include <ft2build.h>\r\n#include FT_RENDER_H\r\n#include FT_SIZES_H\r\n#include FT_LCD_FILTER_H\r\n#include FT_INTERNAL_MEMORY_H\r\n#include FT_INTERNAL_GLYPH_LOADER_H\r\n#include FT_INTERNAL_DRIVER_H\r\n#include FT_INTERNAL_AUTOHINT_H\r\n#include FT_INTERNAL_SERVICE_H\r\n#include FT_INTERNAL_PIC_H\r\n\r\n#ifdef FT_CONFIG_OPTION_INCREMENTAL\r\n#include FT_INCREMENTAL_H\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Some generic definitions.                                             */\r\n  /*                                                                       */\r\n#ifndef TRUE\r\n#define TRUE  1\r\n#endif\r\n\r\n#ifndef FALSE\r\n#define FALSE  0\r\n#endif\r\n\r\n#ifndef NULL\r\n#define NULL  (void*)0\r\n#endif\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* The min and max functions missing in C.  As usual, be careful not to  */\r\n  /* write things like FT_MIN( a++, b++ ) to avoid side effects.           */\r\n  /*                                                                       */\r\n#define FT_MIN( a, b )  ( (a) < (b) ? (a) : (b) )\r\n#define FT_MAX( a, b )  ( (a) > (b) ? (a) : (b) )\r\n\r\n#define FT_ABS( a )     ( (a) < 0 ? -(a) : (a) )\r\n\r\n\r\n#define FT_PAD_FLOOR( x, n )  ( (x) & ~((n)-1) )\r\n#define FT_PAD_ROUND( x, n )  FT_PAD_FLOOR( (x) + ((n)/2), n )\r\n#define FT_PAD_CEIL( x, n )   FT_PAD_FLOOR( (x) + ((n)-1), n )\r\n\r\n#define FT_PIX_FLOOR( x )     ( (x) & ~63 )\r\n#define FT_PIX_ROUND( x )     FT_PIX_FLOOR( (x) + 32 )\r\n#define FT_PIX_CEIL( x )      FT_PIX_FLOOR( (x) + 63 )\r\n\r\n\r\n  /*\r\n   *  Return the highest power of 2 that is <= value; this correspond to\r\n   *  the highest bit in a given 32-bit value.\r\n   */\r\n  FT_BASE( FT_UInt32 )\r\n  ft_highpow2( FT_UInt32  value );\r\n\r\n\r\n  /*\r\n   *  character classification functions -- since these are used to parse\r\n   *  font files, we must not use those in <ctypes.h> which are\r\n   *  locale-dependent\r\n   */\r\n#define  ft_isdigit( x )   ( ( (unsigned)(x) - '0' ) < 10U )\r\n\r\n#define  ft_isxdigit( x )  ( ( (unsigned)(x) - '0' ) < 10U || \\\r\n                             ( (unsigned)(x) - 'a' ) < 6U  || \\\r\n                             ( (unsigned)(x) - 'A' ) < 6U  )\r\n\r\n  /* the next two macros assume ASCII representation */\r\n#define  ft_isupper( x )  ( ( (unsigned)(x) - 'A' ) < 26U )\r\n#define  ft_islower( x )  ( ( (unsigned)(x) - 'a' ) < 26U )\r\n\r\n#define  ft_isalpha( x )  ( ft_isupper( x ) || ft_islower( x ) )\r\n#define  ft_isalnum( x )  ( ft_isdigit( x ) || ft_isalpha( x ) )\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /****                                                                 ****/\r\n  /****                                                                 ****/\r\n  /****                       C H A R M A P S                           ****/\r\n  /****                                                                 ****/\r\n  /****                                                                 ****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n  /* handle to internal charmap object */\r\n  typedef struct FT_CMapRec_*              FT_CMap;\r\n\r\n  /* handle to charmap class structure */\r\n  typedef const struct FT_CMap_ClassRec_*  FT_CMap_Class;\r\n\r\n  /* internal charmap object structure */\r\n  typedef struct  FT_CMapRec_\r\n  {\r\n    FT_CharMapRec  charmap;\r\n    FT_CMap_Class  clazz;\r\n\r\n  } FT_CMapRec;\r\n\r\n  /* typecase any pointer to a charmap handle */\r\n#define FT_CMAP( x )              ((FT_CMap)( x ))\r\n\r\n  /* obvious macros */\r\n#define FT_CMAP_PLATFORM_ID( x )  FT_CMAP( x )->charmap.platform_id\r\n#define FT_CMAP_ENCODING_ID( x )  FT_CMAP( x )->charmap.encoding_id\r\n#define FT_CMAP_ENCODING( x )     FT_CMAP( x )->charmap.encoding\r\n#define FT_CMAP_FACE( x )         FT_CMAP( x )->charmap.face\r\n\r\n\r\n  /* class method definitions */\r\n  typedef FT_Error\r\n  (*FT_CMap_InitFunc)( FT_CMap     cmap,\r\n                       FT_Pointer  init_data );\r\n\r\n  typedef void\r\n  (*FT_CMap_DoneFunc)( FT_CMap  cmap );\r\n\r\n  typedef FT_UInt\r\n  (*FT_CMap_CharIndexFunc)( FT_CMap    cmap,\r\n                            FT_UInt32  char_code );\r\n\r\n  typedef FT_UInt\r\n  (*FT_CMap_CharNextFunc)( FT_CMap     cmap,\r\n                           FT_UInt32  *achar_code );\r\n\r\n  typedef FT_UInt\r\n  (*FT_CMap_CharVarIndexFunc)( FT_CMap    cmap,\r\n                               FT_CMap    unicode_cmap,\r\n                               FT_UInt32  char_code,\r\n                               FT_UInt32  variant_selector );\r\n\r\n  typedef FT_Bool\r\n  (*FT_CMap_CharVarIsDefaultFunc)( FT_CMap    cmap,\r\n                                   FT_UInt32  char_code,\r\n                                   FT_UInt32  variant_selector );\r\n\r\n  typedef FT_UInt32 *\r\n  (*FT_CMap_VariantListFunc)( FT_CMap    cmap,\r\n                              FT_Memory  mem );\r\n\r\n  typedef FT_UInt32 *\r\n  (*FT_CMap_CharVariantListFunc)( FT_CMap    cmap,\r\n                                  FT_Memory  mem,\r\n                                  FT_UInt32  char_code );\r\n\r\n  typedef FT_UInt32 *\r\n  (*FT_CMap_VariantCharListFunc)( FT_CMap    cmap,\r\n                                  FT_Memory  mem,\r\n                                  FT_UInt32  variant_selector );\r\n\r\n\r\n  typedef struct  FT_CMap_ClassRec_\r\n  {\r\n    FT_ULong               size;\r\n    FT_CMap_InitFunc       init;\r\n    FT_CMap_DoneFunc       done;\r\n    FT_CMap_CharIndexFunc  char_index;\r\n    FT_CMap_CharNextFunc   char_next;\r\n\r\n    /* Subsequent entries are special ones for format 14 -- the variant */\r\n    /* selector subtable which behaves like no other                    */\r\n\r\n    FT_CMap_CharVarIndexFunc      char_var_index;\r\n    FT_CMap_CharVarIsDefaultFunc  char_var_default;\r\n    FT_CMap_VariantListFunc       variant_list;\r\n    FT_CMap_CharVariantListFunc   charvariant_list;\r\n    FT_CMap_VariantCharListFunc   variantchar_list;\r\n\r\n  } FT_CMap_ClassRec;\r\n\r\n#ifndef FT_CONFIG_OPTION_PIC\r\n\r\n#define FT_DECLARE_CMAP_CLASS(class_) \\\r\n    FT_CALLBACK_TABLE const FT_CMap_ClassRec class_;\r\n\r\n#define FT_DEFINE_CMAP_CLASS(class_, size_, init_, done_, char_index_,       \\\r\n        char_next_, char_var_index_, char_var_default_, variant_list_,       \\\r\n        charvariant_list_, variantchar_list_)                                \\\r\n  FT_CALLBACK_TABLE_DEF                                                      \\\r\n  const FT_CMap_ClassRec class_ =                                            \\\r\n  {                                                                          \\\r\n    size_, init_, done_, char_index_, char_next_, char_var_index_,           \\\r\n    char_var_default_, variant_list_, charvariant_list_, variantchar_list_   \\\r\n  };\r\n#else /* FT_CONFIG_OPTION_PIC */\r\n\r\n#define FT_DECLARE_CMAP_CLASS(class_) \\\r\n    void FT_Init_Class_##class_( FT_Library library, FT_CMap_ClassRec*  clazz);\r\n\r\n#define FT_DEFINE_CMAP_CLASS(class_, size_, init_, done_, char_index_,       \\\r\n        char_next_, char_var_index_, char_var_default_, variant_list_,       \\\r\n        charvariant_list_, variantchar_list_)                                \\\r\n  void                                                                       \\\r\n  FT_Init_Class_##class_( FT_Library library,                                \\\r\n                          FT_CMap_ClassRec*  clazz)                          \\\r\n  {                                                                          \\\r\n    FT_UNUSED(library);                                                      \\\r\n    clazz->size = size_;                                                     \\\r\n    clazz->init = init_;                                                     \\\r\n    clazz->done = done_;                                                     \\\r\n    clazz->char_index = char_index_;                                         \\\r\n    clazz->char_next = char_next_;                                           \\\r\n    clazz->char_var_index = char_var_index_;                                 \\\r\n    clazz->char_var_default = char_var_default_;                             \\\r\n    clazz->variant_list = variant_list_;                                     \\\r\n    clazz->charvariant_list = charvariant_list_;                             \\\r\n    clazz->variantchar_list = variantchar_list_;                             \\\r\n  } \r\n#endif /* FT_CONFIG_OPTION_PIC */\r\n\r\n  /* create a new charmap and add it to charmap->face */\r\n  FT_BASE( FT_Error )\r\n  FT_CMap_New( FT_CMap_Class  clazz,\r\n               FT_Pointer     init_data,\r\n               FT_CharMap     charmap,\r\n               FT_CMap       *acmap );\r\n\r\n  /* destroy a charmap and remove it from face's list */\r\n  FT_BASE( void )\r\n  FT_CMap_Done( FT_CMap  cmap );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Face_InternalRec                                                */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This structure contains the internal fields of each FT_Face        */\r\n  /*    object.  These fields may change between different releases of     */\r\n  /*    FreeType.                                                          */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    max_points ::                                                      */\r\n  /*      The maximal number of points used to store the vectorial outline */\r\n  /*      of any glyph in this face.  If this value cannot be known in     */\r\n  /*      advance, or if the face isn't scalable, this should be set to 0. */\r\n  /*      Only relevant for scalable formats.                              */\r\n  /*                                                                       */\r\n  /*    max_contours ::                                                    */\r\n  /*      The maximal number of contours used to store the vectorial       */\r\n  /*      outline of any glyph in this face.  If this value cannot be      */\r\n  /*      known in advance, or if the face isn't scalable, this should be  */\r\n  /*      set to 0.  Only relevant for scalable formats.                   */\r\n  /*                                                                       */\r\n  /*    transform_matrix ::                                                */\r\n  /*      A 2x2 matrix of 16.16 coefficients used to transform glyph       */\r\n  /*      outlines after they are loaded from the font.  Only used by the  */\r\n  /*      convenience functions.                                           */\r\n  /*                                                                       */\r\n  /*    transform_delta ::                                                 */\r\n  /*      A translation vector used to transform glyph outlines after they */\r\n  /*      are loaded from the font.  Only used by the convenience          */\r\n  /*      functions.                                                       */\r\n  /*                                                                       */\r\n  /*    transform_flags ::                                                 */\r\n  /*      Some flags used to classify the transform.  Only used by the     */\r\n  /*      convenience functions.                                           */\r\n  /*                                                                       */\r\n  /*    services ::                                                        */\r\n  /*      A cache for frequently used services.  It should be only         */\r\n  /*      accessed with the macro `FT_FACE_LOOKUP_SERVICE'.                */\r\n  /*                                                                       */\r\n  /*    incremental_interface ::                                           */\r\n  /*      If non-null, the interface through which glyph data and metrics  */\r\n  /*      are loaded incrementally for faces that do not provide all of    */\r\n  /*      this data when first opened.  This field exists only if          */\r\n  /*      @FT_CONFIG_OPTION_INCREMENTAL is defined.                        */\r\n  /*                                                                       */\r\n  /*    ignore_unpatented_hinter ::                                        */\r\n  /*      This boolean flag instructs the glyph loader to ignore the       */\r\n  /*      native font hinter, if one is found.  This is exclusively used   */\r\n  /*      in the case when the unpatented hinter is compiled within the    */\r\n  /*      library.                                                         */\r\n  /*                                                                       */\r\n  /*    refcount ::                                                        */\r\n  /*      A counter initialized to~1 at the time an @FT_Face structure is  */\r\n  /*      created.  @FT_Reference_Face increments this counter, and        */\r\n  /*      @FT_Done_Face only destroys a face if the counter is~1,          */\r\n  /*      otherwise it simply decrements it.                               */\r\n  /*                                                                       */\r\n  typedef struct  FT_Face_InternalRec_\r\n  {\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n    FT_UShort           reserved1;\r\n    FT_Short            reserved2;\r\n#endif\r\n    FT_Matrix           transform_matrix;\r\n    FT_Vector           transform_delta;\r\n    FT_Int              transform_flags;\r\n\r\n    FT_ServiceCacheRec  services;\r\n\r\n#ifdef FT_CONFIG_OPTION_INCREMENTAL\r\n    FT_Incremental_InterfaceRec*  incremental_interface;\r\n#endif\r\n\r\n    FT_Bool             ignore_unpatented_hinter;\r\n    FT_UInt             refcount;\r\n\r\n  } FT_Face_InternalRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Slot_InternalRec                                                */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This structure contains the internal fields of each FT_GlyphSlot   */\r\n  /*    object.  These fields may change between different releases of     */\r\n  /*    FreeType.                                                          */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    loader            :: The glyph loader object used to load outlines */\r\n  /*                         into the glyph slot.                          */\r\n  /*                                                                       */\r\n  /*    flags             :: Possible values are zero or                   */\r\n  /*                         FT_GLYPH_OWN_BITMAP.  The latter indicates    */\r\n  /*                         that the FT_GlyphSlot structure owns the      */\r\n  /*                         bitmap buffer.                                */\r\n  /*                                                                       */\r\n  /*    glyph_transformed :: Boolean.  Set to TRUE when the loaded glyph   */\r\n  /*                         must be transformed through a specific        */\r\n  /*                         font transformation.  This is _not_ the same  */\r\n  /*                         as the face transform set through             */\r\n  /*                         FT_Set_Transform().                           */\r\n  /*                                                                       */\r\n  /*    glyph_matrix      :: The 2x2 matrix corresponding to the glyph     */\r\n  /*                         transformation, if necessary.                 */\r\n  /*                                                                       */\r\n  /*    glyph_delta       :: The 2d translation vector corresponding to    */\r\n  /*                         the glyph transformation, if necessary.       */\r\n  /*                                                                       */\r\n  /*    glyph_hints       :: Format-specific glyph hints management.       */\r\n  /*                                                                       */\r\n\r\n#define FT_GLYPH_OWN_BITMAP  0x1\r\n\r\n  typedef struct  FT_Slot_InternalRec_\r\n  {\r\n    FT_GlyphLoader  loader;\r\n    FT_UInt         flags;\r\n    FT_Bool         glyph_transformed;\r\n    FT_Matrix       glyph_matrix;\r\n    FT_Vector       glyph_delta;\r\n    void*           glyph_hints;\r\n\r\n  } FT_GlyphSlot_InternalRec;\r\n\r\n\r\n#if 0\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_Size_InternalRec                                                */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This structure contains the internal fields of each FT_Size        */\r\n  /*    object.  Currently, it's empty.                                    */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n  typedef struct  FT_Size_InternalRec_\r\n  {\r\n    /* empty */\r\n\r\n  } FT_Size_InternalRec;\r\n\r\n#endif\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /****                                                                 ****/\r\n  /****                                                                 ****/\r\n  /****                         M O D U L E S                           ****/\r\n  /****                                                                 ****/\r\n  /****                                                                 ****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_ModuleRec                                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A module object instance.                                          */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    clazz   :: A pointer to the module's class.                        */\r\n  /*                                                                       */\r\n  /*    library :: A handle to the parent library object.                  */\r\n  /*                                                                       */\r\n  /*    memory  :: A handle to the memory manager.                         */\r\n  /*                                                                       */\r\n  /*    generic :: A generic structure for user-level extensibility (?).   */\r\n  /*                                                                       */\r\n  typedef struct  FT_ModuleRec_\r\n  {\r\n    FT_Module_Class*  clazz;\r\n    FT_Library        library;\r\n    FT_Memory         memory;\r\n    FT_Generic        generic;\r\n\r\n  } FT_ModuleRec;\r\n\r\n\r\n  /* typecast an object to a FT_Module */\r\n#define FT_MODULE( x )          ((FT_Module)( x ))\r\n#define FT_MODULE_CLASS( x )    FT_MODULE( x )->clazz\r\n#define FT_MODULE_LIBRARY( x )  FT_MODULE( x )->library\r\n#define FT_MODULE_MEMORY( x )   FT_MODULE( x )->memory\r\n\r\n\r\n#define FT_MODULE_IS_DRIVER( x )  ( FT_MODULE_CLASS( x )->module_flags & \\\r\n                                    FT_MODULE_FONT_DRIVER )\r\n\r\n#define FT_MODULE_IS_RENDERER( x )  ( FT_MODULE_CLASS( x )->module_flags & \\\r\n                                      FT_MODULE_RENDERER )\r\n\r\n#define FT_MODULE_IS_HINTER( x )  ( FT_MODULE_CLASS( x )->module_flags & \\\r\n                                    FT_MODULE_HINTER )\r\n\r\n#define FT_MODULE_IS_STYLER( x )  ( FT_MODULE_CLASS( x )->module_flags & \\\r\n                                    FT_MODULE_STYLER )\r\n\r\n#define FT_DRIVER_IS_SCALABLE( x )  ( FT_MODULE_CLASS( x )->module_flags & \\\r\n                                      FT_MODULE_DRIVER_SCALABLE )\r\n\r\n#define FT_DRIVER_USES_OUTLINES( x )  !( FT_MODULE_CLASS( x )->module_flags & \\\r\n                                         FT_MODULE_DRIVER_NO_OUTLINES )\r\n\r\n#define FT_DRIVER_HAS_HINTER( x )  ( FT_MODULE_CLASS( x )->module_flags & \\\r\n                                     FT_MODULE_DRIVER_HAS_HINTER )\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Get_Module_Interface                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Finds a module and returns its specific interface as a typeless    */\r\n  /*    pointer.                                                           */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    library     :: A handle to the library object.                     */\r\n  /*                                                                       */\r\n  /*    module_name :: The module's name (as an ASCII string).             */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    A module-specific interface if available, 0 otherwise.             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    You should better be familiar with FreeType internals to know      */\r\n  /*    which module to look for, and what its interface is :-)            */\r\n  /*                                                                       */\r\n  FT_BASE( const void* )\r\n  FT_Get_Module_Interface( FT_Library   library,\r\n                           const char*  mod_name );\r\n\r\n  FT_BASE( FT_Pointer )\r\n  ft_module_get_service( FT_Module    module,\r\n                         const char*  service_id );\r\n\r\n /* */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /****                                                                 ****/\r\n  /****                                                                 ****/\r\n  /****               FACE, SIZE & GLYPH SLOT OBJECTS                   ****/\r\n  /****                                                                 ****/\r\n  /****                                                                 ****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n  /* a few macros used to perform easy typecasts with minimal brain damage */\r\n\r\n#define FT_FACE( x )          ((FT_Face)(x))\r\n#define FT_SIZE( x )          ((FT_Size)(x))\r\n#define FT_SLOT( x )          ((FT_GlyphSlot)(x))\r\n\r\n#define FT_FACE_DRIVER( x )   FT_FACE( x )->driver\r\n#define FT_FACE_LIBRARY( x )  FT_FACE_DRIVER( x )->root.library\r\n#define FT_FACE_MEMORY( x )   FT_FACE( x )->memory\r\n#define FT_FACE_STREAM( x )   FT_FACE( x )->stream\r\n\r\n#define FT_SIZE_FACE( x )     FT_SIZE( x )->face\r\n#define FT_SLOT_FACE( x )     FT_SLOT( x )->face\r\n\r\n#define FT_FACE_SLOT( x )     FT_FACE( x )->glyph\r\n#define FT_FACE_SIZE( x )     FT_FACE( x )->size\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_New_GlyphSlot                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    It is sometimes useful to have more than one glyph slot for a      */\r\n  /*    given face object.  This function is used to create additional     */\r\n  /*    slots.  All of them are automatically discarded when the face is   */\r\n  /*    destroyed.                                                         */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face  :: A handle to a parent face object.                         */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    aslot :: A handle to a new glyph slot object.                      */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0 means success.                             */\r\n  /*                                                                       */\r\n  FT_BASE( FT_Error )\r\n  FT_New_GlyphSlot( FT_Face        face,\r\n                    FT_GlyphSlot  *aslot );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Done_GlyphSlot                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Destroys a given glyph slot.  Remember however that all slots are  */\r\n  /*    automatically destroyed with its parent.  Using this function is   */\r\n  /*    not always mandatory.                                              */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    slot :: A handle to a target glyph slot.                           */\r\n  /*                                                                       */\r\n  FT_BASE( void )\r\n  FT_Done_GlyphSlot( FT_GlyphSlot  slot );\r\n\r\n /* */\r\n\r\n#define FT_REQUEST_WIDTH( req )                                            \\\r\n          ( (req)->horiResolution                                          \\\r\n              ? (FT_Pos)( (req)->width * (req)->horiResolution + 36 ) / 72 \\\r\n              : (req)->width )\r\n\r\n#define FT_REQUEST_HEIGHT( req )                                            \\\r\n          ( (req)->vertResolution                                           \\\r\n              ? (FT_Pos)( (req)->height * (req)->vertResolution + 36 ) / 72 \\\r\n              : (req)->height )\r\n\r\n\r\n  /* Set the metrics according to a bitmap strike. */\r\n  FT_BASE( void )\r\n  FT_Select_Metrics( FT_Face   face,\r\n                     FT_ULong  strike_index );\r\n\r\n\r\n  /* Set the metrics according to a size request. */\r\n  FT_BASE( void )\r\n  FT_Request_Metrics( FT_Face          face,\r\n                      FT_Size_Request  req );\r\n\r\n\r\n  /* Match a size request against `available_sizes'. */\r\n  FT_BASE( FT_Error )\r\n  FT_Match_Size( FT_Face          face,\r\n                 FT_Size_Request  req,\r\n                 FT_Bool          ignore_width,\r\n                 FT_ULong*        size_index );\r\n\r\n\r\n  /* Use the horizontal metrics to synthesize the vertical metrics. */\r\n  /* If `advance' is zero, it is also synthesized.                  */\r\n  FT_BASE( void )\r\n  ft_synthesize_vertical_metrics( FT_Glyph_Metrics*  metrics,\r\n                                  FT_Pos             advance );\r\n\r\n\r\n  /* Free the bitmap of a given glyphslot when needed (i.e., only when it */\r\n  /* was allocated with ft_glyphslot_alloc_bitmap).                       */\r\n  FT_BASE( void )\r\n  ft_glyphslot_free_bitmap( FT_GlyphSlot  slot );\r\n\r\n\r\n  /* Allocate a new bitmap buffer in a glyph slot. */\r\n  FT_BASE( FT_Error )\r\n  ft_glyphslot_alloc_bitmap( FT_GlyphSlot  slot,\r\n                             FT_ULong      size );\r\n\r\n\r\n  /* Set the bitmap buffer in a glyph slot to a given pointer.  The buffer */\r\n  /* will not be freed by a later call to ft_glyphslot_free_bitmap.        */\r\n  FT_BASE( void )\r\n  ft_glyphslot_set_bitmap( FT_GlyphSlot  slot,\r\n                           FT_Byte*      buffer );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /****                                                                 ****/\r\n  /****                                                                 ****/\r\n  /****                        R E N D E R E R S                        ****/\r\n  /****                                                                 ****/\r\n  /****                                                                 ****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n#define FT_RENDERER( x )      ((FT_Renderer)( x ))\r\n#define FT_GLYPH( x )         ((FT_Glyph)( x ))\r\n#define FT_BITMAP_GLYPH( x )  ((FT_BitmapGlyph)( x ))\r\n#define FT_OUTLINE_GLYPH( x ) ((FT_OutlineGlyph)( x ))\r\n\r\n\r\n  typedef struct  FT_RendererRec_\r\n  {\r\n    FT_ModuleRec            root;\r\n    FT_Renderer_Class*      clazz;\r\n    FT_Glyph_Format         glyph_format;\r\n    FT_Glyph_Class          glyph_class;\r\n\r\n    FT_Raster               raster;\r\n    FT_Raster_Render_Func   raster_render;\r\n    FT_Renderer_RenderFunc  render;\r\n\r\n  } FT_RendererRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /****                                                                 ****/\r\n  /****                                                                 ****/\r\n  /****                    F O N T   D R I V E R S                      ****/\r\n  /****                                                                 ****/\r\n  /****                                                                 ****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /* typecast a module into a driver easily */\r\n#define FT_DRIVER( x )        ((FT_Driver)(x))\r\n\r\n  /* typecast a module as a driver, and get its driver class */\r\n#define FT_DRIVER_CLASS( x )  FT_DRIVER( x )->clazz\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_DriverRec                                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    The root font driver class.  A font driver is responsible for      */\r\n  /*    managing and loading font files of a given format.                 */\r\n  /*                                                                       */\r\n  /*  <Fields>                                                             */\r\n  /*     root         :: Contains the fields of the root module class.     */\r\n  /*                                                                       */\r\n  /*     clazz        :: A pointer to the font driver's class.  Note that  */\r\n  /*                     this is NOT root.clazz.  `class' wasn't used      */\r\n  /*                     as it is a reserved word in C++.                  */\r\n  /*                                                                       */\r\n  /*     faces_list   :: The list of faces currently opened by this        */\r\n  /*                     driver.                                           */\r\n  /*                                                                       */\r\n  /*     extensions   :: A typeless pointer to the driver's extensions     */\r\n  /*                     registry, if they are supported through the       */\r\n  /*                     configuration macro FT_CONFIG_OPTION_EXTENSIONS.  */\r\n  /*                                                                       */\r\n  /*     glyph_loader :: The glyph loader for all faces managed by this    */\r\n  /*                     driver.  This object isn't defined for unscalable */\r\n  /*                     formats.                                          */\r\n  /*                                                                       */\r\n  typedef struct  FT_DriverRec_\r\n  {\r\n    FT_ModuleRec     root;\r\n    FT_Driver_Class  clazz;\r\n\r\n    FT_ListRec       faces_list;\r\n    void*            extensions;\r\n\r\n    FT_GlyphLoader   glyph_loader;\r\n\r\n  } FT_DriverRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /****                                                                 ****/\r\n  /****                                                                 ****/\r\n  /****                       L I B R A R I E S                         ****/\r\n  /****                                                                 ****/\r\n  /****                                                                 ****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /* This hook is used by the TrueType debugger.  It must be set to an */\r\n  /* alternate truetype bytecode interpreter function.                 */\r\n#define FT_DEBUG_HOOK_TRUETYPE            0\r\n\r\n\r\n  /* Set this debug hook to a non-null pointer to force unpatented hinting */\r\n  /* for all faces when both TT_USE_BYTECODE_INTERPRETER and               */\r\n  /* TT_CONFIG_OPTION_UNPATENTED_HINTING are defined.  This is only used   */\r\n  /* during debugging.                                                     */\r\n#define FT_DEBUG_HOOK_UNPATENTED_HINTING  1\r\n\r\n\r\n  typedef void  (*FT_Bitmap_LcdFilterFunc)( FT_Bitmap*      bitmap,\r\n                                            FT_Render_Mode  render_mode,\r\n                                            FT_Library      library );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    FT_LibraryRec                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    The FreeType library class.  This is the root of all FreeType      */\r\n  /*    data.  Use FT_New_Library() to create a library object, and        */\r\n  /*    FT_Done_Library() to discard it and all child objects.             */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    memory           :: The library's memory object.  Manages memory   */\r\n  /*                        allocation.                                    */\r\n  /*                                                                       */\r\n  /*    generic          :: Client data variable.  Used to extend the      */\r\n  /*                        Library class by higher levels and clients.    */\r\n  /*                                                                       */\r\n  /*    version_major    :: The major version number of the library.       */\r\n  /*                                                                       */\r\n  /*    version_minor    :: The minor version number of the library.       */\r\n  /*                                                                       */\r\n  /*    version_patch    :: The current patch level of the library.        */\r\n  /*                                                                       */\r\n  /*    num_modules      :: The number of modules currently registered     */\r\n  /*                        within this library.  This is set to 0 for new */\r\n  /*                        libraries.  New modules are added through the  */\r\n  /*                        FT_Add_Module() API function.                  */\r\n  /*                                                                       */\r\n  /*    modules          :: A table used to store handles to the currently */\r\n  /*                        registered modules. Note that each font driver */\r\n  /*                        contains a list of its opened faces.           */\r\n  /*                                                                       */\r\n  /*    renderers        :: The list of renderers currently registered     */\r\n  /*                        within the library.                            */\r\n  /*                                                                       */\r\n  /*    cur_renderer     :: The current outline renderer.  This is a       */\r\n  /*                        shortcut used to avoid parsing the list on     */\r\n  /*                        each call to FT_Outline_Render().  It is a     */\r\n  /*                        handle to the current renderer for the         */\r\n  /*                        FT_GLYPH_FORMAT_OUTLINE format.                */\r\n  /*                                                                       */\r\n  /*    auto_hinter      :: XXX                                            */\r\n  /*                                                                       */\r\n  /*    raster_pool      :: The raster object's render pool.  This can     */\r\n  /*                        ideally be changed dynamically at run-time.    */\r\n  /*                                                                       */\r\n  /*    raster_pool_size :: The size of the render pool in bytes.          */\r\n  /*                                                                       */\r\n  /*    debug_hooks      :: XXX                                            */\r\n  /*                                                                       */\r\n  /*    lcd_filter       :: If subpixel rendering is activated, the        */\r\n  /*                        selected LCD filter mode.                      */\r\n  /*                                                                       */\r\n  /*    lcd_extra        :: If subpixel rendering is activated, the number */\r\n  /*                        of extra pixels needed for the LCD filter.     */\r\n  /*                                                                       */\r\n  /*    lcd_weights      :: If subpixel rendering is activated, the LCD    */\r\n  /*                        filter weights, if any.                        */\r\n  /*                                                                       */\r\n  /*    lcd_filter_func  :: If subpixel rendering is activated, the LCD    */\r\n  /*                        filtering callback function.                   */\r\n  /*                                                                       */\r\n  /*    pic_container    :: Contains global structs and tables, instead    */\r\n  /*                        of defining them globallly.                    */\r\n  /*                                                                       */\r\n  /*    refcount         :: A counter initialized to~1 at the time an      */\r\n  /*                        @FT_Library structure is created.              */\r\n  /*                        @FT_Reference_Library increments this counter, */\r\n  /*                        and @FT_Done_Library only destroys a library   */\r\n  /*                        if the counter is~1, otherwise it simply       */\r\n  /*                        decrements it.                                 */\r\n  /*                                                                       */\r\n  typedef struct  FT_LibraryRec_\r\n  {\r\n    FT_Memory          memory;           /* library's memory manager */\r\n\r\n    FT_Generic         generic;\r\n\r\n    FT_Int             version_major;\r\n    FT_Int             version_minor;\r\n    FT_Int             version_patch;\r\n\r\n    FT_UInt            num_modules;\r\n    FT_Module          modules[FT_MAX_MODULES];  /* module objects  */\r\n\r\n    FT_ListRec         renderers;        /* list of renderers        */\r\n    FT_Renderer        cur_renderer;     /* current outline renderer */\r\n    FT_Module          auto_hinter;\r\n\r\n    FT_Byte*           raster_pool;      /* scan-line conversion */\r\n                                         /* render pool          */\r\n    FT_ULong           raster_pool_size; /* size of render pool in bytes */\r\n\r\n    FT_DebugHook_Func  debug_hooks[4];\r\n\r\n#ifdef FT_CONFIG_OPTION_SUBPIXEL_RENDERING\r\n    FT_LcdFilter             lcd_filter;\r\n    FT_Int                   lcd_extra;        /* number of extra pixels */\r\n    FT_Byte                  lcd_weights[7];   /* filter weights, if any */\r\n    FT_Bitmap_LcdFilterFunc  lcd_filter_func;  /* filtering callback     */\r\n#endif\r\n\r\n#ifdef FT_CONFIG_OPTION_PIC\r\n    FT_PIC_Container   pic_container;\r\n#endif\r\n\r\n    FT_UInt            refcount;\r\n\r\n  } FT_LibraryRec;\r\n\r\n\r\n  FT_BASE( FT_Renderer )\r\n  FT_Lookup_Renderer( FT_Library       library,\r\n                      FT_Glyph_Format  format,\r\n                      FT_ListNode*     node );\r\n\r\n  FT_BASE( FT_Error )\r\n  FT_Render_Glyph_Internal( FT_Library      library,\r\n                            FT_GlyphSlot    slot,\r\n                            FT_Render_Mode  render_mode );\r\n\r\n  typedef const char*\r\n  (*FT_Face_GetPostscriptNameFunc)( FT_Face  face );\r\n\r\n  typedef FT_Error\r\n  (*FT_Face_GetGlyphNameFunc)( FT_Face     face,\r\n                               FT_UInt     glyph_index,\r\n                               FT_Pointer  buffer,\r\n                               FT_UInt     buffer_max );\r\n\r\n  typedef FT_UInt\r\n  (*FT_Face_GetGlyphNameIndexFunc)( FT_Face     face,\r\n                                    FT_String*  glyph_name );\r\n\r\n\r\n#ifndef FT_CONFIG_OPTION_NO_DEFAULT_SYSTEM\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_New_Memory                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Creates a new memory object.                                       */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    A pointer to the new memory object.  0 in case of error.           */\r\n  /*                                                                       */\r\n  FT_BASE( FT_Memory )\r\n  FT_New_Memory( void );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Done_Memory                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Discards memory manager.                                           */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    memory :: A handle to the memory manager.                          */\r\n  /*                                                                       */\r\n  FT_BASE( void )\r\n  FT_Done_Memory( FT_Memory  memory );\r\n\r\n#endif /* !FT_CONFIG_OPTION_NO_DEFAULT_SYSTEM */\r\n\r\n\r\n  /* Define default raster's interface.  The default raster is located in  */\r\n  /* `src/base/ftraster.c'.                                                */\r\n  /*                                                                       */\r\n  /* Client applications can register new rasters through the              */\r\n  /* FT_Set_Raster() API.                                                  */\r\n\r\n#ifndef FT_NO_DEFAULT_RASTER\r\n  FT_EXPORT_VAR( FT_Raster_Funcs )  ft_default_raster;\r\n#endif\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /****                                                                 ****/\r\n  /****                                                                 ****/\r\n  /****              PIC-Support Macros for ftimage.h                   ****/\r\n  /****                                                                 ****/\r\n  /****                                                                 ****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Macro>                                                               */\r\n  /*    FT_DEFINE_OUTLINE_FUNCS                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Used to initialize an instance of FT_Outline_Funcs struct.         */\r\n  /*    When FT_CONFIG_OPTION_PIC is defined an init funtion will need to  */\r\n  /*    called with a pre-allocated stracture to be filled.                */\r\n  /*    When FT_CONFIG_OPTION_PIC is not defined the struct will be        */\r\n  /*    allocated in the global scope (or the scope where the macro        */\r\n  /*    is used).                                                          */\r\n  /*                                                                       */\r\n#ifndef FT_CONFIG_OPTION_PIC\r\n\r\n#define FT_DEFINE_OUTLINE_FUNCS(class_, move_to_, line_to_, conic_to_,       \\\r\n                                cubic_to_, shift_, delta_)                   \\\r\n  static const FT_Outline_Funcs class_ =                                     \\\r\n  {                                                                          \\\r\n    move_to_, line_to_, conic_to_, cubic_to_, shift_, delta_                 \\\r\n  };\r\n\r\n#else /* FT_CONFIG_OPTION_PIC */ \r\n\r\n#define FT_DEFINE_OUTLINE_FUNCS(class_, move_to_, line_to_, conic_to_,       \\\r\n                                cubic_to_, shift_, delta_)                   \\\r\n  static FT_Error                                                            \\\r\n  Init_Class_##class_( FT_Outline_Funcs*  clazz )                            \\\r\n  {                                                                          \\\r\n    clazz->move_to = move_to_;                                               \\\r\n    clazz->line_to = line_to_;                                               \\\r\n    clazz->conic_to = conic_to_;                                             \\\r\n    clazz->cubic_to = cubic_to_;                                             \\\r\n    clazz->shift = shift_;                                                   \\\r\n    clazz->delta = delta_;                                                   \\\r\n    return FT_Err_Ok;                                                        \\\r\n  } \r\n\r\n#endif /* FT_CONFIG_OPTION_PIC */ \r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Macro>                                                               */\r\n  /*    FT_DEFINE_RASTER_FUNCS                                             */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Used to initialize an instance of FT_Raster_Funcs struct.          */\r\n  /*    When FT_CONFIG_OPTION_PIC is defined an init funtion will need to  */\r\n  /*    called with a pre-allocated stracture to be filled.                */\r\n  /*    When FT_CONFIG_OPTION_PIC is not defined the struct will be        */\r\n  /*    allocated in the global scope (or the scope where the macro        */\r\n  /*    is used).                                                          */\r\n  /*                                                                       */\r\n#ifndef FT_CONFIG_OPTION_PIC\r\n\r\n#define FT_DEFINE_RASTER_FUNCS(class_, glyph_format_, raster_new_,           \\\r\n                               raster_reset_, raster_set_mode_,              \\\r\n                               raster_render_, raster_done_)                 \\\r\n  const FT_Raster_Funcs class_ =                                      \\\r\n  {                                                                          \\\r\n    glyph_format_, raster_new_, raster_reset_,                               \\\r\n    raster_set_mode_, raster_render_, raster_done_                           \\\r\n  };\r\n\r\n#else /* FT_CONFIG_OPTION_PIC */ \r\n\r\n#define FT_DEFINE_RASTER_FUNCS(class_, glyph_format_, raster_new_,           \\\r\n    raster_reset_, raster_set_mode_, raster_render_, raster_done_)           \\\r\n  void                                                                       \\\r\n  FT_Init_Class_##class_( FT_Raster_Funcs*  clazz )                          \\\r\n  {                                                                          \\\r\n    clazz->glyph_format = glyph_format_;                                     \\\r\n    clazz->raster_new = raster_new_;                                         \\\r\n    clazz->raster_reset = raster_reset_;                                     \\\r\n    clazz->raster_set_mode = raster_set_mode_;                               \\\r\n    clazz->raster_render = raster_render_;                                   \\\r\n    clazz->raster_done = raster_done_;                                       \\\r\n  } \r\n\r\n#endif /* FT_CONFIG_OPTION_PIC */ \r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /****                                                                 ****/\r\n  /****                                                                 ****/\r\n  /****              PIC-Support Macros for ftrender.h                  ****/\r\n  /****                                                                 ****/\r\n  /****                                                                 ****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Macro>                                                               */\r\n  /*    FT_DEFINE_GLYPH                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Used to initialize an instance of FT_Glyph_Class struct.           */\r\n  /*    When FT_CONFIG_OPTION_PIC is defined an init funtion will need to  */\r\n  /*    called with a pre-allocated stracture to be filled.                */\r\n  /*    When FT_CONFIG_OPTION_PIC is not defined the struct will be        */\r\n  /*    allocated in the global scope (or the scope where the macro        */\r\n  /*    is used).                                                          */\r\n  /*                                                                       */\r\n#ifndef FT_CONFIG_OPTION_PIC\r\n\r\n#define FT_DEFINE_GLYPH(class_, size_, format_, init_, done_, copy_,         \\\r\n                        transform_, bbox_, prepare_)                         \\\r\n  FT_CALLBACK_TABLE_DEF                                                      \\\r\n  const FT_Glyph_Class class_ =                                              \\\r\n  {                                                                          \\\r\n    size_, format_, init_, done_, copy_, transform_, bbox_, prepare_         \\\r\n  };\r\n\r\n#else /* FT_CONFIG_OPTION_PIC */ \r\n\r\n#define FT_DEFINE_GLYPH(class_, size_, format_, init_, done_, copy_,         \\\r\n                        transform_, bbox_, prepare_)                         \\\r\n  void                                                                       \\\r\n  FT_Init_Class_##class_( FT_Glyph_Class*  clazz )                           \\\r\n  {                                                                          \\\r\n    clazz->glyph_size = size_;                                               \\\r\n    clazz->glyph_format = format_;                                           \\\r\n    clazz->glyph_init = init_;                                               \\\r\n    clazz->glyph_done = done_;                                               \\\r\n    clazz->glyph_copy = copy_;                                               \\\r\n    clazz->glyph_transform = transform_;                                     \\\r\n    clazz->glyph_bbox = bbox_;                                               \\\r\n    clazz->glyph_prepare = prepare_;                                         \\\r\n  } \r\n\r\n#endif /* FT_CONFIG_OPTION_PIC */ \r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Macro>                                                               */\r\n  /*    FT_DECLARE_RENDERER                                                */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Used to create a forward declaration of a                          */\r\n  /*    FT_Renderer_Class stract instance.                                 */\r\n  /*                                                                       */\r\n  /* <Macro>                                                               */\r\n  /*    FT_DEFINE_RENDERER                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Used to initialize an instance of FT_Renderer_Class struct.        */\r\n  /*                                                                       */\r\n  /*    When FT_CONFIG_OPTION_PIC is defined a Create funtion will need    */\r\n  /*    to called with a pointer where the allocated stracture is returned.*/\r\n  /*    And when it is no longer needed a Destroy function needs           */\r\n  /*    to be called to release that allocation.                           */\r\n  /*    fcinit.c (ft_create_default_module_classes) already contains       */\r\n  /*    a mechanism to call these functions for the default modules        */\r\n  /*    described in ftmodule.h                                            */\r\n  /*                                                                       */\r\n  /*    Notice that the created Create and Destroy functions call          */\r\n  /*    pic_init and pic_free function to allow you to manually allocate   */\r\n  /*    and initialize any additional global data, like module specific    */\r\n  /*    interface, and put them in the global pic container defined in     */\r\n  /*    ftpic.h. if you don't need them just implement the functions as    */\r\n  /*    empty to resolve the link error.                                   */\r\n  /*                                                                       */\r\n  /*    When FT_CONFIG_OPTION_PIC is not defined the struct will be        */\r\n  /*    allocated in the global scope (or the scope where the macro        */\r\n  /*    is used).                                                          */\r\n  /*                                                                       */\r\n#ifndef FT_CONFIG_OPTION_PIC\r\n\r\n#define FT_DECLARE_RENDERER(class_)                                          \\\r\n    FT_EXPORT_VAR( const FT_Renderer_Class ) class_;\r\n\r\n#define FT_DEFINE_RENDERER(class_,                                           \\\r\n                           flags_, size_, name_, version_, requires_,        \\\r\n                           interface_, init_, done_, get_interface_,         \\\r\n                           glyph_format_, render_glyph_, transform_glyph_,   \\\r\n                           get_glyph_cbox_, set_mode_, raster_class_ )       \\\r\n  FT_CALLBACK_TABLE_DEF                                                      \\\r\n  const FT_Renderer_Class  class_ =                                          \\\r\n  {                                                                          \\\r\n    FT_DEFINE_ROOT_MODULE(flags_,size_,name_,version_,requires_,             \\\r\n                          interface_,init_,done_,get_interface_)             \\\r\n    glyph_format_,                                                           \\\r\n                                                                             \\\r\n    render_glyph_,                                                           \\\r\n    transform_glyph_,                                                        \\\r\n    get_glyph_cbox_,                                                         \\\r\n    set_mode_,                                                               \\\r\n                                                                             \\\r\n    raster_class_                                                            \\\r\n  };\r\n\r\n#else /* FT_CONFIG_OPTION_PIC */ \r\n\r\n#define FT_DECLARE_RENDERER(class_)  FT_DECLARE_MODULE(class_)\r\n\r\n#define FT_DEFINE_RENDERER(class_, \\\r\n                           flags_, size_, name_, version_, requires_,        \\\r\n                           interface_, init_, done_, get_interface_,         \\\r\n                           glyph_format_, render_glyph_, transform_glyph_,   \\\r\n                           get_glyph_cbox_, set_mode_, raster_class_ )       \\\r\n  void class_##_pic_free( FT_Library library );                              \\\r\n  FT_Error class_##_pic_init( FT_Library library );                          \\\r\n                                                                             \\\r\n  void                                                                       \\\r\n  FT_Destroy_Class_##class_( FT_Library        library,                      \\\r\n                        FT_Module_Class*  clazz )                            \\\r\n  {                                                                          \\\r\n    FT_Renderer_Class* rclazz = (FT_Renderer_Class*)clazz;                   \\\r\n    FT_Memory         memory = library->memory;                              \\\r\n    class_##_pic_free( library );                                            \\\r\n    if ( rclazz )                                                            \\\r\n      FT_FREE( rclazz );                                                     \\\r\n  }                                                                          \\\r\n                                                                             \\\r\n  FT_Error                                                                   \\\r\n  FT_Create_Class_##class_( FT_Library         library,                      \\\r\n                            FT_Module_Class**  output_class )                \\\r\n  {                                                                          \\\r\n    FT_Renderer_Class*  clazz;                                               \\\r\n    FT_Error            error;                                               \\\r\n    FT_Memory           memory = library->memory;                            \\\r\n                                                                             \\\r\n    if ( FT_ALLOC( clazz, sizeof(*clazz) ) )                                 \\\r\n      return error;                                                          \\\r\n                                                                             \\\r\n    error = class_##_pic_init( library );                                    \\\r\n    if(error)                                                                \\\r\n    {                                                                        \\\r\n      FT_FREE( clazz );                                                      \\\r\n      return error;                                                          \\\r\n    }                                                                        \\\r\n                                                                             \\\r\n    FT_DEFINE_ROOT_MODULE(flags_,size_,name_,version_,requires_,             \\\r\n                          interface_,init_,done_,get_interface_)             \\\r\n                                                                             \\\r\n    clazz->glyph_format       = glyph_format_;                               \\\r\n                                                                             \\\r\n    clazz->render_glyph       = render_glyph_;                               \\\r\n    clazz->transform_glyph    = transform_glyph_;                            \\\r\n    clazz->get_glyph_cbox     = get_glyph_cbox_;                             \\\r\n    clazz->set_mode           = set_mode_;                                   \\\r\n                                                                             \\\r\n    clazz->raster_class       = raster_class_;                               \\\r\n                                                                             \\\r\n    *output_class = (FT_Module_Class*)clazz;                                 \\\r\n    return FT_Err_Ok;                                                        \\\r\n  } \r\n\r\n\r\n\r\n#endif /* FT_CONFIG_OPTION_PIC */ \r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /****                                                                 ****/\r\n  /****                                                                 ****/\r\n  /****              PIC-Support Macros for ftmodapi.h                  ****/\r\n  /****                                                                 ****/\r\n  /****                                                                 ****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n#ifdef FT_CONFIG_OPTION_PIC\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_Module_Creator                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A function used to create (allocate) a new module class object.    */\r\n  /*    The object's members are initialized, but the module itself is     */\r\n  /*    not.                                                               */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    memory       :: A handle to the memory manager.                    */\r\n  /*    output_class :: Initialized with the newly allocated class.        */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*FT_Module_Creator)( FT_Memory          memory,\r\n                        FT_Module_Class**  output_class );\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    FT_Module_Destroyer                                                */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A function used to destroy (deallocate) a module class object.     */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    memory :: A handle to the memory manager.                          */\r\n  /*    clazz  :: Module class to destroy.                                 */\r\n  /*                                                                       */\r\n  typedef void\r\n  (*FT_Module_Destroyer)( FT_Memory         memory,\r\n                          FT_Module_Class*  clazz );\r\n\r\n#endif\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Macro>                                                               */\r\n  /*    FT_DECLARE_MODULE                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Used to create a forward declaration of a                          */\r\n  /*    FT_Module_Class stract instance.                                   */\r\n  /*                                                                       */\r\n  /* <Macro>                                                               */\r\n  /*    FT_DEFINE_MODULE                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Used to initialize an instance of FT_Module_Class struct.          */\r\n  /*                                                                       */\r\n  /*    When FT_CONFIG_OPTION_PIC is defined a Create funtion will need    */\r\n  /*    to called with a pointer where the allocated stracture is returned.*/\r\n  /*    And when it is no longer needed a Destroy function needs           */\r\n  /*    to be called to release that allocation.                           */\r\n  /*    fcinit.c (ft_create_default_module_classes) already contains       */\r\n  /*    a mechanism to call these functions for the default modules        */\r\n  /*    described in ftmodule.h                                            */\r\n  /*                                                                       */\r\n  /*    Notice that the created Create and Destroy functions call          */\r\n  /*    pic_init and pic_free function to allow you to manually allocate   */\r\n  /*    and initialize any additional global data, like module specific    */\r\n  /*    interface, and put them in the global pic container defined in     */\r\n  /*    ftpic.h. if you don't need them just implement the functions as    */\r\n  /*    empty to resolve the link error.                                   */\r\n  /*                                                                       */\r\n  /*    When FT_CONFIG_OPTION_PIC is not defined the struct will be        */\r\n  /*    allocated in the global scope (or the scope where the macro        */\r\n  /*    is used).                                                          */\r\n  /*                                                                       */\r\n  /* <Macro>                                                               */\r\n  /*    FT_DEFINE_ROOT_MODULE                                              */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Used to initialize an instance of FT_Module_Class struct inside    */\r\n  /*    another stract that contains it or in a function that initializes  */\r\n  /*    that containing stract                                             */\r\n  /*                                                                       */\r\n#ifndef FT_CONFIG_OPTION_PIC\r\n\r\n#define FT_DECLARE_MODULE(class_)                                            \\\r\n  FT_CALLBACK_TABLE                                                          \\\r\n  const FT_Module_Class  class_;                                             \\\r\n\r\n#define FT_DEFINE_ROOT_MODULE(flags_, size_, name_, version_, requires_,     \\\r\n                              interface_, init_, done_, get_interface_)      \\\r\n  {                                                                          \\\r\n    flags_,                                                                  \\\r\n    size_,                                                                   \\\r\n                                                                             \\\r\n    name_,                                                                   \\\r\n    version_,                                                                \\\r\n    requires_,                                                               \\\r\n                                                                             \\\r\n    interface_,                                                              \\\r\n                                                                             \\\r\n    init_,                                                                   \\\r\n    done_,                                                                   \\\r\n    get_interface_,                                                          \\\r\n  },\r\n\r\n#define FT_DEFINE_MODULE(class_, flags_, size_, name_, version_, requires_,  \\\r\n                         interface_, init_, done_, get_interface_)           \\\r\n  FT_CALLBACK_TABLE_DEF                                                      \\\r\n  const FT_Module_Class class_ =                                             \\\r\n  {                                                                          \\\r\n    flags_,                                                                  \\\r\n    size_,                                                                   \\\r\n                                                                             \\\r\n    name_,                                                                   \\\r\n    version_,                                                                \\\r\n    requires_,                                                               \\\r\n                                                                             \\\r\n    interface_,                                                              \\\r\n                                                                             \\\r\n    init_,                                                                   \\\r\n    done_,                                                                   \\\r\n    get_interface_,                                                          \\\r\n  };\r\n\r\n\r\n#else /* FT_CONFIG_OPTION_PIC */\r\n\r\n#define FT_DECLARE_MODULE(class_)                                            \\\r\n  FT_Error FT_Create_Class_##class_( FT_Library library,                     \\\r\n                                     FT_Module_Class** output_class );       \\\r\n  void     FT_Destroy_Class_##class_( FT_Library library,                    \\\r\n                                      FT_Module_Class*  clazz );\r\n\r\n#define FT_DEFINE_ROOT_MODULE(flags_, size_, name_, version_, requires_,     \\\r\n                              interface_, init_, done_, get_interface_)      \\\r\n    clazz->root.module_flags       = flags_;                                 \\\r\n    clazz->root.module_size        = size_;                                  \\\r\n    clazz->root.module_name        = name_;                                  \\\r\n    clazz->root.module_version     = version_;                               \\\r\n    clazz->root.module_requires    = requires_;                              \\\r\n                                                                             \\\r\n    clazz->root.module_interface   = interface_;                             \\\r\n                                                                             \\\r\n    clazz->root.module_init        = init_;                                  \\\r\n    clazz->root.module_done        = done_;                                  \\\r\n    clazz->root.get_interface      = get_interface_;               \r\n\r\n#define FT_DEFINE_MODULE(class_, flags_, size_, name_, version_, requires_,  \\\r\n                         interface_, init_, done_, get_interface_)           \\\r\n  void class_##_pic_free( FT_Library library );                              \\\r\n  FT_Error class_##_pic_init( FT_Library library );                          \\\r\n                                                                             \\\r\n  void                                                                       \\\r\n  FT_Destroy_Class_##class_( FT_Library library,                             \\\r\n                             FT_Module_Class*  clazz )                       \\\r\n  {                                                                          \\\r\n    FT_Memory memory = library->memory;                                      \\\r\n    class_##_pic_free( library );                                            \\\r\n    if ( clazz )                                                             \\\r\n      FT_FREE( clazz );                                                      \\\r\n  }                                                                          \\\r\n                                                                             \\\r\n  FT_Error                                                                   \\\r\n  FT_Create_Class_##class_( FT_Library library,                              \\\r\n                            FT_Module_Class**  output_class )                \\\r\n  {                                                                          \\\r\n    FT_Memory memory = library->memory;                                      \\\r\n    FT_Module_Class*  clazz;                                                 \\\r\n    FT_Error          error;                                                 \\\r\n                                                                             \\\r\n    if ( FT_ALLOC( clazz, sizeof(*clazz) ) )                                 \\\r\n      return error;                                                          \\\r\n    error = class_##_pic_init( library );                                    \\\r\n    if(error)                                                                \\\r\n    {                                                                        \\\r\n      FT_FREE( clazz );                                                      \\\r\n      return error;                                                          \\\r\n    }                                                                        \\\r\n                                                                             \\\r\n    clazz->module_flags       = flags_;                                      \\\r\n    clazz->module_size        = size_;                                       \\\r\n    clazz->module_name        = name_;                                       \\\r\n    clazz->module_version     = version_;                                    \\\r\n    clazz->module_requires    = requires_;                                   \\\r\n                                                                             \\\r\n    clazz->module_interface   = interface_;                                  \\\r\n                                                                             \\\r\n    clazz->module_init        = init_;                                       \\\r\n    clazz->module_done        = done_;                                       \\\r\n    clazz->get_interface      = get_interface_;                              \\\r\n                                                                             \\\r\n    *output_class = clazz;                                                   \\\r\n    return FT_Err_Ok;                                                        \\\r\n  } \r\n\r\n#endif /* FT_CONFIG_OPTION_PIC */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTOBJS_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/ftpic.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftpic.h                                                                */\r\n/*                                                                         */\r\n/*    The FreeType position independent code services (declaration).       */\r\n/*                                                                         */\r\n/*  Copyright 2009 by                                                      */\r\n/*  Oran Agra and Mickey Gabel.                                            */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /*  Modules that ordinarily have const global data that need address     */\r\n  /*  can instead define pointers here.                                    */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n#ifndef __FTPIC_H__\r\n#define __FTPIC_H__\r\n\r\n  \r\nFT_BEGIN_HEADER\r\n\r\n#ifdef FT_CONFIG_OPTION_PIC\r\n\r\n  typedef struct FT_PIC_Container_\r\n  {\r\n    /* pic containers for base */\r\n    void* base;\r\n    /* pic containers for modules */\r\n    void* autofit;   \r\n    void* cff;    \r\n    void* pshinter;    \r\n    void* psnames;    \r\n    void* raster;     \r\n    void* sfnt;     \r\n    void* smooth;     \r\n    void* truetype;     \r\n  } FT_PIC_Container;\r\n\r\n  /* Initialize the various function tables, structs, etc. stored in the container. */\r\n  FT_BASE( FT_Error )\r\n  ft_pic_container_init( FT_Library library );\r\n\r\n\r\n  /* Destroy the contents of the container. */\r\n  FT_BASE( void )\r\n  ft_pic_container_destroy( FT_Library library );\r\n\r\n#endif /* FT_CONFIG_OPTION_PIC */\r\n\r\n /* */\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTPIC_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/ftrfork.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftrfork.h                                                              */\r\n/*                                                                         */\r\n/*    Embedded resource forks accessor (specification).                    */\r\n/*                                                                         */\r\n/*  Copyright 2004, 2006, 2007 by                                          */\r\n/*  Masatake YAMATO and Redhat K.K.                                        */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n/***************************************************************************/\r\n/* Development of the code in this file is support of                      */\r\n/* Information-technology Promotion Agency, Japan.                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTRFORK_H__\r\n#define __FTRFORK_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_INTERNAL_OBJECTS_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /* Number of guessing rules supported in `FT_Raccess_Guess'.            */\r\n  /* Don't forget to increment the number if you add a new guessing rule. */\r\n#define FT_RACCESS_N_RULES  9\r\n\r\n\r\n  /* A structure to describe a reference in a resource by its resource ID */\r\n  /* and internal offset.  The `POST' resource expects to be concatenated */\r\n  /* by the order of resource IDs instead of its appearance in the file.  */\r\n\r\n  typedef struct  FT_RFork_Ref_\r\n  {\r\n    FT_UShort  res_id;\r\n    FT_ULong   offset;\r\n\r\n  } FT_RFork_Ref;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Raccess_Guess                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Guess a file name and offset where the actual resource fork is     */\r\n  /*    stored.  The macro FT_RACCESS_N_RULES holds the number of          */\r\n  /*    guessing rules;  the guessed result for the Nth rule is            */\r\n  /*    represented as a triplet: a new file name (new_names[N]), a file   */\r\n  /*    offset (offsets[N]), and an error code (errors[N]).                */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    library ::                                                         */\r\n  /*      A FreeType library instance.                                     */\r\n  /*                                                                       */\r\n  /*    stream ::                                                          */\r\n  /*      A file stream containing the resource fork.                      */\r\n  /*                                                                       */\r\n  /*    base_name ::                                                       */\r\n  /*      The (base) file name of the resource fork used for some          */\r\n  /*      guessing rules.                                                  */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    new_names ::                                                       */\r\n  /*      An array of guessed file names in which the resource forks may   */\r\n  /*      exist.  If `new_names[N]' is NULL, the guessed file name is      */\r\n  /*      equal to `base_name'.                                            */\r\n  /*                                                                       */\r\n  /*    offsets ::                                                         */\r\n  /*      An array of guessed file offsets.  `offsets[N]' holds the file   */\r\n  /*      offset of the possible start of the resource fork in file        */\r\n  /*      `new_names[N]'.                                                  */\r\n  /*                                                                       */\r\n  /*    errors ::                                                          */\r\n  /*      An array of FreeType error codes.  `errors[N]' is the error      */\r\n  /*      code of Nth guessing rule function.  If `errors[N]' is not       */\r\n  /*      FT_Err_Ok, `new_names[N]' and `offsets[N]' are meaningless.      */\r\n  /*                                                                       */\r\n  FT_BASE( void )\r\n  FT_Raccess_Guess( FT_Library  library,\r\n                    FT_Stream   stream,\r\n                    char*       base_name,\r\n                    char**      new_names,\r\n                    FT_Long*    offsets,\r\n                    FT_Error*   errors );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Raccess_Get_HeaderInfo                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Get the information from the header of resource fork.  The         */\r\n  /*    information includes the file offset where the resource map        */\r\n  /*    starts, and the file offset where the resource data starts.        */\r\n  /*    `FT_Raccess_Get_DataOffsets' requires these two data.              */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    library ::                                                         */\r\n  /*      A FreeType library instance.                                     */\r\n  /*                                                                       */\r\n  /*    stream ::                                                          */\r\n  /*      A file stream containing the resource fork.                      */\r\n  /*                                                                       */\r\n  /*    rfork_offset ::                                                    */\r\n  /*      The file offset where the resource fork starts.                  */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    map_offset ::                                                      */\r\n  /*      The file offset where the resource map starts.                   */\r\n  /*                                                                       */\r\n  /*    rdata_pos ::                                                       */\r\n  /*      The file offset where the resource data starts.                  */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  FT_Err_Ok means success.                     */\r\n  /*                                                                       */\r\n  FT_BASE( FT_Error )\r\n  FT_Raccess_Get_HeaderInfo( FT_Library  library,\r\n                             FT_Stream   stream,\r\n                             FT_Long     rfork_offset,\r\n                             FT_Long    *map_offset,\r\n                             FT_Long    *rdata_pos );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Raccess_Get_DataOffsets                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Get the data offsets for a tag in a resource fork.  Offsets are    */\r\n  /*    stored in an array because, in some cases, resources in a resource */\r\n  /*    fork have the same tag.                                            */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    library ::                                                         */\r\n  /*      A FreeType library instance.                                     */\r\n  /*                                                                       */\r\n  /*    stream ::                                                          */\r\n  /*      A file stream containing the resource fork.                      */\r\n  /*                                                                       */\r\n  /*    map_offset ::                                                      */\r\n  /*      The file offset where the resource map starts.                   */\r\n  /*                                                                       */\r\n  /*    rdata_pos ::                                                       */\r\n  /*      The file offset where the resource data starts.                  */\r\n  /*                                                                       */\r\n  /*    tag ::                                                             */\r\n  /*      The resource tag.                                                */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    offsets ::                                                         */\r\n  /*      The stream offsets for the resource data specified by `tag'.     */\r\n  /*      This array is allocated by the function, so you have to call     */\r\n  /*      @ft_mem_free after use.                                          */\r\n  /*                                                                       */\r\n  /*    count ::                                                           */\r\n  /*      The length of offsets array.                                     */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  FT_Err_Ok means success.                     */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    Normally you should use `FT_Raccess_Get_HeaderInfo' to get the     */\r\n  /*    value for `map_offset' and `rdata_pos'.                            */\r\n  /*                                                                       */\r\n  FT_BASE( FT_Error )\r\n  FT_Raccess_Get_DataOffsets( FT_Library  library,\r\n                              FT_Stream   stream,\r\n                              FT_Long     map_offset,\r\n                              FT_Long     rdata_pos,\r\n                              FT_Long     tag,\r\n                              FT_Long   **offsets,\r\n                              FT_Long    *count );\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTRFORK_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/ftserv.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftserv.h                                                               */\r\n/*                                                                         */\r\n/*    The FreeType services (specification only).                          */\r\n/*                                                                         */\r\n/*  Copyright 2003, 2004, 2005, 2006, 2007 by                              */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /*  Each module can export one or more `services'.  Each service is      */\r\n  /*  identified by a constant string and modeled by a pointer; the latter */\r\n  /*  generally corresponds to a structure containing function pointers.   */\r\n  /*                                                                       */\r\n  /*  Note that a service's data cannot be a mere function pointer because */\r\n  /*  in C it is possible that function pointers might be implemented      */\r\n  /*  differently than data pointers (e.g. 48 bits instead of 32).         */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n#ifndef __FTSERV_H__\r\n#define __FTSERV_H__\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n#if defined( _MSC_VER )      /* Visual C++ (and Intel C++) */\r\n\r\n  /* we disable the warning `conditional expression is constant' here */\r\n  /* in order to compile cleanly with the maximum level of warnings   */\r\n#pragma warning( disable : 4127 )\r\n\r\n#endif /* _MSC_VER */\r\n\r\n  /*\r\n   * @macro:\r\n   *   FT_FACE_FIND_SERVICE\r\n   *\r\n   * @description:\r\n   *   This macro is used to look up a service from a face's driver module.\r\n   *\r\n   * @input:\r\n   *   face ::\r\n   *     The source face handle.\r\n   *\r\n   *   id ::\r\n   *     A string describing the service as defined in the service's\r\n   *     header files (e.g. FT_SERVICE_ID_MULTI_MASTERS which expands to\r\n   *     `multi-masters').  It is automatically prefixed with\r\n   *     `FT_SERVICE_ID_'.\r\n   *\r\n   * @output:\r\n   *   ptr ::\r\n   *     A variable that receives the service pointer.  Will be NULL\r\n   *     if not found.\r\n   */\r\n#ifdef __cplusplus\r\n\r\n#define FT_FACE_FIND_SERVICE( face, ptr, id )                               \\\r\n  FT_BEGIN_STMNT                                                            \\\r\n    FT_Module    module = FT_MODULE( FT_FACE( face )->driver );             \\\r\n    FT_Pointer   _tmp_  = NULL;                                             \\\r\n    FT_Pointer*  _pptr_ = (FT_Pointer*)&(ptr);                              \\\r\n                                                                            \\\r\n                                                                            \\\r\n    if ( module->clazz->get_interface )                                     \\\r\n      _tmp_ = module->clazz->get_interface( module, FT_SERVICE_ID_ ## id ); \\\r\n    *_pptr_ = _tmp_;                                                        \\\r\n  FT_END_STMNT\r\n\r\n#else /* !C++ */\r\n\r\n#define FT_FACE_FIND_SERVICE( face, ptr, id )                               \\\r\n  FT_BEGIN_STMNT                                                            \\\r\n    FT_Module   module = FT_MODULE( FT_FACE( face )->driver );              \\\r\n    FT_Pointer  _tmp_  = NULL;                                              \\\r\n                                                                            \\\r\n    if ( module->clazz->get_interface )                                     \\\r\n      _tmp_ = module->clazz->get_interface( module, FT_SERVICE_ID_ ## id ); \\\r\n    ptr = _tmp_;                                                            \\\r\n  FT_END_STMNT\r\n\r\n#endif /* !C++ */\r\n\r\n  /*\r\n   * @macro:\r\n   *   FT_FACE_FIND_GLOBAL_SERVICE\r\n   *\r\n   * @description:\r\n   *   This macro is used to look up a service from all modules.\r\n   *\r\n   * @input:\r\n   *   face ::\r\n   *     The source face handle.\r\n   *\r\n   *   id ::\r\n   *     A string describing the service as defined in the service's\r\n   *     header files (e.g. FT_SERVICE_ID_MULTI_MASTERS which expands to\r\n   *     `multi-masters').  It is automatically prefixed with\r\n   *     `FT_SERVICE_ID_'.\r\n   *\r\n   * @output:\r\n   *   ptr ::\r\n   *     A variable that receives the service pointer.  Will be NULL\r\n   *     if not found.\r\n   */\r\n#ifdef __cplusplus\r\n\r\n#define FT_FACE_FIND_GLOBAL_SERVICE( face, ptr, id )               \\\r\n  FT_BEGIN_STMNT                                                   \\\r\n    FT_Module    module = FT_MODULE( FT_FACE( face )->driver );    \\\r\n    FT_Pointer   _tmp_;                                            \\\r\n    FT_Pointer*  _pptr_ = (FT_Pointer*)&(ptr);                     \\\r\n                                                                   \\\r\n                                                                   \\\r\n    _tmp_ = ft_module_get_service( module, FT_SERVICE_ID_ ## id ); \\\r\n    *_pptr_ = _tmp_;                                               \\\r\n  FT_END_STMNT\r\n\r\n#else /* !C++ */\r\n\r\n#define FT_FACE_FIND_GLOBAL_SERVICE( face, ptr, id )               \\\r\n  FT_BEGIN_STMNT                                                   \\\r\n    FT_Module   module = FT_MODULE( FT_FACE( face )->driver );     \\\r\n    FT_Pointer  _tmp_;                                             \\\r\n                                                                   \\\r\n                                                                   \\\r\n    _tmp_ = ft_module_get_service( module, FT_SERVICE_ID_ ## id ); \\\r\n    ptr   = _tmp_;                                                 \\\r\n  FT_END_STMNT\r\n\r\n#endif /* !C++ */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*****                                                               *****/\r\n  /*****         S E R V I C E   D E S C R I P T O R S                 *****/\r\n  /*****                                                               *****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n  /*\r\n   *  The following structure is used to _describe_ a given service\r\n   *  to the library.  This is useful to build simple static service lists.\r\n   */\r\n  typedef struct  FT_ServiceDescRec_\r\n  {\r\n    const char*  serv_id;     /* service name         */\r\n    const void*  serv_data;   /* service pointer/data */\r\n\r\n  } FT_ServiceDescRec;\r\n\r\n  typedef const FT_ServiceDescRec*  FT_ServiceDesc;\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Macro>                                                               */\r\n  /*    FT_DEFINE_SERVICEDESCREC1 .. FT_DEFINE_SERVICEDESCREC6             */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Used to initialize an array of FT_ServiceDescRec structs.          */\r\n  /*                                                                       */\r\n  /*    When FT_CONFIG_OPTION_PIC is defined a Create funtion will need    */\r\n  /*    to called with a pointer where the allocated array is returned.    */\r\n  /*    And when it is no longer needed a Destroy function needs           */\r\n  /*    to be called to release that allocation.                           */\r\n  /*                                                                       */\r\n  /*    These functions should be manyally called from the pic_init and    */\r\n  /*    pic_free functions of your module (see FT_DEFINE_MODULE)           */\r\n  /*                                                                       */\r\n  /*    When FT_CONFIG_OPTION_PIC is not defined the array will be         */\r\n  /*    allocated in the global scope (or the scope where the macro        */\r\n  /*    is used).                                                          */\r\n  /*                                                                       */\r\n#ifndef FT_CONFIG_OPTION_PIC\r\n\r\n#define FT_DEFINE_SERVICEDESCREC1(class_, serv_id_1, serv_data_1)            \\\r\n  static const FT_ServiceDescRec class_[] =                                  \\\r\n  {                                                                          \\\r\n  {serv_id_1, serv_data_1},                                                  \\\r\n  {NULL, NULL}                                                               \\\r\n  };\r\n#define FT_DEFINE_SERVICEDESCREC2(class_, serv_id_1, serv_data_1,            \\\r\n        serv_id_2, serv_data_2)                                              \\\r\n  static const FT_ServiceDescRec class_[] =                                  \\\r\n  {                                                                          \\\r\n  {serv_id_1, serv_data_1},                                                  \\\r\n  {serv_id_2, serv_data_2},                                                  \\\r\n  {NULL, NULL}                                                               \\\r\n  };\r\n#define FT_DEFINE_SERVICEDESCREC3(class_, serv_id_1, serv_data_1,            \\\r\n        serv_id_2, serv_data_2, serv_id_3, serv_data_3)                      \\\r\n  static const FT_ServiceDescRec class_[] =                                  \\\r\n  {                                                                          \\\r\n  {serv_id_1, serv_data_1},                                                  \\\r\n  {serv_id_2, serv_data_2},                                                  \\\r\n  {serv_id_3, serv_data_3},                                                  \\\r\n  {NULL, NULL}                                                               \\\r\n  };\r\n#define FT_DEFINE_SERVICEDESCREC4(class_, serv_id_1, serv_data_1,            \\\r\n        serv_id_2, serv_data_2, serv_id_3, serv_data_3,                      \\\r\n        serv_id_4, serv_data_4)                                              \\\r\n  static const FT_ServiceDescRec class_[] =                                  \\\r\n  {                                                                          \\\r\n  {serv_id_1, serv_data_1},                                                  \\\r\n  {serv_id_2, serv_data_2},                                                  \\\r\n  {serv_id_3, serv_data_3},                                                  \\\r\n  {serv_id_4, serv_data_4},                                                  \\\r\n  {NULL, NULL}                                                               \\\r\n  };\r\n#define FT_DEFINE_SERVICEDESCREC5(class_, serv_id_1, serv_data_1,            \\\r\n        serv_id_2, serv_data_2, serv_id_3, serv_data_3,                      \\\r\n        serv_id_4, serv_data_4, serv_id_5, serv_data_5)                      \\\r\n  static const FT_ServiceDescRec class_[] =                                  \\\r\n  {                                                                          \\\r\n  {serv_id_1, serv_data_1},                                                  \\\r\n  {serv_id_2, serv_data_2},                                                  \\\r\n  {serv_id_3, serv_data_3},                                                  \\\r\n  {serv_id_4, serv_data_4},                                                  \\\r\n  {serv_id_5, serv_data_5},                                                  \\\r\n  {NULL, NULL}                                                               \\\r\n  };\r\n#define FT_DEFINE_SERVICEDESCREC6(class_, serv_id_1, serv_data_1,            \\\r\n        serv_id_2, serv_data_2, serv_id_3, serv_data_3,                      \\\r\n        serv_id_4, serv_data_4, serv_id_5, serv_data_5,                      \\\r\n        serv_id_6, serv_data_6)                                              \\\r\n  static const FT_ServiceDescRec class_[] =                                  \\\r\n  {                                                                          \\\r\n  {serv_id_1, serv_data_1},                                                  \\\r\n  {serv_id_2, serv_data_2},                                                  \\\r\n  {serv_id_3, serv_data_3},                                                  \\\r\n  {serv_id_4, serv_data_4},                                                  \\\r\n  {serv_id_5, serv_data_5},                                                  \\\r\n  {serv_id_6, serv_data_6},                                                  \\\r\n  {NULL, NULL}                                                               \\\r\n  };\r\n\r\n#else /* FT_CONFIG_OPTION_PIC */ \r\n\r\n#define FT_DEFINE_SERVICEDESCREC1(class_, serv_id_1, serv_data_1)            \\\r\n  void                                                                       \\\r\n  FT_Destroy_Class_##class_( FT_Library library,                             \\\r\n                             FT_ServiceDescRec* clazz )                      \\\r\n  {                                                                          \\\r\n    FT_Memory memory = library->memory;                                      \\\r\n    if ( clazz )                                                             \\\r\n      FT_FREE( clazz );                                                      \\\r\n  }                                                                          \\\r\n                                                                             \\\r\n  FT_Error                                                                   \\\r\n  FT_Create_Class_##class_( FT_Library library,                              \\\r\n                            FT_ServiceDescRec** output_class)                \\\r\n  {                                                                          \\\r\n    FT_ServiceDescRec*  clazz;                                               \\\r\n    FT_Error          error;                                                 \\\r\n    FT_Memory memory = library->memory;                                      \\\r\n                                                                             \\\r\n    if ( FT_ALLOC( clazz, sizeof(*clazz)*2 ) )                               \\\r\n      return error;                                                          \\\r\n    clazz[0].serv_id = serv_id_1;                                            \\\r\n    clazz[0].serv_data = serv_data_1;                                        \\\r\n    clazz[1].serv_id = NULL;                                                 \\\r\n    clazz[1].serv_data = NULL;                                               \\\r\n    *output_class = clazz;                                                   \\\r\n    return FT_Err_Ok;                                                        \\\r\n  } \r\n\r\n#define FT_DEFINE_SERVICEDESCREC2(class_, serv_id_1, serv_data_1,            \\\r\n        serv_id_2, serv_data_2)                                              \\\r\n  void                                                                       \\\r\n  FT_Destroy_Class_##class_( FT_Library library,                             \\\r\n                             FT_ServiceDescRec* clazz )                      \\\r\n  {                                                                          \\\r\n    FT_Memory memory = library->memory;                                      \\\r\n    if ( clazz )                                                             \\\r\n      FT_FREE( clazz );                                                      \\\r\n  }                                                                          \\\r\n                                                                             \\\r\n  FT_Error                                                                   \\\r\n  FT_Create_Class_##class_( FT_Library library,                              \\\r\n                            FT_ServiceDescRec** output_class)                \\\r\n  {                                                                          \\\r\n    FT_ServiceDescRec*  clazz;                                               \\\r\n    FT_Error          error;                                                 \\\r\n    FT_Memory memory = library->memory;                                      \\\r\n                                                                             \\\r\n    if ( FT_ALLOC( clazz, sizeof(*clazz)*3 ) )                               \\\r\n      return error;                                                          \\\r\n    clazz[0].serv_id = serv_id_1;                                            \\\r\n    clazz[0].serv_data = serv_data_1;                                        \\\r\n    clazz[1].serv_id = serv_id_2;                                            \\\r\n    clazz[1].serv_data = serv_data_2;                                        \\\r\n    clazz[2].serv_id = NULL;                                                 \\\r\n    clazz[2].serv_data = NULL;                                               \\\r\n    *output_class = clazz;                                                   \\\r\n    return FT_Err_Ok;                                                        \\\r\n  } \r\n\r\n#define FT_DEFINE_SERVICEDESCREC3(class_, serv_id_1, serv_data_1,            \\\r\n        serv_id_2, serv_data_2, serv_id_3, serv_data_3)                      \\\r\n  void                                                                       \\\r\n  FT_Destroy_Class_##class_( FT_Library library,                             \\\r\n                             FT_ServiceDescRec* clazz )                      \\\r\n  {                                                                          \\\r\n    FT_Memory memory = library->memory;                                      \\\r\n    if ( clazz )                                                             \\\r\n      FT_FREE( clazz );                                                      \\\r\n  }                                                                          \\\r\n                                                                             \\\r\n  FT_Error                                                                   \\\r\n  FT_Create_Class_##class_( FT_Library library,                              \\\r\n                            FT_ServiceDescRec** output_class)                \\\r\n  {                                                                          \\\r\n    FT_ServiceDescRec*  clazz;                                               \\\r\n    FT_Error          error;                                                 \\\r\n    FT_Memory memory = library->memory;                                      \\\r\n                                                                             \\\r\n    if ( FT_ALLOC( clazz, sizeof(*clazz)*4 ) )                               \\\r\n      return error;                                                          \\\r\n    clazz[0].serv_id = serv_id_1;                                            \\\r\n    clazz[0].serv_data = serv_data_1;                                        \\\r\n    clazz[1].serv_id = serv_id_2;                                            \\\r\n    clazz[1].serv_data = serv_data_2;                                        \\\r\n    clazz[2].serv_id = serv_id_3;                                            \\\r\n    clazz[2].serv_data = serv_data_3;                                        \\\r\n    clazz[3].serv_id = NULL;                                                 \\\r\n    clazz[3].serv_data = NULL;                                               \\\r\n    *output_class = clazz;                                                   \\\r\n    return FT_Err_Ok;                                                        \\\r\n  } \r\n\r\n#define FT_DEFINE_SERVICEDESCREC4(class_, serv_id_1, serv_data_1,            \\\r\n        serv_id_2, serv_data_2, serv_id_3, serv_data_3,                      \\\r\n        serv_id_4, serv_data_4)                                              \\\r\n  void                                                                       \\\r\n  FT_Destroy_Class_##class_( FT_Library library,                             \\\r\n                             FT_ServiceDescRec* clazz )                      \\\r\n  {                                                                          \\\r\n    FT_Memory memory = library->memory;                                      \\\r\n    if ( clazz )                                                             \\\r\n      FT_FREE( clazz );                                                      \\\r\n  }                                                                          \\\r\n                                                                             \\\r\n  FT_Error                                                                   \\\r\n  FT_Create_Class_##class_( FT_Library library,                              \\\r\n                            FT_ServiceDescRec** output_class)                \\\r\n  {                                                                          \\\r\n    FT_ServiceDescRec*  clazz;                                               \\\r\n    FT_Error          error;                                                 \\\r\n    FT_Memory memory = library->memory;                                      \\\r\n                                                                             \\\r\n    if ( FT_ALLOC( clazz, sizeof(*clazz)*5 ) )                               \\\r\n      return error;                                                          \\\r\n    clazz[0].serv_id = serv_id_1;                                            \\\r\n    clazz[0].serv_data = serv_data_1;                                        \\\r\n    clazz[1].serv_id = serv_id_2;                                            \\\r\n    clazz[1].serv_data = serv_data_2;                                        \\\r\n    clazz[2].serv_id = serv_id_3;                                            \\\r\n    clazz[2].serv_data = serv_data_3;                                        \\\r\n    clazz[3].serv_id = serv_id_4;                                            \\\r\n    clazz[3].serv_data = serv_data_4;                                        \\\r\n    clazz[4].serv_id = NULL;                                                 \\\r\n    clazz[4].serv_data = NULL;                                               \\\r\n    *output_class = clazz;                                                   \\\r\n    return FT_Err_Ok;                                                        \\\r\n  } \r\n\r\n#define FT_DEFINE_SERVICEDESCREC5(class_, serv_id_1, serv_data_1,            \\\r\n        serv_id_2, serv_data_2, serv_id_3, serv_data_3, serv_id_4,           \\\r\n        serv_data_4, serv_id_5, serv_data_5)                                 \\\r\n  void                                                                       \\\r\n  FT_Destroy_Class_##class_( FT_Library library,                             \\\r\n                             FT_ServiceDescRec* clazz )                      \\\r\n  {                                                                          \\\r\n    FT_Memory memory = library->memory;                                      \\\r\n    if ( clazz )                                                             \\\r\n      FT_FREE( clazz );                                                      \\\r\n  }                                                                          \\\r\n                                                                             \\\r\n  FT_Error                                                                   \\\r\n  FT_Create_Class_##class_( FT_Library library,                              \\\r\n                            FT_ServiceDescRec** output_class)                \\\r\n  {                                                                          \\\r\n    FT_ServiceDescRec*  clazz;                                               \\\r\n    FT_Error          error;                                                 \\\r\n    FT_Memory memory = library->memory;                                      \\\r\n                                                                             \\\r\n    if ( FT_ALLOC( clazz, sizeof(*clazz)*6 ) )                               \\\r\n      return error;                                                          \\\r\n    clazz[0].serv_id = serv_id_1;                                            \\\r\n    clazz[0].serv_data = serv_data_1;                                        \\\r\n    clazz[1].serv_id = serv_id_2;                                            \\\r\n    clazz[1].serv_data = serv_data_2;                                        \\\r\n    clazz[2].serv_id = serv_id_3;                                            \\\r\n    clazz[2].serv_data = serv_data_3;                                        \\\r\n    clazz[3].serv_id = serv_id_4;                                            \\\r\n    clazz[3].serv_data = serv_data_4;                                        \\\r\n    clazz[4].serv_id = serv_id_5;                                            \\\r\n    clazz[4].serv_data = serv_data_5;                                        \\\r\n    clazz[5].serv_id = NULL;                                                 \\\r\n    clazz[5].serv_data = NULL;                                               \\\r\n    *output_class = clazz;                                                   \\\r\n    return FT_Err_Ok;                                                        \\\r\n  } \r\n\r\n#define FT_DEFINE_SERVICEDESCREC6(class_, serv_id_1, serv_data_1,            \\\r\n        serv_id_2, serv_data_2, serv_id_3, serv_data_3,                      \\\r\n        serv_id_4, serv_data_4, serv_id_5, serv_data_5,                      \\\r\n        serv_id_6, serv_data_6)                                              \\\r\n  void                                                                       \\\r\n  FT_Destroy_Class_##class_( FT_Library library,                             \\\r\n                             FT_ServiceDescRec* clazz )                      \\\r\n  {                                                                          \\\r\n    FT_Memory memory = library->memory;                                      \\\r\n    if ( clazz )                                                             \\\r\n      FT_FREE( clazz );                                                      \\\r\n  }                                                                          \\\r\n                                                                             \\\r\n  FT_Error                                                                   \\\r\n  FT_Create_Class_##class_( FT_Library library,                              \\\r\n                            FT_ServiceDescRec** output_class)                \\\r\n  {                                                                          \\\r\n    FT_ServiceDescRec*  clazz;                                               \\\r\n    FT_Error          error;                                                 \\\r\n    FT_Memory memory = library->memory;                                      \\\r\n                                                                             \\\r\n    if ( FT_ALLOC( clazz, sizeof(*clazz)*7 ) )                               \\\r\n      return error;                                                          \\\r\n    clazz[0].serv_id = serv_id_1;                                            \\\r\n    clazz[0].serv_data = serv_data_1;                                        \\\r\n    clazz[1].serv_id = serv_id_2;                                            \\\r\n    clazz[1].serv_data = serv_data_2;                                        \\\r\n    clazz[2].serv_id = serv_id_3;                                            \\\r\n    clazz[2].serv_data = serv_data_3;                                        \\\r\n    clazz[3].serv_id = serv_id_4;                                            \\\r\n    clazz[3].serv_data = serv_data_4;                                        \\\r\n    clazz[4].serv_id = serv_id_5;                                            \\\r\n    clazz[4].serv_data = serv_data_5;                                        \\\r\n    clazz[5].serv_id = serv_id_6;                                            \\\r\n    clazz[5].serv_data = serv_data_6;                                        \\\r\n    clazz[6].serv_id = NULL;                                                 \\\r\n    clazz[6].serv_data = NULL;                                               \\\r\n    *output_class = clazz;                                                   \\\r\n    return FT_Err_Ok;                                                        \\\r\n  } \r\n#endif /* FT_CONFIG_OPTION_PIC */ \r\n\r\n  /*\r\n   *  Parse a list of FT_ServiceDescRec descriptors and look for\r\n   *  a specific service by ID.  Note that the last element in the\r\n   *  array must be { NULL, NULL }, and that the function should\r\n   *  return NULL if the service isn't available.\r\n   *\r\n   *  This function can be used by modules to implement their\r\n   *  `get_service' method.\r\n   */\r\n  FT_BASE( FT_Pointer )\r\n  ft_service_list_lookup( FT_ServiceDesc  service_descriptors,\r\n                          const char*     service_id );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*****                                                               *****/\r\n  /*****             S E R V I C E S   C A C H E                       *****/\r\n  /*****                                                               *****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n  /*\r\n   *  This structure is used to store a cache for several frequently used\r\n   *  services.  It is the type of `face->internal->services'.  You\r\n   *  should only use FT_FACE_LOOKUP_SERVICE to access it.\r\n   *\r\n   *  All fields should have the type FT_Pointer to relax compilation\r\n   *  dependencies.  We assume the developer isn't completely stupid.\r\n   *\r\n   *  Each field must be named `service_XXXX' where `XXX' corresponds to\r\n   *  the correct FT_SERVICE_ID_XXXX macro.  See the definition of\r\n   *  FT_FACE_LOOKUP_SERVICE below how this is implemented.\r\n   *\r\n   */\r\n  typedef struct  FT_ServiceCacheRec_\r\n  {\r\n    FT_Pointer  service_POSTSCRIPT_FONT_NAME;\r\n    FT_Pointer  service_MULTI_MASTERS;\r\n    FT_Pointer  service_GLYPH_DICT;\r\n    FT_Pointer  service_PFR_METRICS;\r\n    FT_Pointer  service_WINFNT;\r\n\r\n  } FT_ServiceCacheRec, *FT_ServiceCache;\r\n\r\n\r\n  /*\r\n   *  A magic number used within the services cache.\r\n   */\r\n#define FT_SERVICE_UNAVAILABLE  ((FT_Pointer)-2)  /* magic number */\r\n\r\n\r\n  /*\r\n   * @macro:\r\n   *   FT_FACE_LOOKUP_SERVICE\r\n   *\r\n   * @description:\r\n   *   This macro is used to lookup a service from a face's driver module\r\n   *   using its cache.\r\n   *\r\n   * @input:\r\n   *   face::\r\n   *     The source face handle containing the cache.\r\n   *\r\n   *   field ::\r\n   *     The field name in the cache.\r\n   *\r\n   *   id ::\r\n   *     The service ID.\r\n   *\r\n   * @output:\r\n   *   ptr ::\r\n   *     A variable receiving the service data.  NULL if not available.\r\n   */\r\n#ifdef __cplusplus\r\n\r\n#define FT_FACE_LOOKUP_SERVICE( face, ptr, id )                \\\r\n  FT_BEGIN_STMNT                                               \\\r\n    FT_Pointer   svc;                                          \\\r\n    FT_Pointer*  Pptr = (FT_Pointer*)&(ptr);                   \\\r\n                                                               \\\r\n                                                               \\\r\n    svc = FT_FACE( face )->internal->services. service_ ## id; \\\r\n    if ( svc == FT_SERVICE_UNAVAILABLE )                       \\\r\n      svc = NULL;                                              \\\r\n    else if ( svc == NULL )                                    \\\r\n    {                                                          \\\r\n      FT_FACE_FIND_SERVICE( face, svc, id );                   \\\r\n                                                               \\\r\n      FT_FACE( face )->internal->services. service_ ## id =    \\\r\n        (FT_Pointer)( svc != NULL ? svc                        \\\r\n                                  : FT_SERVICE_UNAVAILABLE );  \\\r\n    }                                                          \\\r\n    *Pptr = svc;                                               \\\r\n  FT_END_STMNT\r\n\r\n#else /* !C++ */\r\n\r\n#define FT_FACE_LOOKUP_SERVICE( face, ptr, id )                \\\r\n  FT_BEGIN_STMNT                                               \\\r\n    FT_Pointer  svc;                                           \\\r\n                                                               \\\r\n                                                               \\\r\n    svc = FT_FACE( face )->internal->services. service_ ## id; \\\r\n    if ( svc == FT_SERVICE_UNAVAILABLE )                       \\\r\n      svc = NULL;                                              \\\r\n    else if ( svc == NULL )                                    \\\r\n    {                                                          \\\r\n      FT_FACE_FIND_SERVICE( face, svc, id );                   \\\r\n                                                               \\\r\n      FT_FACE( face )->internal->services. service_ ## id =    \\\r\n        (FT_Pointer)( svc != NULL ? svc                        \\\r\n                                  : FT_SERVICE_UNAVAILABLE );  \\\r\n    }                                                          \\\r\n    ptr = svc;                                                 \\\r\n  FT_END_STMNT\r\n\r\n#endif /* !C++ */\r\n\r\n  /*\r\n   *  A macro used to define new service structure types.\r\n   */\r\n\r\n#define FT_DEFINE_SERVICE( name )            \\\r\n  typedef struct FT_Service_ ## name ## Rec_ \\\r\n    FT_Service_ ## name ## Rec ;             \\\r\n  typedef struct FT_Service_ ## name ## Rec_ \\\r\n    const * FT_Service_ ## name ;            \\\r\n  struct FT_Service_ ## name ## Rec_\r\n\r\n  /* */\r\n\r\n  /*\r\n   *  The header files containing the services.\r\n   */\r\n\r\n#define FT_SERVICE_BDF_H                <freetype/internal/services/svbdf.h>\r\n#define FT_SERVICE_CID_H                <freetype/internal/services/svcid.h>\r\n#define FT_SERVICE_GLYPH_DICT_H         <freetype/internal/services/svgldict.h>\r\n#define FT_SERVICE_GX_VALIDATE_H        <freetype/internal/services/svgxval.h>\r\n#define FT_SERVICE_KERNING_H            <freetype/internal/services/svkern.h>\r\n#define FT_SERVICE_MULTIPLE_MASTERS_H   <freetype/internal/services/svmm.h>\r\n#define FT_SERVICE_OPENTYPE_VALIDATE_H  <freetype/internal/services/svotval.h>\r\n#define FT_SERVICE_PFR_H                <freetype/internal/services/svpfr.h>\r\n#define FT_SERVICE_POSTSCRIPT_CMAPS_H   <freetype/internal/services/svpscmap.h>\r\n#define FT_SERVICE_POSTSCRIPT_INFO_H    <freetype/internal/services/svpsinfo.h>\r\n#define FT_SERVICE_POSTSCRIPT_NAME_H    <freetype/internal/services/svpostnm.h>\r\n#define FT_SERVICE_SFNT_H               <freetype/internal/services/svsfnt.h>\r\n#define FT_SERVICE_TRUETYPE_ENGINE_H    <freetype/internal/services/svtteng.h>\r\n#define FT_SERVICE_TT_CMAP_H            <freetype/internal/services/svttcmap.h>\r\n#define FT_SERVICE_WINFNT_H             <freetype/internal/services/svwinfnt.h>\r\n#define FT_SERVICE_XFREE86_NAME_H       <freetype/internal/services/svxf86nm.h>\r\n#define FT_SERVICE_TRUETYPE_GLYF_H      <freetype/internal/services/svttglyf.h>\r\n\r\n /* */\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTSERV_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/ftstream.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftstream.h                                                             */\r\n/*                                                                         */\r\n/*    Stream handling (specification).                                     */\r\n/*                                                                         */\r\n/*  Copyright 1996-2002, 2004-2006, 2011 by                                */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTSTREAM_H__\r\n#define __FTSTREAM_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_SYSTEM_H\r\n#include FT_INTERNAL_OBJECTS_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /* format of an 8-bit frame_op value:           */\r\n  /*                                              */\r\n  /* bit  76543210                                */\r\n  /*      xxxxxxes                                */\r\n  /*                                              */\r\n  /* s is set to 1 if the value is signed.        */\r\n  /* e is set to 1 if the value is little-endian. */\r\n  /* xxx is a command.                            */\r\n\r\n#define FT_FRAME_OP_SHIFT         2\r\n#define FT_FRAME_OP_SIGNED        1\r\n#define FT_FRAME_OP_LITTLE        2\r\n#define FT_FRAME_OP_COMMAND( x )  ( x >> FT_FRAME_OP_SHIFT )\r\n\r\n#define FT_MAKE_FRAME_OP( command, little, sign ) \\\r\n          ( ( command << FT_FRAME_OP_SHIFT ) | ( little << 1 ) | sign )\r\n\r\n#define FT_FRAME_OP_END    0\r\n#define FT_FRAME_OP_START  1  /* start a new frame     */\r\n#define FT_FRAME_OP_BYTE   2  /* read 1-byte value     */\r\n#define FT_FRAME_OP_SHORT  3  /* read 2-byte value     */\r\n#define FT_FRAME_OP_LONG   4  /* read 4-byte value     */\r\n#define FT_FRAME_OP_OFF3   5  /* read 3-byte value     */\r\n#define FT_FRAME_OP_BYTES  6  /* read a bytes sequence */\r\n\r\n\r\n  typedef enum  FT_Frame_Op_\r\n  {\r\n    ft_frame_end       = 0,\r\n    ft_frame_start     = FT_MAKE_FRAME_OP( FT_FRAME_OP_START, 0, 0 ),\r\n\r\n    ft_frame_byte      = FT_MAKE_FRAME_OP( FT_FRAME_OP_BYTE,  0, 0 ),\r\n    ft_frame_schar     = FT_MAKE_FRAME_OP( FT_FRAME_OP_BYTE,  0, 1 ),\r\n\r\n    ft_frame_ushort_be = FT_MAKE_FRAME_OP( FT_FRAME_OP_SHORT, 0, 0 ),\r\n    ft_frame_short_be  = FT_MAKE_FRAME_OP( FT_FRAME_OP_SHORT, 0, 1 ),\r\n    ft_frame_ushort_le = FT_MAKE_FRAME_OP( FT_FRAME_OP_SHORT, 1, 0 ),\r\n    ft_frame_short_le  = FT_MAKE_FRAME_OP( FT_FRAME_OP_SHORT, 1, 1 ),\r\n\r\n    ft_frame_ulong_be  = FT_MAKE_FRAME_OP( FT_FRAME_OP_LONG, 0, 0 ),\r\n    ft_frame_long_be   = FT_MAKE_FRAME_OP( FT_FRAME_OP_LONG, 0, 1 ),\r\n    ft_frame_ulong_le  = FT_MAKE_FRAME_OP( FT_FRAME_OP_LONG, 1, 0 ),\r\n    ft_frame_long_le   = FT_MAKE_FRAME_OP( FT_FRAME_OP_LONG, 1, 1 ),\r\n\r\n    ft_frame_uoff3_be  = FT_MAKE_FRAME_OP( FT_FRAME_OP_OFF3, 0, 0 ),\r\n    ft_frame_off3_be   = FT_MAKE_FRAME_OP( FT_FRAME_OP_OFF3, 0, 1 ),\r\n    ft_frame_uoff3_le  = FT_MAKE_FRAME_OP( FT_FRAME_OP_OFF3, 1, 0 ),\r\n    ft_frame_off3_le   = FT_MAKE_FRAME_OP( FT_FRAME_OP_OFF3, 1, 1 ),\r\n\r\n    ft_frame_bytes     = FT_MAKE_FRAME_OP( FT_FRAME_OP_BYTES, 0, 0 ),\r\n    ft_frame_skip      = FT_MAKE_FRAME_OP( FT_FRAME_OP_BYTES, 0, 1 )\r\n\r\n  } FT_Frame_Op;\r\n\r\n\r\n  typedef struct  FT_Frame_Field_\r\n  {\r\n    FT_Byte    value;\r\n    FT_Byte    size;\r\n    FT_UShort  offset;\r\n\r\n  } FT_Frame_Field;\r\n\r\n\r\n  /* Construct an FT_Frame_Field out of a structure type and a field name. */\r\n  /* The structure type must be set in the FT_STRUCTURE macro before       */\r\n  /* calling the FT_FRAME_START() macro.                                   */\r\n  /*                                                                       */\r\n#define FT_FIELD_SIZE( f ) \\\r\n          (FT_Byte)sizeof ( ((FT_STRUCTURE*)0)->f )\r\n\r\n#define FT_FIELD_SIZE_DELTA( f ) \\\r\n          (FT_Byte)sizeof ( ((FT_STRUCTURE*)0)->f[0] )\r\n\r\n#define FT_FIELD_OFFSET( f ) \\\r\n          (FT_UShort)( offsetof( FT_STRUCTURE, f ) )\r\n\r\n#define FT_FRAME_FIELD( frame_op, field ) \\\r\n          {                               \\\r\n            frame_op,                     \\\r\n            FT_FIELD_SIZE( field ),       \\\r\n            FT_FIELD_OFFSET( field )      \\\r\n          }\r\n\r\n#define FT_MAKE_EMPTY_FIELD( frame_op )  { frame_op, 0, 0 }\r\n\r\n#define FT_FRAME_START( size )   { ft_frame_start, 0, size }\r\n#define FT_FRAME_END             { ft_frame_end, 0, 0 }\r\n\r\n#define FT_FRAME_LONG( f )       FT_FRAME_FIELD( ft_frame_long_be, f )\r\n#define FT_FRAME_ULONG( f )      FT_FRAME_FIELD( ft_frame_ulong_be, f )\r\n#define FT_FRAME_SHORT( f )      FT_FRAME_FIELD( ft_frame_short_be, f )\r\n#define FT_FRAME_USHORT( f )     FT_FRAME_FIELD( ft_frame_ushort_be, f )\r\n#define FT_FRAME_OFF3( f )       FT_FRAME_FIELD( ft_frame_off3_be, f )\r\n#define FT_FRAME_UOFF3( f )      FT_FRAME_FIELD( ft_frame_uoff3_be, f )\r\n#define FT_FRAME_BYTE( f )       FT_FRAME_FIELD( ft_frame_byte, f )\r\n#define FT_FRAME_CHAR( f )       FT_FRAME_FIELD( ft_frame_schar, f )\r\n\r\n#define FT_FRAME_LONG_LE( f )    FT_FRAME_FIELD( ft_frame_long_le, f )\r\n#define FT_FRAME_ULONG_LE( f )   FT_FRAME_FIELD( ft_frame_ulong_le, f )\r\n#define FT_FRAME_SHORT_LE( f )   FT_FRAME_FIELD( ft_frame_short_le, f )\r\n#define FT_FRAME_USHORT_LE( f )  FT_FRAME_FIELD( ft_frame_ushort_le, f )\r\n#define FT_FRAME_OFF3_LE( f )    FT_FRAME_FIELD( ft_frame_off3_le, f )\r\n#define FT_FRAME_UOFF3_LE( f )   FT_FRAME_FIELD( ft_frame_uoff3_le, f )\r\n\r\n#define FT_FRAME_SKIP_LONG       { ft_frame_long_be, 0, 0 }\r\n#define FT_FRAME_SKIP_SHORT      { ft_frame_short_be, 0, 0 }\r\n#define FT_FRAME_SKIP_BYTE       { ft_frame_byte, 0, 0 }\r\n\r\n#define FT_FRAME_BYTES( field, count ) \\\r\n          {                            \\\r\n            ft_frame_bytes,            \\\r\n            count,                     \\\r\n            FT_FIELD_OFFSET( field )   \\\r\n          }\r\n\r\n#define FT_FRAME_SKIP_BYTES( count )  { ft_frame_skip, count, 0 }\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Integer extraction macros -- the `buffer' parameter must ALWAYS be of */\r\n  /* type `char*' or equivalent (1-byte elements).                         */\r\n  /*                                                                       */\r\n\r\n#define FT_BYTE_( p, i )  ( ((const FT_Byte*)(p))[(i)] )\r\n#define FT_INT8_( p, i )  ( ((const FT_Char*)(p))[(i)] )\r\n\r\n#define FT_INT16( x )   ( (FT_Int16)(x)  )\r\n#define FT_UINT16( x )  ( (FT_UInt16)(x) )\r\n#define FT_INT32( x )   ( (FT_Int32)(x)  )\r\n#define FT_UINT32( x )  ( (FT_UInt32)(x) )\r\n\r\n#define FT_BYTE_I16( p, i, s )  ( FT_INT16(  FT_BYTE_( p, i ) ) << (s) )\r\n#define FT_BYTE_U16( p, i, s )  ( FT_UINT16( FT_BYTE_( p, i ) ) << (s) )\r\n#define FT_BYTE_I32( p, i, s )  ( FT_INT32(  FT_BYTE_( p, i ) ) << (s) )\r\n#define FT_BYTE_U32( p, i, s )  ( FT_UINT32( FT_BYTE_( p, i ) ) << (s) )\r\n\r\n#define FT_INT8_I16( p, i, s )  ( FT_INT16(  FT_INT8_( p, i ) ) << (s) )\r\n#define FT_INT8_U16( p, i, s )  ( FT_UINT16( FT_INT8_( p, i ) ) << (s) )\r\n#define FT_INT8_I32( p, i, s )  ( FT_INT32(  FT_INT8_( p, i ) ) << (s) )\r\n#define FT_INT8_U32( p, i, s )  ( FT_UINT32( FT_INT8_( p, i ) ) << (s) )\r\n\r\n\r\n#define FT_PEEK_SHORT( p )  FT_INT16( FT_INT8_I16( p, 0, 8) | \\\r\n                                      FT_BYTE_I16( p, 1, 0) )\r\n\r\n#define FT_PEEK_USHORT( p )  FT_UINT16( FT_BYTE_U16( p, 0, 8 ) | \\\r\n                                        FT_BYTE_U16( p, 1, 0 ) )\r\n\r\n#define FT_PEEK_LONG( p )  FT_INT32( FT_INT8_I32( p, 0, 24 ) | \\\r\n                                     FT_BYTE_I32( p, 1, 16 ) | \\\r\n                                     FT_BYTE_I32( p, 2,  8 ) | \\\r\n                                     FT_BYTE_I32( p, 3,  0 ) )\r\n\r\n#define FT_PEEK_ULONG( p )  FT_UINT32( FT_BYTE_U32( p, 0, 24 ) | \\\r\n                                       FT_BYTE_U32( p, 1, 16 ) | \\\r\n                                       FT_BYTE_U32( p, 2,  8 ) | \\\r\n                                       FT_BYTE_U32( p, 3,  0 ) )\r\n\r\n#define FT_PEEK_OFF3( p )  FT_INT32( FT_INT8_I32( p, 0, 16 ) | \\\r\n                                     FT_BYTE_I32( p, 1,  8 ) | \\\r\n                                     FT_BYTE_I32( p, 2,  0 ) )\r\n\r\n#define FT_PEEK_UOFF3( p )  FT_UINT32( FT_BYTE_U32( p, 0, 16 ) | \\\r\n                                       FT_BYTE_U32( p, 1,  8 ) | \\\r\n                                       FT_BYTE_U32( p, 2,  0 ) )\r\n\r\n#define FT_PEEK_SHORT_LE( p )  FT_INT16( FT_INT8_I16( p, 1, 8 ) | \\\r\n                                         FT_BYTE_I16( p, 0, 0 ) )\r\n\r\n#define FT_PEEK_USHORT_LE( p )  FT_UINT16( FT_BYTE_U16( p, 1, 8 ) |  \\\r\n                                           FT_BYTE_U16( p, 0, 0 ) )\r\n\r\n#define FT_PEEK_LONG_LE( p )  FT_INT32( FT_INT8_I32( p, 3, 24 ) | \\\r\n                                        FT_BYTE_I32( p, 2, 16 ) | \\\r\n                                        FT_BYTE_I32( p, 1,  8 ) | \\\r\n                                        FT_BYTE_I32( p, 0,  0 ) )\r\n\r\n#define FT_PEEK_ULONG_LE( p )  FT_UINT32( FT_BYTE_U32( p, 3, 24 ) | \\\r\n                                          FT_BYTE_U32( p, 2, 16 ) | \\\r\n                                          FT_BYTE_U32( p, 1,  8 ) | \\\r\n                                          FT_BYTE_U32( p, 0,  0 ) )\r\n\r\n#define FT_PEEK_OFF3_LE( p )  FT_INT32( FT_INT8_I32( p, 2, 16 ) | \\\r\n                                        FT_BYTE_I32( p, 1,  8 ) | \\\r\n                                        FT_BYTE_I32( p, 0,  0 ) )\r\n\r\n#define FT_PEEK_UOFF3_LE( p )  FT_UINT32( FT_BYTE_U32( p, 2, 16 ) | \\\r\n                                          FT_BYTE_U32( p, 1,  8 ) | \\\r\n                                          FT_BYTE_U32( p, 0,  0 ) )\r\n\r\n\r\n#define FT_NEXT_CHAR( buffer )       \\\r\n          ( (signed char)*buffer++ )\r\n\r\n#define FT_NEXT_BYTE( buffer )         \\\r\n          ( (unsigned char)*buffer++ )\r\n\r\n#define FT_NEXT_SHORT( buffer )                                   \\\r\n          ( (short)( buffer += 2, FT_PEEK_SHORT( buffer - 2 ) ) )\r\n\r\n#define FT_NEXT_USHORT( buffer )                                            \\\r\n          ( (unsigned short)( buffer += 2, FT_PEEK_USHORT( buffer - 2 ) ) )\r\n\r\n#define FT_NEXT_OFF3( buffer )                                  \\\r\n          ( (long)( buffer += 3, FT_PEEK_OFF3( buffer - 3 ) ) )\r\n\r\n#define FT_NEXT_UOFF3( buffer )                                           \\\r\n          ( (unsigned long)( buffer += 3, FT_PEEK_UOFF3( buffer - 3 ) ) )\r\n\r\n#define FT_NEXT_LONG( buffer )                                  \\\r\n          ( (long)( buffer += 4, FT_PEEK_LONG( buffer - 4 ) ) )\r\n\r\n#define FT_NEXT_ULONG( buffer )                                           \\\r\n          ( (unsigned long)( buffer += 4, FT_PEEK_ULONG( buffer - 4 ) ) )\r\n\r\n\r\n#define FT_NEXT_SHORT_LE( buffer )                                   \\\r\n          ( (short)( buffer += 2, FT_PEEK_SHORT_LE( buffer - 2 ) ) )\r\n\r\n#define FT_NEXT_USHORT_LE( buffer )                                            \\\r\n          ( (unsigned short)( buffer += 2, FT_PEEK_USHORT_LE( buffer - 2 ) ) )\r\n\r\n#define FT_NEXT_OFF3_LE( buffer )                                  \\\r\n          ( (long)( buffer += 3, FT_PEEK_OFF3_LE( buffer - 3 ) ) )\r\n\r\n#define FT_NEXT_UOFF3_LE( buffer )                                           \\\r\n          ( (unsigned long)( buffer += 3, FT_PEEK_UOFF3_LE( buffer - 3 ) ) )\r\n\r\n#define FT_NEXT_LONG_LE( buffer )                                  \\\r\n          ( (long)( buffer += 4, FT_PEEK_LONG_LE( buffer - 4 ) ) )\r\n\r\n#define FT_NEXT_ULONG_LE( buffer )                                           \\\r\n          ( (unsigned long)( buffer += 4, FT_PEEK_ULONG_LE( buffer - 4 ) ) )\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Each GET_xxxx() macro uses an implicit `stream' variable.             */\r\n  /*                                                                       */\r\n#if 0\r\n#define FT_GET_MACRO( type )    FT_NEXT_ ## type ( stream->cursor )\r\n\r\n#define FT_GET_CHAR()       FT_GET_MACRO( CHAR )\r\n#define FT_GET_BYTE()       FT_GET_MACRO( BYTE )\r\n#define FT_GET_SHORT()      FT_GET_MACRO( SHORT )\r\n#define FT_GET_USHORT()     FT_GET_MACRO( USHORT )\r\n#define FT_GET_OFF3()       FT_GET_MACRO( OFF3 )\r\n#define FT_GET_UOFF3()      FT_GET_MACRO( UOFF3 )\r\n#define FT_GET_LONG()       FT_GET_MACRO( LONG )\r\n#define FT_GET_ULONG()      FT_GET_MACRO( ULONG )\r\n#define FT_GET_TAG4()       FT_GET_MACRO( ULONG )\r\n\r\n#define FT_GET_SHORT_LE()   FT_GET_MACRO( SHORT_LE )\r\n#define FT_GET_USHORT_LE()  FT_GET_MACRO( USHORT_LE )\r\n#define FT_GET_LONG_LE()    FT_GET_MACRO( LONG_LE )\r\n#define FT_GET_ULONG_LE()   FT_GET_MACRO( ULONG_LE )\r\n\r\n#else\r\n#define FT_GET_MACRO( func, type )        ( (type)func( stream ) )\r\n\r\n#define FT_GET_CHAR()       FT_GET_MACRO( FT_Stream_GetChar, FT_Char )\r\n#define FT_GET_BYTE()       FT_GET_MACRO( FT_Stream_GetChar, FT_Byte )\r\n#define FT_GET_SHORT()      FT_GET_MACRO( FT_Stream_GetUShort, FT_Short )\r\n#define FT_GET_USHORT()     FT_GET_MACRO( FT_Stream_GetUShort, FT_UShort )\r\n#define FT_GET_OFF3()       FT_GET_MACRO( FT_Stream_GetUOffset, FT_Long )\r\n#define FT_GET_UOFF3()      FT_GET_MACRO( FT_Stream_GetUOffset, FT_ULong )\r\n#define FT_GET_LONG()       FT_GET_MACRO( FT_Stream_GetULong, FT_Long )\r\n#define FT_GET_ULONG()      FT_GET_MACRO( FT_Stream_GetULong, FT_ULong )\r\n#define FT_GET_TAG4()       FT_GET_MACRO( FT_Stream_GetULong, FT_ULong )\r\n\r\n#define FT_GET_SHORT_LE()   FT_GET_MACRO( FT_Stream_GetUShortLE, FT_Short )\r\n#define FT_GET_USHORT_LE()  FT_GET_MACRO( FT_Stream_GetUShortLE, FT_UShort )\r\n#define FT_GET_LONG_LE()    FT_GET_MACRO( FT_Stream_GetULongLE, FT_Long )\r\n#define FT_GET_ULONG_LE()   FT_GET_MACRO( FT_Stream_GetULongLE, FT_ULong )\r\n#endif\r\n\r\n#define FT_READ_MACRO( func, type, var )        \\\r\n          ( var = (type)func( stream, &error ), \\\r\n            error != FT_Err_Ok )\r\n\r\n#define FT_READ_BYTE( var )       FT_READ_MACRO( FT_Stream_ReadChar, FT_Byte, var )\r\n#define FT_READ_CHAR( var )       FT_READ_MACRO( FT_Stream_ReadChar, FT_Char, var )\r\n#define FT_READ_SHORT( var )      FT_READ_MACRO( FT_Stream_ReadUShort, FT_Short, var )\r\n#define FT_READ_USHORT( var )     FT_READ_MACRO( FT_Stream_ReadUShort, FT_UShort, var )\r\n#define FT_READ_OFF3( var )       FT_READ_MACRO( FT_Stream_ReadUOffset, FT_Long, var )\r\n#define FT_READ_UOFF3( var )      FT_READ_MACRO( FT_Stream_ReadUOffset, FT_ULong, var )\r\n#define FT_READ_LONG( var )       FT_READ_MACRO( FT_Stream_ReadULong, FT_Long, var )\r\n#define FT_READ_ULONG( var )      FT_READ_MACRO( FT_Stream_ReadULong, FT_ULong, var )\r\n\r\n#define FT_READ_SHORT_LE( var )   FT_READ_MACRO( FT_Stream_ReadUShortLE, FT_Short, var )\r\n#define FT_READ_USHORT_LE( var )  FT_READ_MACRO( FT_Stream_ReadUShortLE, FT_UShort, var )\r\n#define FT_READ_LONG_LE( var )    FT_READ_MACRO( FT_Stream_ReadULongLE, FT_Long, var )\r\n#define FT_READ_ULONG_LE( var )   FT_READ_MACRO( FT_Stream_ReadULongLE, FT_ULong, var )\r\n\r\n\r\n#ifndef FT_CONFIG_OPTION_NO_DEFAULT_SYSTEM\r\n\r\n  /* initialize a stream for reading a regular system stream */\r\n  FT_BASE( FT_Error )\r\n  FT_Stream_Open( FT_Stream    stream,\r\n                  const char*  filepathname );\r\n\r\n#endif /* FT_CONFIG_OPTION_NO_DEFAULT_SYSTEM */\r\n\r\n\r\n  /* create a new (input) stream from an FT_Open_Args structure */\r\n  FT_BASE( FT_Error )\r\n  FT_Stream_New( FT_Library           library,\r\n                 const FT_Open_Args*  args,\r\n                 FT_Stream           *astream );\r\n\r\n  /* free a stream */\r\n  FT_BASE( void )\r\n  FT_Stream_Free( FT_Stream  stream,\r\n                  FT_Int     external );\r\n\r\n  /* initialize a stream for reading in-memory data */\r\n  FT_BASE( void )\r\n  FT_Stream_OpenMemory( FT_Stream       stream,\r\n                        const FT_Byte*  base,\r\n                        FT_ULong        size );\r\n\r\n  /* close a stream (does not destroy the stream structure) */\r\n  FT_BASE( void )\r\n  FT_Stream_Close( FT_Stream  stream );\r\n\r\n\r\n  /* seek within a stream. position is relative to start of stream */\r\n  FT_BASE( FT_Error )\r\n  FT_Stream_Seek( FT_Stream  stream,\r\n                  FT_ULong   pos );\r\n\r\n  /* skip bytes in a stream */\r\n  FT_BASE( FT_Error )\r\n  FT_Stream_Skip( FT_Stream  stream,\r\n                  FT_Long    distance );\r\n\r\n  /* return current stream position */\r\n  FT_BASE( FT_Long )\r\n  FT_Stream_Pos( FT_Stream  stream );\r\n\r\n  /* read bytes from a stream into a user-allocated buffer, returns an */\r\n  /* error if not all bytes could be read.                             */\r\n  FT_BASE( FT_Error )\r\n  FT_Stream_Read( FT_Stream  stream,\r\n                  FT_Byte*   buffer,\r\n                  FT_ULong   count );\r\n\r\n  /* read bytes from a stream at a given position */\r\n  FT_BASE( FT_Error )\r\n  FT_Stream_ReadAt( FT_Stream  stream,\r\n                    FT_ULong   pos,\r\n                    FT_Byte*   buffer,\r\n                    FT_ULong   count );\r\n\r\n  /* try to read bytes at the end of a stream; return number of bytes */\r\n  /* really available                                                 */\r\n  FT_BASE( FT_ULong )\r\n  FT_Stream_TryRead( FT_Stream  stream,\r\n                     FT_Byte*   buffer,\r\n                     FT_ULong   count );\r\n\r\n  /* Enter a frame of `count' consecutive bytes in a stream.  Returns an */\r\n  /* error if the frame could not be read/accessed.  The caller can use  */\r\n  /* the FT_Stream_Get_XXX functions to retrieve frame data without      */\r\n  /* error checks.                                                       */\r\n  /*                                                                     */\r\n  /* You must _always_ call FT_Stream_ExitFrame() once you have entered  */\r\n  /* a stream frame!                                                     */\r\n  /*                                                                     */\r\n  FT_BASE( FT_Error )\r\n  FT_Stream_EnterFrame( FT_Stream  stream,\r\n                        FT_ULong   count );\r\n\r\n  /* exit a stream frame */\r\n  FT_BASE( void )\r\n  FT_Stream_ExitFrame( FT_Stream  stream );\r\n\r\n  /* Extract a stream frame.  If the stream is disk-based, a heap block */\r\n  /* is allocated and the frame bytes are read into it.  If the stream  */\r\n  /* is memory-based, this function simply set a pointer to the data.   */\r\n  /*                                                                    */\r\n  /* Useful to optimize access to memory-based streams transparently.   */\r\n  /*                                                                    */\r\n  /* All extracted frames must be `freed' with a call to the function   */\r\n  /* FT_Stream_ReleaseFrame().                                          */\r\n  /*                                                                    */\r\n  FT_BASE( FT_Error )\r\n  FT_Stream_ExtractFrame( FT_Stream  stream,\r\n                          FT_ULong   count,\r\n                          FT_Byte**  pbytes );\r\n\r\n  /* release an extract frame (see FT_Stream_ExtractFrame) */\r\n  FT_BASE( void )\r\n  FT_Stream_ReleaseFrame( FT_Stream  stream,\r\n                          FT_Byte**  pbytes );\r\n\r\n  /* read a byte from an entered frame */\r\n  FT_BASE( FT_Char )\r\n  FT_Stream_GetChar( FT_Stream  stream );\r\n\r\n  /* read a 16-bit big-endian unsigned integer from an entered frame */\r\n  FT_BASE( FT_UShort )\r\n  FT_Stream_GetUShort( FT_Stream  stream );\r\n\r\n  /* read a 24-bit big-endian unsigned integer from an entered frame */\r\n  FT_BASE( FT_ULong )\r\n  FT_Stream_GetUOffset( FT_Stream  stream );\r\n\r\n  /* read a 32-bit big-endian unsigned integer from an entered frame */\r\n  FT_BASE( FT_ULong )\r\n  FT_Stream_GetULong( FT_Stream  stream );\r\n\r\n  /* read a 16-bit little-endian unsigned integer from an entered frame */\r\n  FT_BASE( FT_UShort )\r\n  FT_Stream_GetUShortLE( FT_Stream  stream );\r\n\r\n  /* read a 32-bit little-endian unsigned integer from an entered frame */\r\n  FT_BASE( FT_ULong )\r\n  FT_Stream_GetULongLE( FT_Stream  stream );\r\n\r\n\r\n  /* read a byte from a stream */\r\n  FT_BASE( FT_Char )\r\n  FT_Stream_ReadChar( FT_Stream  stream,\r\n                      FT_Error*  error );\r\n\r\n  /* read a 16-bit big-endian unsigned integer from a stream */\r\n  FT_BASE( FT_UShort )\r\n  FT_Stream_ReadUShort( FT_Stream  stream,\r\n                        FT_Error*  error );\r\n\r\n  /* read a 24-bit big-endian unsigned integer from a stream */\r\n  FT_BASE( FT_ULong )\r\n  FT_Stream_ReadUOffset( FT_Stream  stream,\r\n                         FT_Error*  error );\r\n\r\n  /* read a 32-bit big-endian integer from a stream */\r\n  FT_BASE( FT_ULong )\r\n  FT_Stream_ReadULong( FT_Stream  stream,\r\n                       FT_Error*  error );\r\n\r\n  /* read a 16-bit little-endian unsigned integer from a stream */\r\n  FT_BASE( FT_UShort )\r\n  FT_Stream_ReadUShortLE( FT_Stream  stream,\r\n                          FT_Error*  error );\r\n\r\n  /* read a 32-bit little-endian unsigned integer from a stream */\r\n  FT_BASE( FT_ULong )\r\n  FT_Stream_ReadULongLE( FT_Stream  stream,\r\n                         FT_Error*  error );\r\n\r\n  /* Read a structure from a stream.  The structure must be described */\r\n  /* by an array of FT_Frame_Field records.                           */\r\n  FT_BASE( FT_Error )\r\n  FT_Stream_ReadFields( FT_Stream              stream,\r\n                        const FT_Frame_Field*  fields,\r\n                        void*                  structure );\r\n\r\n\r\n#define FT_STREAM_POS()           \\\r\n          FT_Stream_Pos( stream )\r\n\r\n#define FT_STREAM_SEEK( position )                           \\\r\n          FT_SET_ERROR( FT_Stream_Seek( stream, position ) )\r\n\r\n#define FT_STREAM_SKIP( distance )                           \\\r\n          FT_SET_ERROR( FT_Stream_Skip( stream, distance ) )\r\n\r\n#define FT_STREAM_READ( buffer, count )                   \\\r\n          FT_SET_ERROR( FT_Stream_Read( stream,           \\\r\n                                        (FT_Byte*)buffer, \\\r\n                                        count ) )\r\n\r\n#define FT_STREAM_READ_AT( position, buffer, count )         \\\r\n          FT_SET_ERROR( FT_Stream_ReadAt( stream,            \\\r\n                                           position,         \\\r\n                                           (FT_Byte*)buffer, \\\r\n                                           count ) )\r\n\r\n#define FT_STREAM_READ_FIELDS( fields, object )                          \\\r\n          FT_SET_ERROR( FT_Stream_ReadFields( stream, fields, object ) )\r\n\r\n\r\n#define FT_FRAME_ENTER( size )                                       \\\r\n          FT_SET_ERROR(                                              \\\r\n            FT_DEBUG_INNER( FT_Stream_EnterFrame( stream, size ) ) )\r\n\r\n#define FT_FRAME_EXIT()                 \\\r\n          FT_DEBUG_INNER( FT_Stream_ExitFrame( stream ) )\r\n\r\n#define FT_FRAME_EXTRACT( size, bytes )                                       \\\r\n          FT_SET_ERROR(                                                       \\\r\n            FT_DEBUG_INNER( FT_Stream_ExtractFrame( stream, size,             \\\r\n                                                    (FT_Byte**)&(bytes) ) ) )\r\n\r\n#define FT_FRAME_RELEASE( bytes )                                         \\\r\n          FT_DEBUG_INNER( FT_Stream_ReleaseFrame( stream,                 \\\r\n                                                  (FT_Byte**)&(bytes) ) )\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTSTREAM_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/fttrace.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  fttrace.h                                                              */\r\n/*                                                                         */\r\n/*    Tracing handling (specification only).                               */\r\n/*                                                                         */\r\n/*  Copyright 2002, 2004-2007, 2009, 2011 by                               */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n  /* definitions of trace levels for FreeType 2 */\r\n\r\n  /* the first level must always be `trace_any' */\r\nFT_TRACE_DEF( any )\r\n\r\n  /* base components */\r\nFT_TRACE_DEF( calc )      /* calculations            (ftcalc.c)   */\r\nFT_TRACE_DEF( memory )    /* memory manager          (ftobjs.c)   */\r\nFT_TRACE_DEF( stream )    /* stream manager          (ftstream.c) */\r\nFT_TRACE_DEF( io )        /* i/o interface           (ftsystem.c) */\r\nFT_TRACE_DEF( list )      /* list management         (ftlist.c)   */\r\nFT_TRACE_DEF( init )      /* initialization          (ftinit.c)   */\r\nFT_TRACE_DEF( objs )      /* base objects            (ftobjs.c)   */\r\nFT_TRACE_DEF( outline )   /* outline management      (ftoutln.c)  */\r\nFT_TRACE_DEF( glyph )     /* glyph management        (ftglyph.c)  */\r\nFT_TRACE_DEF( gloader )   /* glyph loader            (ftgloadr.c) */\r\n\r\nFT_TRACE_DEF( raster )    /* monochrome rasterizer   (ftraster.c) */\r\nFT_TRACE_DEF( smooth )    /* anti-aliasing raster    (ftgrays.c)  */\r\nFT_TRACE_DEF( mm )        /* MM interface            (ftmm.c)     */\r\nFT_TRACE_DEF( raccess )   /* resource fork accessor  (ftrfork.c)  */\r\nFT_TRACE_DEF( synth )     /* bold/slant synthesizer  (ftsynth.c)  */\r\n\r\n  /* Cache sub-system */\r\nFT_TRACE_DEF( cache )     /* cache sub-system        (ftcache.c, etc.) */\r\n\r\n  /* SFNT driver components */\r\nFT_TRACE_DEF( sfdriver )  /* SFNT font driver        (sfdriver.c) */\r\nFT_TRACE_DEF( sfobjs )    /* SFNT object handler     (sfobjs.c)   */\r\nFT_TRACE_DEF( ttcmap )    /* charmap handler         (ttcmap.c)   */\r\nFT_TRACE_DEF( ttkern )    /* kerning handler         (ttkern.c)   */\r\nFT_TRACE_DEF( ttload )    /* basic TrueType tables   (ttload.c)   */\r\nFT_TRACE_DEF( ttmtx )     /* metrics-related tables  (ttmtx.c)    */\r\nFT_TRACE_DEF( ttpost )    /* PS table processing     (ttpost.c)   */\r\nFT_TRACE_DEF( ttsbit )    /* TrueType sbit handling  (ttsbit.c)   */\r\nFT_TRACE_DEF( ttbdf )     /* TrueType embedded BDF   (ttbdf.c)    */\r\n\r\n  /* TrueType driver components */\r\nFT_TRACE_DEF( ttdriver )  /* TT font driver          (ttdriver.c) */\r\nFT_TRACE_DEF( ttgload )   /* TT glyph loader         (ttgload.c)  */\r\nFT_TRACE_DEF( ttinterp )  /* bytecode interpreter    (ttinterp.c) */\r\nFT_TRACE_DEF( ttobjs )    /* TT objects manager      (ttobjs.c)   */\r\nFT_TRACE_DEF( ttpload )   /* TT data/program loader  (ttpload.c)  */\r\nFT_TRACE_DEF( ttgxvar )   /* TrueType GX var handler (ttgxvar.c)  */\r\n\r\n  /* Type 1 driver components */\r\nFT_TRACE_DEF( t1afm )\r\nFT_TRACE_DEF( t1driver )\r\nFT_TRACE_DEF( t1gload )\r\nFT_TRACE_DEF( t1hint )\r\nFT_TRACE_DEF( t1load )\r\nFT_TRACE_DEF( t1objs )\r\nFT_TRACE_DEF( t1parse )\r\n\r\n  /* PostScript helper module `psaux' */\r\nFT_TRACE_DEF( t1decode )\r\nFT_TRACE_DEF( psobjs )\r\n\r\n  /* PostScript hinting module `pshinter' */\r\nFT_TRACE_DEF( pshrec )\r\nFT_TRACE_DEF( pshalgo1 )\r\nFT_TRACE_DEF( pshalgo2 )\r\n\r\n  /* Type 2 driver components */\r\nFT_TRACE_DEF( cffdriver )\r\nFT_TRACE_DEF( cffgload )\r\nFT_TRACE_DEF( cffload )\r\nFT_TRACE_DEF( cffobjs )\r\nFT_TRACE_DEF( cffparse )\r\n\r\n  /* Type 42 driver component */\r\nFT_TRACE_DEF( t42 )\r\n\r\n  /* CID driver components */\r\nFT_TRACE_DEF( cidafm )\r\nFT_TRACE_DEF( ciddriver )\r\nFT_TRACE_DEF( cidgload )\r\nFT_TRACE_DEF( cidload )\r\nFT_TRACE_DEF( cidobjs )\r\nFT_TRACE_DEF( cidparse )\r\n\r\n  /* Windows font component */\r\nFT_TRACE_DEF( winfnt )\r\n\r\n  /* PCF font components */\r\nFT_TRACE_DEF( pcfdriver )\r\nFT_TRACE_DEF( pcfread )\r\n\r\n  /* BDF font components */\r\nFT_TRACE_DEF( bdfdriver )\r\nFT_TRACE_DEF( bdflib )\r\n\r\n  /* PFR font component */\r\nFT_TRACE_DEF( pfr )\r\n\r\n  /* OpenType validation components */\r\nFT_TRACE_DEF( otvmodule )\r\nFT_TRACE_DEF( otvcommon )\r\nFT_TRACE_DEF( otvbase )\r\nFT_TRACE_DEF( otvgdef )\r\nFT_TRACE_DEF( otvgpos )\r\nFT_TRACE_DEF( otvgsub )\r\nFT_TRACE_DEF( otvjstf )\r\nFT_TRACE_DEF( otvmath )\r\n\r\n  /* TrueTypeGX/AAT validation components */\r\nFT_TRACE_DEF( gxvmodule )\r\nFT_TRACE_DEF( gxvcommon )\r\nFT_TRACE_DEF( gxvfeat )\r\nFT_TRACE_DEF( gxvmort )\r\nFT_TRACE_DEF( gxvmorx )\r\nFT_TRACE_DEF( gxvbsln )\r\nFT_TRACE_DEF( gxvjust )\r\nFT_TRACE_DEF( gxvkern )\r\nFT_TRACE_DEF( gxvopbd )\r\nFT_TRACE_DEF( gxvtrak )\r\nFT_TRACE_DEF( gxvprop )\r\nFT_TRACE_DEF( gxvlcar )\r\n\r\n  /* autofit components */\r\nFT_TRACE_DEF( afcjk )\r\nFT_TRACE_DEF( aflatin )\r\nFT_TRACE_DEF( aflatin2 )\r\nFT_TRACE_DEF( afwarp )\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/ftvalid.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ftvalid.h                                                              */\r\n/*                                                                         */\r\n/*    FreeType validation support (specification).                         */\r\n/*                                                                         */\r\n/*  Copyright 2004 by                                                      */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __FTVALID_H__\r\n#define __FTVALID_H__\r\n\r\n#include <ft2build.h>\r\n#include FT_CONFIG_STANDARD_LIBRARY_H   /* for ft_setjmp and ft_longjmp */\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /****                                                                 ****/\r\n  /****                                                                 ****/\r\n  /****                    V A L I D A T I O N                          ****/\r\n  /****                                                                 ****/\r\n  /****                                                                 ****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n  /* handle to a validation object */\r\n  typedef struct FT_ValidatorRec_ volatile*  FT_Validator;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* There are three distinct validation levels defined here:              */\r\n  /*                                                                       */\r\n  /* FT_VALIDATE_DEFAULT ::                                                */\r\n  /*   A table that passes this validation level can be used reliably by   */\r\n  /*   FreeType.  It generally means that all offsets have been checked to */\r\n  /*   prevent out-of-bound reads, that array counts are correct, etc.     */\r\n  /*                                                                       */\r\n  /* FT_VALIDATE_TIGHT ::                                                  */\r\n  /*   A table that passes this validation level can be used reliably and  */\r\n  /*   doesn't contain invalid data.  For example, a charmap table that    */\r\n  /*   returns invalid glyph indices will not pass, even though it can     */\r\n  /*   be used with FreeType in default mode (the library will simply      */\r\n  /*   return an error later when trying to load the glyph).               */\r\n  /*                                                                       */\r\n  /*   It also checks that fields which must be a multiple of 2, 4, or 8,  */\r\n  /*   don't have incorrect values, etc.                                   */\r\n  /*                                                                       */\r\n  /* FT_VALIDATE_PARANOID ::                                               */\r\n  /*   Only for font debugging.  Checks that a table follows the           */\r\n  /*   specification by 100%.  Very few fonts will be able to pass this    */\r\n  /*   level anyway but it can be useful for certain tools like font       */\r\n  /*   editors/converters.                                                 */\r\n  /*                                                                       */\r\n  typedef enum  FT_ValidationLevel_\r\n  {\r\n    FT_VALIDATE_DEFAULT = 0,\r\n    FT_VALIDATE_TIGHT,\r\n    FT_VALIDATE_PARANOID\r\n\r\n  } FT_ValidationLevel;\r\n\r\n\r\n  /* validator structure */\r\n  typedef struct  FT_ValidatorRec_\r\n  {\r\n    const FT_Byte*      base;        /* address of table in memory       */\r\n    const FT_Byte*      limit;       /* `base' + sizeof(table) in memory */\r\n    FT_ValidationLevel  level;       /* validation level                 */\r\n    FT_Error            error;       /* error returned. 0 means success  */\r\n\r\n    ft_jmp_buf          jump_buffer; /* used for exception handling      */\r\n\r\n  } FT_ValidatorRec;\r\n\r\n\r\n#define FT_VALIDATOR( x )  ((FT_Validator)( x ))\r\n\r\n\r\n  FT_BASE( void )\r\n  ft_validator_init( FT_Validator        valid,\r\n                     const FT_Byte*      base,\r\n                     const FT_Byte*      limit,\r\n                     FT_ValidationLevel  level );\r\n\r\n  /* Do not use this. It's broken and will cause your validator to crash */\r\n  /* if you run it on an invalid font.                                   */\r\n  FT_BASE( FT_Int )\r\n  ft_validator_run( FT_Validator  valid );\r\n\r\n  /* Sets the error field in a validator, then calls `longjmp' to return */\r\n  /* to high-level caller.  Using `setjmp/longjmp' avoids many stupid    */\r\n  /* error checks within the validation routines.                        */\r\n  /*                                                                     */\r\n  FT_BASE( void )\r\n  ft_validator_error( FT_Validator  valid,\r\n                      FT_Error      error );\r\n\r\n\r\n  /* Calls ft_validate_error.  Assumes that the `valid' local variable */\r\n  /* holds a pointer to the current validator object.                  */\r\n  /*                                                                   */\r\n  /* Use preprocessor prescan to pass FT_ERR_PREFIX.                   */\r\n  /*                                                                   */\r\n#define FT_INVALID( _prefix, _error )  FT_INVALID_( _prefix, _error )\r\n#define FT_INVALID_( _prefix, _error ) \\\r\n          ft_validator_error( valid, _prefix ## _error )\r\n\r\n  /* called when a broken table is detected */\r\n#define FT_INVALID_TOO_SHORT \\\r\n          FT_INVALID( FT_ERR_PREFIX, Invalid_Table )\r\n\r\n  /* called when an invalid offset is detected */\r\n#define FT_INVALID_OFFSET \\\r\n          FT_INVALID( FT_ERR_PREFIX, Invalid_Offset )\r\n\r\n  /* called when an invalid format/value is detected */\r\n#define FT_INVALID_FORMAT \\\r\n          FT_INVALID( FT_ERR_PREFIX, Invalid_Table )\r\n\r\n  /* called when an invalid glyph index is detected */\r\n#define FT_INVALID_GLYPH_ID \\\r\n          FT_INVALID( FT_ERR_PREFIX, Invalid_Glyph_Index )\r\n\r\n  /* called when an invalid field value is detected */\r\n#define FT_INVALID_DATA \\\r\n          FT_INVALID( FT_ERR_PREFIX, Invalid_Table )\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __FTVALID_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/internal.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  internal.h                                                             */\r\n/*                                                                         */\r\n/*    Internal header files (specification only).                          */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2002, 2003, 2004 by                               */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* This file is automatically included by `ft2build.h'.                  */\r\n  /* Do not include it manually!                                           */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n#define FT_INTERNAL_OBJECTS_H             <freetype/internal/ftobjs.h>\r\n#define FT_INTERNAL_PIC_H                 <freetype/internal/ftpic.h>\r\n#define FT_INTERNAL_STREAM_H              <freetype/internal/ftstream.h>\r\n#define FT_INTERNAL_MEMORY_H              <freetype/internal/ftmemory.h>\r\n#define FT_INTERNAL_DEBUG_H               <freetype/internal/ftdebug.h>\r\n#define FT_INTERNAL_CALC_H                <freetype/internal/ftcalc.h>\r\n#define FT_INTERNAL_DRIVER_H              <freetype/internal/ftdriver.h>\r\n#define FT_INTERNAL_TRACE_H               <freetype/internal/fttrace.h>\r\n#define FT_INTERNAL_GLYPH_LOADER_H        <freetype/internal/ftgloadr.h>\r\n#define FT_INTERNAL_SFNT_H                <freetype/internal/sfnt.h>\r\n#define FT_INTERNAL_SERVICE_H             <freetype/internal/ftserv.h>\r\n#define FT_INTERNAL_RFORK_H               <freetype/internal/ftrfork.h>\r\n#define FT_INTERNAL_VALIDATE_H            <freetype/internal/ftvalid.h>\r\n\r\n#define FT_INTERNAL_TRUETYPE_TYPES_H      <freetype/internal/tttypes.h>\r\n#define FT_INTERNAL_TYPE1_TYPES_H         <freetype/internal/t1types.h>\r\n\r\n#define FT_INTERNAL_POSTSCRIPT_AUX_H      <freetype/internal/psaux.h>\r\n#define FT_INTERNAL_POSTSCRIPT_HINTS_H    <freetype/internal/pshints.h>\r\n#define FT_INTERNAL_POSTSCRIPT_GLOBALS_H  <freetype/internal/psglobal.h>\r\n\r\n#define FT_INTERNAL_AUTOHINT_H            <freetype/internal/autohint.h>\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/psaux.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  psaux.h                                                                */\r\n/*                                                                         */\r\n/*    Auxiliary functions and data structures related to PostScript fonts  */\r\n/*    (specification).                                                     */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2002, 2003, 2004, 2006, 2008, 2009 by             */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __PSAUX_H__\r\n#define __PSAUX_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_INTERNAL_OBJECTS_H\r\n#include FT_INTERNAL_TYPE1_TYPES_H\r\n#include FT_SERVICE_POSTSCRIPT_CMAPS_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*****                                                               *****/\r\n  /*****                             T1_TABLE                          *****/\r\n  /*****                                                               *****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  typedef struct PS_TableRec_*              PS_Table;\r\n  typedef const struct PS_Table_FuncsRec_*  PS_Table_Funcs;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    PS_Table_FuncsRec                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A set of function pointers to manage PS_Table objects.             */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    table_init    :: Used to initialize a table.                       */\r\n  /*                                                                       */\r\n  /*    table_done    :: Finalizes resp. destroy a given table.            */\r\n  /*                                                                       */\r\n  /*    table_add     :: Adds a new object to a table.                     */\r\n  /*                                                                       */\r\n  /*    table_release :: Releases table data, then finalizes it.           */\r\n  /*                                                                       */\r\n  typedef struct  PS_Table_FuncsRec_\r\n  {\r\n    FT_Error\r\n    (*init)( PS_Table   table,\r\n             FT_Int     count,\r\n             FT_Memory  memory );\r\n\r\n    void\r\n    (*done)( PS_Table  table );\r\n\r\n    FT_Error\r\n    (*add)( PS_Table    table,\r\n            FT_Int      idx,\r\n            void*       object,\r\n            FT_PtrDist  length );\r\n\r\n    void\r\n    (*release)( PS_Table  table );\r\n\r\n  } PS_Table_FuncsRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    PS_TableRec                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A PS_Table is a simple object used to store an array of objects in */\r\n  /*    a single memory block.                                             */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    block     :: The address in memory of the growheap's block.  This  */\r\n  /*                 can change between two object adds, due to            */\r\n  /*                 reallocation.                                         */\r\n  /*                                                                       */\r\n  /*    cursor    :: The current top of the grow heap within its block.    */\r\n  /*                                                                       */\r\n  /*    capacity  :: The current size of the heap block.  Increments by    */\r\n  /*                 1kByte chunks.                                        */\r\n  /*                                                                       */\r\n  /*    max_elems :: The maximum number of elements in table.              */\r\n  /*                                                                       */\r\n  /*    num_elems :: The current number of elements in table.              */\r\n  /*                                                                       */\r\n  /*    elements  :: A table of element addresses within the block.        */\r\n  /*                                                                       */\r\n  /*    lengths   :: A table of element sizes within the block.            */\r\n  /*                                                                       */\r\n  /*    memory    :: The object used for memory operations                 */\r\n  /*                 (alloc/realloc).                                      */\r\n  /*                                                                       */\r\n  /*    funcs     :: A table of method pointers for this object.           */\r\n  /*                                                                       */\r\n  typedef struct  PS_TableRec_\r\n  {\r\n    FT_Byte*           block;          /* current memory block           */\r\n    FT_Offset          cursor;         /* current cursor in memory block */\r\n    FT_Offset          capacity;       /* current size of memory block   */\r\n    FT_Long            init;\r\n\r\n    FT_Int             max_elems;\r\n    FT_Int             num_elems;\r\n    FT_Byte**          elements;       /* addresses of table elements */\r\n    FT_PtrDist*        lengths;        /* lengths of table elements   */\r\n\r\n    FT_Memory          memory;\r\n    PS_Table_FuncsRec  funcs;\r\n\r\n  } PS_TableRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*****                                                               *****/\r\n  /*****                       T1 FIELDS & TOKENS                      *****/\r\n  /*****                                                               *****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n  typedef struct PS_ParserRec_*  PS_Parser;\r\n\r\n  typedef struct T1_TokenRec_*   T1_Token;\r\n\r\n  typedef struct T1_FieldRec_*   T1_Field;\r\n\r\n\r\n  /* simple enumeration type used to identify token types */\r\n  typedef enum  T1_TokenType_\r\n  {\r\n    T1_TOKEN_TYPE_NONE = 0,\r\n    T1_TOKEN_TYPE_ANY,\r\n    T1_TOKEN_TYPE_STRING,\r\n    T1_TOKEN_TYPE_ARRAY,\r\n    T1_TOKEN_TYPE_KEY, /* aka `name' */\r\n\r\n    /* do not remove */\r\n    T1_TOKEN_TYPE_MAX\r\n\r\n  } T1_TokenType;\r\n\r\n\r\n  /* a simple structure used to identify tokens */\r\n  typedef struct  T1_TokenRec_\r\n  {\r\n    FT_Byte*      start;   /* first character of token in input stream */\r\n    FT_Byte*      limit;   /* first character after the token          */\r\n    T1_TokenType  type;    /* type of token                            */\r\n\r\n  } T1_TokenRec;\r\n\r\n\r\n  /* enumeration type used to identify object fields */\r\n  typedef enum  T1_FieldType_\r\n  {\r\n    T1_FIELD_TYPE_NONE = 0,\r\n    T1_FIELD_TYPE_BOOL,\r\n    T1_FIELD_TYPE_INTEGER,\r\n    T1_FIELD_TYPE_FIXED,\r\n    T1_FIELD_TYPE_FIXED_1000,\r\n    T1_FIELD_TYPE_STRING,\r\n    T1_FIELD_TYPE_KEY,\r\n    T1_FIELD_TYPE_BBOX,\r\n    T1_FIELD_TYPE_INTEGER_ARRAY,\r\n    T1_FIELD_TYPE_FIXED_ARRAY,\r\n    T1_FIELD_TYPE_CALLBACK,\r\n\r\n    /* do not remove */\r\n    T1_FIELD_TYPE_MAX\r\n\r\n  } T1_FieldType;\r\n\r\n\r\n  typedef enum  T1_FieldLocation_\r\n  {\r\n    T1_FIELD_LOCATION_CID_INFO,\r\n    T1_FIELD_LOCATION_FONT_DICT,\r\n    T1_FIELD_LOCATION_FONT_EXTRA,\r\n    T1_FIELD_LOCATION_FONT_INFO,\r\n    T1_FIELD_LOCATION_PRIVATE,\r\n    T1_FIELD_LOCATION_BBOX,\r\n    T1_FIELD_LOCATION_LOADER,\r\n    T1_FIELD_LOCATION_FACE,\r\n    T1_FIELD_LOCATION_BLEND,\r\n\r\n    /* do not remove */\r\n    T1_FIELD_LOCATION_MAX\r\n\r\n  } T1_FieldLocation;\r\n\r\n\r\n  typedef void\r\n  (*T1_Field_ParseFunc)( FT_Face     face,\r\n                         FT_Pointer  parser );\r\n\r\n\r\n  /* structure type used to model object fields */\r\n  typedef struct  T1_FieldRec_\r\n  {\r\n    const char*         ident;        /* field identifier               */\r\n    T1_FieldLocation    location;\r\n    T1_FieldType        type;         /* type of field                  */\r\n    T1_Field_ParseFunc  reader;\r\n    FT_UInt             offset;       /* offset of field in object      */\r\n    FT_Byte             size;         /* size of field in bytes         */\r\n    FT_UInt             array_max;    /* maximal number of elements for */\r\n                                      /* array                          */\r\n    FT_UInt             count_offset; /* offset of element count for    */\r\n                                      /* arrays; must not be zero if in */\r\n                                      /* use -- in other words, a       */\r\n                                      /* `num_FOO' element must not     */\r\n                                      /* start the used structure if we */\r\n                                      /* parse a `FOO' array            */\r\n    FT_UInt             dict;         /* where we expect it             */\r\n  } T1_FieldRec;\r\n\r\n#define T1_FIELD_DICT_FONTDICT ( 1 << 0 ) /* also FontInfo and FDArray */\r\n#define T1_FIELD_DICT_PRIVATE  ( 1 << 1 )\r\n\r\n\r\n\r\n#define T1_NEW_SIMPLE_FIELD( _ident, _type, _fname, _dict ) \\\r\n          {                                                 \\\r\n            _ident, T1CODE, _type,                          \\\r\n            0,                                              \\\r\n            FT_FIELD_OFFSET( _fname ),                      \\\r\n            FT_FIELD_SIZE( _fname ),                        \\\r\n            0, 0,                                           \\\r\n            _dict                                           \\\r\n          },\r\n\r\n#define T1_NEW_CALLBACK_FIELD( _ident, _reader, _dict ) \\\r\n          {                                             \\\r\n            _ident, T1CODE, T1_FIELD_TYPE_CALLBACK,     \\\r\n            (T1_Field_ParseFunc)_reader,                \\\r\n            0, 0,                                       \\\r\n            0, 0,                                       \\\r\n            _dict                                       \\\r\n          },\r\n\r\n#define T1_NEW_TABLE_FIELD( _ident, _type, _fname, _max, _dict ) \\\r\n          {                                                      \\\r\n            _ident, T1CODE, _type,                               \\\r\n            0,                                                   \\\r\n            FT_FIELD_OFFSET( _fname ),                           \\\r\n            FT_FIELD_SIZE_DELTA( _fname ),                       \\\r\n            _max,                                                \\\r\n            FT_FIELD_OFFSET( num_ ## _fname ),                   \\\r\n            _dict                                                \\\r\n          },\r\n\r\n#define T1_NEW_TABLE_FIELD2( _ident, _type, _fname, _max, _dict ) \\\r\n          {                                                       \\\r\n            _ident, T1CODE, _type,                                \\\r\n            0,                                                    \\\r\n            FT_FIELD_OFFSET( _fname ),                            \\\r\n            FT_FIELD_SIZE_DELTA( _fname ),                        \\\r\n            _max, 0,                                              \\\r\n            _dict                                                 \\\r\n          },\r\n\r\n\r\n#define T1_FIELD_BOOL( _ident, _fname, _dict )                             \\\r\n          T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_BOOL, _fname, _dict )\r\n\r\n#define T1_FIELD_NUM( _ident, _fname, _dict )                                 \\\r\n          T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_INTEGER, _fname, _dict )\r\n\r\n#define T1_FIELD_FIXED( _ident, _fname, _dict )                             \\\r\n          T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_FIXED, _fname, _dict )\r\n\r\n#define T1_FIELD_FIXED_1000( _ident, _fname, _dict )                     \\\r\n          T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_FIXED_1000, _fname, \\\r\n                               _dict )\r\n\r\n#define T1_FIELD_STRING( _ident, _fname, _dict )                             \\\r\n          T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_STRING, _fname, _dict )\r\n\r\n#define T1_FIELD_KEY( _ident, _fname, _dict )                             \\\r\n          T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_KEY, _fname, _dict )\r\n\r\n#define T1_FIELD_BBOX( _ident, _fname, _dict )                             \\\r\n          T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_BBOX, _fname, _dict )\r\n\r\n\r\n#define T1_FIELD_NUM_TABLE( _ident, _fname, _fmax, _dict )         \\\r\n          T1_NEW_TABLE_FIELD( _ident, T1_FIELD_TYPE_INTEGER_ARRAY, \\\r\n                              _fname, _fmax, _dict )\r\n\r\n#define T1_FIELD_FIXED_TABLE( _ident, _fname, _fmax, _dict )     \\\r\n          T1_NEW_TABLE_FIELD( _ident, T1_FIELD_TYPE_FIXED_ARRAY, \\\r\n                              _fname, _fmax, _dict )\r\n\r\n#define T1_FIELD_NUM_TABLE2( _ident, _fname, _fmax, _dict )         \\\r\n          T1_NEW_TABLE_FIELD2( _ident, T1_FIELD_TYPE_INTEGER_ARRAY, \\\r\n                               _fname, _fmax, _dict )\r\n\r\n#define T1_FIELD_FIXED_TABLE2( _ident, _fname, _fmax, _dict )     \\\r\n          T1_NEW_TABLE_FIELD2( _ident, T1_FIELD_TYPE_FIXED_ARRAY, \\\r\n                               _fname, _fmax, _dict )\r\n\r\n#define T1_FIELD_CALLBACK( _ident, _name, _dict )       \\\r\n          T1_NEW_CALLBACK_FIELD( _ident, _name, _dict )\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*****                                                               *****/\r\n  /*****                            T1 PARSER                          *****/\r\n  /*****                                                               *****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n  typedef const struct PS_Parser_FuncsRec_*  PS_Parser_Funcs;\r\n\r\n  typedef struct  PS_Parser_FuncsRec_\r\n  {\r\n    void\r\n    (*init)( PS_Parser  parser,\r\n             FT_Byte*   base,\r\n             FT_Byte*   limit,\r\n             FT_Memory  memory );\r\n\r\n    void\r\n    (*done)( PS_Parser  parser );\r\n\r\n    void\r\n    (*skip_spaces)( PS_Parser  parser );\r\n    void\r\n    (*skip_PS_token)( PS_Parser  parser );\r\n\r\n    FT_Long\r\n    (*to_int)( PS_Parser  parser );\r\n    FT_Fixed\r\n    (*to_fixed)( PS_Parser  parser,\r\n                 FT_Int     power_ten );\r\n\r\n    FT_Error\r\n    (*to_bytes)( PS_Parser  parser,\r\n                 FT_Byte*   bytes,\r\n                 FT_Offset  max_bytes,\r\n                 FT_Long*   pnum_bytes,\r\n                 FT_Bool    delimiters );\r\n\r\n    FT_Int\r\n    (*to_coord_array)( PS_Parser  parser,\r\n                       FT_Int     max_coords,\r\n                       FT_Short*  coords );\r\n    FT_Int\r\n    (*to_fixed_array)( PS_Parser  parser,\r\n                       FT_Int     max_values,\r\n                       FT_Fixed*  values,\r\n                       FT_Int     power_ten );\r\n\r\n    void\r\n    (*to_token)( PS_Parser  parser,\r\n                 T1_Token   token );\r\n    void\r\n    (*to_token_array)( PS_Parser  parser,\r\n                       T1_Token   tokens,\r\n                       FT_UInt    max_tokens,\r\n                       FT_Int*    pnum_tokens );\r\n\r\n    FT_Error\r\n    (*load_field)( PS_Parser       parser,\r\n                   const T1_Field  field,\r\n                   void**          objects,\r\n                   FT_UInt         max_objects,\r\n                   FT_ULong*       pflags );\r\n\r\n    FT_Error\r\n    (*load_field_table)( PS_Parser       parser,\r\n                         const T1_Field  field,\r\n                         void**          objects,\r\n                         FT_UInt         max_objects,\r\n                         FT_ULong*       pflags );\r\n\r\n  } PS_Parser_FuncsRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    PS_ParserRec                                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A PS_Parser is an object used to parse a Type 1 font very quickly. */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    cursor :: The current position in the text.                        */\r\n  /*                                                                       */\r\n  /*    base   :: Start of the processed text.                             */\r\n  /*                                                                       */\r\n  /*    limit  :: End of the processed text.                               */\r\n  /*                                                                       */\r\n  /*    error  :: The last error returned.                                 */\r\n  /*                                                                       */\r\n  /*    memory :: The object used for memory operations (alloc/realloc).   */\r\n  /*                                                                       */\r\n  /*    funcs  :: A table of functions for the parser.                     */\r\n  /*                                                                       */\r\n  typedef struct  PS_ParserRec_\r\n  {\r\n    FT_Byte*   cursor;\r\n    FT_Byte*   base;\r\n    FT_Byte*   limit;\r\n    FT_Error   error;\r\n    FT_Memory  memory;\r\n\r\n    PS_Parser_FuncsRec  funcs;\r\n\r\n  } PS_ParserRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*****                                                               *****/\r\n  /*****                         T1 BUILDER                            *****/\r\n  /*****                                                               *****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  typedef struct T1_BuilderRec_*  T1_Builder;\r\n\r\n\r\n  typedef FT_Error\r\n  (*T1_Builder_Check_Points_Func)( T1_Builder  builder,\r\n                                   FT_Int      count );\r\n\r\n  typedef void\r\n  (*T1_Builder_Add_Point_Func)( T1_Builder  builder,\r\n                                FT_Pos      x,\r\n                                FT_Pos      y,\r\n                                FT_Byte     flag );\r\n\r\n  typedef FT_Error\r\n  (*T1_Builder_Add_Point1_Func)( T1_Builder  builder,\r\n                                 FT_Pos      x,\r\n                                 FT_Pos      y );\r\n\r\n  typedef FT_Error\r\n  (*T1_Builder_Add_Contour_Func)( T1_Builder  builder );\r\n\r\n  typedef FT_Error\r\n  (*T1_Builder_Start_Point_Func)( T1_Builder  builder,\r\n                                  FT_Pos      x,\r\n                                  FT_Pos      y );\r\n\r\n  typedef void\r\n  (*T1_Builder_Close_Contour_Func)( T1_Builder  builder );\r\n\r\n\r\n  typedef const struct T1_Builder_FuncsRec_*  T1_Builder_Funcs;\r\n\r\n  typedef struct  T1_Builder_FuncsRec_\r\n  {\r\n    void\r\n    (*init)( T1_Builder    builder,\r\n             FT_Face       face,\r\n             FT_Size       size,\r\n             FT_GlyphSlot  slot,\r\n             FT_Bool       hinting );\r\n\r\n    void\r\n    (*done)( T1_Builder   builder );\r\n\r\n    T1_Builder_Check_Points_Func   check_points;\r\n    T1_Builder_Add_Point_Func      add_point;\r\n    T1_Builder_Add_Point1_Func     add_point1;\r\n    T1_Builder_Add_Contour_Func    add_contour;\r\n    T1_Builder_Start_Point_Func    start_point;\r\n    T1_Builder_Close_Contour_Func  close_contour;\r\n\r\n  } T1_Builder_FuncsRec;\r\n\r\n\r\n  /* an enumeration type to handle charstring parsing states */\r\n  typedef enum  T1_ParseState_\r\n  {\r\n    T1_Parse_Start,\r\n    T1_Parse_Have_Width,\r\n    T1_Parse_Have_Moveto,\r\n    T1_Parse_Have_Path\r\n\r\n  } T1_ParseState;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Structure>                                                           */\r\n  /*    T1_BuilderRec                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*     A structure used during glyph loading to store its outline.       */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    memory       :: The current memory object.                         */\r\n  /*                                                                       */\r\n  /*    face         :: The current face object.                           */\r\n  /*                                                                       */\r\n  /*    glyph        :: The current glyph slot.                            */\r\n  /*                                                                       */\r\n  /*    loader       :: XXX                                                */\r\n  /*                                                                       */\r\n  /*    base         :: The base glyph outline.                            */\r\n  /*                                                                       */\r\n  /*    current      :: The current glyph outline.                         */\r\n  /*                                                                       */\r\n  /*    max_points   :: maximum points in builder outline                  */\r\n  /*                                                                       */\r\n  /*    max_contours :: Maximal number of contours in builder outline.     */\r\n  /*                                                                       */\r\n  /*    pos_x        :: The horizontal translation (if composite glyph).   */\r\n  /*                                                                       */\r\n  /*    pos_y        :: The vertical translation (if composite glyph).     */\r\n  /*                                                                       */\r\n  /*    left_bearing :: The left side bearing point.                       */\r\n  /*                                                                       */\r\n  /*    advance      :: The horizontal advance vector.                     */\r\n  /*                                                                       */\r\n  /*    bbox         :: Unused.                                            */\r\n  /*                                                                       */\r\n  /*    parse_state  :: An enumeration which controls the charstring       */\r\n  /*                    parsing state.                                     */\r\n  /*                                                                       */\r\n  /*    load_points  :: If this flag is not set, no points are loaded.     */\r\n  /*                                                                       */\r\n  /*    no_recurse   :: Set but not used.                                  */\r\n  /*                                                                       */\r\n  /*    metrics_only :: A boolean indicating that we only want to compute  */\r\n  /*                    the metrics of a given glyph, not load all of its  */\r\n  /*                    points.                                            */\r\n  /*                                                                       */\r\n  /*    funcs        :: An array of function pointers for the builder.     */\r\n  /*                                                                       */\r\n  typedef struct  T1_BuilderRec_\r\n  {\r\n    FT_Memory       memory;\r\n    FT_Face         face;\r\n    FT_GlyphSlot    glyph;\r\n    FT_GlyphLoader  loader;\r\n    FT_Outline*     base;\r\n    FT_Outline*     current;\r\n\r\n    FT_Pos          pos_x;\r\n    FT_Pos          pos_y;\r\n\r\n    FT_Vector       left_bearing;\r\n    FT_Vector       advance;\r\n\r\n    FT_BBox         bbox;          /* bounding box */\r\n    T1_ParseState   parse_state;\r\n    FT_Bool         load_points;\r\n    FT_Bool         no_recurse;\r\n\r\n    FT_Bool         metrics_only;\r\n\r\n    void*           hints_funcs;    /* hinter-specific */\r\n    void*           hints_globals;  /* hinter-specific */\r\n\r\n    T1_Builder_FuncsRec  funcs;\r\n\r\n  } T1_BuilderRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*****                                                               *****/\r\n  /*****                         T1 DECODER                            *****/\r\n  /*****                                                               *****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n#if 0\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* T1_MAX_SUBRS_CALLS details the maximum number of nested sub-routine   */\r\n  /* calls during glyph loading.                                           */\r\n  /*                                                                       */\r\n#define T1_MAX_SUBRS_CALLS  8\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* T1_MAX_CHARSTRING_OPERANDS is the charstring stack's capacity.  A     */\r\n  /* minimum of 16 is required.                                            */\r\n  /*                                                                       */\r\n#define T1_MAX_CHARSTRINGS_OPERANDS  32\r\n\r\n#endif /* 0 */\r\n\r\n\r\n  typedef struct  T1_Decoder_ZoneRec_\r\n  {\r\n    FT_Byte*  cursor;\r\n    FT_Byte*  base;\r\n    FT_Byte*  limit;\r\n\r\n  } T1_Decoder_ZoneRec, *T1_Decoder_Zone;\r\n\r\n\r\n  typedef struct T1_DecoderRec_*              T1_Decoder;\r\n  typedef const struct T1_Decoder_FuncsRec_*  T1_Decoder_Funcs;\r\n\r\n\r\n  typedef FT_Error\r\n  (*T1_Decoder_Callback)( T1_Decoder  decoder,\r\n                          FT_UInt     glyph_index );\r\n\r\n\r\n  typedef struct  T1_Decoder_FuncsRec_\r\n  {\r\n    FT_Error\r\n    (*init)( T1_Decoder           decoder,\r\n             FT_Face              face,\r\n             FT_Size              size,\r\n             FT_GlyphSlot         slot,\r\n             FT_Byte**            glyph_names,\r\n             PS_Blend             blend,\r\n             FT_Bool              hinting,\r\n             FT_Render_Mode       hint_mode,\r\n             T1_Decoder_Callback  callback );\r\n\r\n    void\r\n    (*done)( T1_Decoder  decoder );\r\n\r\n    FT_Error\r\n    (*parse_charstrings)( T1_Decoder  decoder,\r\n                          FT_Byte*    base,\r\n                          FT_UInt     len );\r\n\r\n  } T1_Decoder_FuncsRec;\r\n\r\n\r\n  typedef struct  T1_DecoderRec_\r\n  {\r\n    T1_BuilderRec        builder;\r\n\r\n    FT_Long              stack[T1_MAX_CHARSTRINGS_OPERANDS];\r\n    FT_Long*             top;\r\n\r\n    T1_Decoder_ZoneRec   zones[T1_MAX_SUBRS_CALLS + 1];\r\n    T1_Decoder_Zone      zone;\r\n\r\n    FT_Service_PsCMaps   psnames;      /* for seac */\r\n    FT_UInt              num_glyphs;\r\n    FT_Byte**            glyph_names;\r\n\r\n    FT_Int               lenIV;        /* internal for sub routine calls */\r\n    FT_UInt              num_subrs;\r\n    FT_Byte**            subrs;\r\n    FT_PtrDist*          subrs_len;    /* array of subrs length (optional) */\r\n\r\n    FT_Matrix            font_matrix;\r\n    FT_Vector            font_offset;\r\n\r\n    FT_Int               flex_state;\r\n    FT_Int               num_flex_vectors;\r\n    FT_Vector            flex_vectors[7];\r\n\r\n    PS_Blend             blend;       /* for multiple master support */\r\n\r\n    FT_Render_Mode       hint_mode;\r\n\r\n    T1_Decoder_Callback  parse_callback;\r\n    T1_Decoder_FuncsRec  funcs;\r\n\r\n    FT_Long*             buildchar;\r\n    FT_UInt              len_buildchar;\r\n\r\n    FT_Bool              seac;\r\n\r\n  } T1_DecoderRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*****                                                               *****/\r\n  /*****                            AFM PARSER                         *****/\r\n  /*****                                                               *****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n  typedef struct AFM_ParserRec_*  AFM_Parser;\r\n\r\n  typedef struct  AFM_Parser_FuncsRec_\r\n  {\r\n    FT_Error\r\n    (*init)( AFM_Parser  parser,\r\n             FT_Memory   memory,\r\n             FT_Byte*    base,\r\n             FT_Byte*    limit );\r\n\r\n    void\r\n    (*done)( AFM_Parser  parser );\r\n\r\n    FT_Error\r\n    (*parse)( AFM_Parser  parser );\r\n\r\n  } AFM_Parser_FuncsRec;\r\n\r\n\r\n  typedef struct AFM_StreamRec_*  AFM_Stream;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    AFM_ParserRec                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    An AFM_Parser is a parser for the AFM files.                       */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    memory    :: The object used for memory operations (alloc and      */\r\n  /*                 realloc).                                             */\r\n  /*                                                                       */\r\n  /*    stream    :: This is an opaque object.                             */\r\n  /*                                                                       */\r\n  /*    FontInfo  :: The result will be stored here.                       */\r\n  /*                                                                       */\r\n  /*    get_index :: A user provided function to get a glyph index by its  */\r\n  /*                 name.                                                 */\r\n  /*                                                                       */\r\n  typedef struct  AFM_ParserRec_\r\n  {\r\n    FT_Memory     memory;\r\n    AFM_Stream    stream;\r\n\r\n    AFM_FontInfo  FontInfo;\r\n\r\n    FT_Int\r\n    (*get_index)( const char*  name,\r\n                  FT_Offset    len,\r\n                  void*        user_data );\r\n\r\n    void*         user_data;\r\n\r\n  } AFM_ParserRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*****                                                               *****/\r\n  /*****                     TYPE1 CHARMAPS                            *****/\r\n  /*****                                                               *****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n  typedef const struct T1_CMap_ClassesRec_*  T1_CMap_Classes;\r\n\r\n  typedef struct T1_CMap_ClassesRec_\r\n  {\r\n    FT_CMap_Class  standard;\r\n    FT_CMap_Class  expert;\r\n    FT_CMap_Class  custom;\r\n    FT_CMap_Class  unicode;\r\n\r\n  } T1_CMap_ClassesRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*****                                                               *****/\r\n  /*****                        PSAux Module Interface                 *****/\r\n  /*****                                                               *****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n  typedef struct  PSAux_ServiceRec_\r\n  {\r\n    /* don't use `PS_Table_Funcs' and friends to avoid compiler warnings */\r\n    const PS_Table_FuncsRec*    ps_table_funcs;\r\n    const PS_Parser_FuncsRec*   ps_parser_funcs;\r\n    const T1_Builder_FuncsRec*  t1_builder_funcs;\r\n    const T1_Decoder_FuncsRec*  t1_decoder_funcs;\r\n\r\n    void\r\n    (*t1_decrypt)( FT_Byte*   buffer,\r\n                   FT_Offset  length,\r\n                   FT_UShort  seed );\r\n\r\n    T1_CMap_Classes  t1_cmap_classes;\r\n\r\n    /* fields after this comment line were added after version 2.1.10 */\r\n    const AFM_Parser_FuncsRec*  afm_parser_funcs;\r\n\r\n  } PSAux_ServiceRec, *PSAux_Service;\r\n\r\n  /* backwards-compatible type definition */\r\n  typedef PSAux_ServiceRec   PSAux_Interface;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*****                                                               *****/\r\n  /*****                 Some convenience functions                    *****/\r\n  /*****                                                               *****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n#define IS_PS_NEWLINE( ch ) \\\r\n  ( (ch) == '\\r' ||         \\\r\n    (ch) == '\\n' )\r\n\r\n#define IS_PS_SPACE( ch )  \\\r\n  ( (ch) == ' '         || \\\r\n    IS_PS_NEWLINE( ch ) || \\\r\n    (ch) == '\\t'        || \\\r\n    (ch) == '\\f'        || \\\r\n    (ch) == '\\0' )\r\n\r\n#define IS_PS_SPECIAL( ch )       \\\r\n  ( (ch) == '/'                || \\\r\n    (ch) == '(' || (ch) == ')' || \\\r\n    (ch) == '<' || (ch) == '>' || \\\r\n    (ch) == '[' || (ch) == ']' || \\\r\n    (ch) == '{' || (ch) == '}' || \\\r\n    (ch) == '%'                )\r\n\r\n#define IS_PS_DELIM( ch )  \\\r\n  ( IS_PS_SPACE( ch )   || \\\r\n    IS_PS_SPECIAL( ch ) )\r\n\r\n#define IS_PS_DIGIT( ch )        \\\r\n  ( (ch) >= '0' && (ch) <= '9' )\r\n\r\n#define IS_PS_XDIGIT( ch )            \\\r\n  ( IS_PS_DIGIT( ch )              || \\\r\n    ( (ch) >= 'A' && (ch) <= 'F' ) || \\\r\n    ( (ch) >= 'a' && (ch) <= 'f' ) )\r\n\r\n#define IS_PS_BASE85( ch )       \\\r\n  ( (ch) >= '!' && (ch) <= 'u' )\r\n\r\n#define IS_PS_TOKEN( cur, limit, token )                                \\\r\n  ( (char)(cur)[0] == (token)[0]                                     && \\\r\n    ( (cur) + sizeof ( (token) ) == (limit) ||                          \\\r\n      ( (cur) + sizeof( (token) ) < (limit)          &&                 \\\r\n        IS_PS_DELIM( (cur)[sizeof ( (token) ) - 1] ) ) )             && \\\r\n    ft_strncmp( (char*)(cur), (token), sizeof ( (token) ) - 1 ) == 0 )\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __PSAUX_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/pshints.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  pshints.h                                                              */\r\n/*                                                                         */\r\n/*    Interface to Postscript-specific (Type 1 and Type 2) hints           */\r\n/*    recorders (specification only).  These are used to support native    */\r\n/*    T1/T2 hints in the `type1', `cid', and `cff' font drivers.           */\r\n/*                                                                         */\r\n/*  Copyright 2001, 2002, 2003, 2005, 2006, 2007, 2009 by                  */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __PSHINTS_H__\r\n#define __PSHINTS_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n#include FT_TYPE1_TABLES_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*****                                                               *****/\r\n  /*****               INTERNAL REPRESENTATION OF GLOBALS              *****/\r\n  /*****                                                               *****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n  typedef struct PSH_GlobalsRec_*  PSH_Globals;\r\n\r\n  typedef FT_Error\r\n  (*PSH_Globals_NewFunc)( FT_Memory     memory,\r\n                          T1_Private*   private_dict,\r\n                          PSH_Globals*  aglobals );\r\n\r\n  typedef FT_Error\r\n  (*PSH_Globals_SetScaleFunc)( PSH_Globals  globals,\r\n                               FT_Fixed     x_scale,\r\n                               FT_Fixed     y_scale,\r\n                               FT_Fixed     x_delta,\r\n                               FT_Fixed     y_delta );\r\n\r\n  typedef void\r\n  (*PSH_Globals_DestroyFunc)( PSH_Globals  globals );\r\n\r\n\r\n  typedef struct  PSH_Globals_FuncsRec_\r\n  {\r\n    PSH_Globals_NewFunc       create;\r\n    PSH_Globals_SetScaleFunc  set_scale;\r\n    PSH_Globals_DestroyFunc   destroy;\r\n\r\n  } PSH_Globals_FuncsRec, *PSH_Globals_Funcs;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*****                                                               *****/\r\n  /*****                  PUBLIC TYPE 1 HINTS RECORDER                 *****/\r\n  /*****                                                               *****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @type:\r\n   *   T1_Hints\r\n   *\r\n   * @description:\r\n   *   This is a handle to an opaque structure used to record glyph hints\r\n   *   from a Type 1 character glyph character string.\r\n   *\r\n   *   The methods used to operate on this object are defined by the\r\n   *   @T1_Hints_FuncsRec structure.  Recording glyph hints is normally\r\n   *   achieved through the following scheme:\r\n   *\r\n   *   - Open a new hint recording session by calling the `open' method.\r\n   *     This rewinds the recorder and prepare it for new input.\r\n   *\r\n   *   - For each hint found in the glyph charstring, call the corresponding\r\n   *     method (`stem', `stem3', or `reset').  Note that these functions do\r\n   *     not return an error code.\r\n   *\r\n   *   - Close the recording session by calling the `close' method.  It\r\n   *     returns an error code if the hints were invalid or something\r\n   *     strange happened (e.g., memory shortage).\r\n   *\r\n   *   The hints accumulated in the object can later be used by the\r\n   *   PostScript hinter.\r\n   *\r\n   */\r\n  typedef struct T1_HintsRec_*  T1_Hints;\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @type:\r\n   *   T1_Hints_Funcs\r\n   *\r\n   * @description:\r\n   *   A pointer to the @T1_Hints_FuncsRec structure that defines the API of\r\n   *   a given @T1_Hints object.\r\n   *\r\n   */\r\n  typedef const struct T1_Hints_FuncsRec_*  T1_Hints_Funcs;\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @functype:\r\n   *   T1_Hints_OpenFunc\r\n   *\r\n   * @description:\r\n   *   A method of the @T1_Hints class used to prepare it for a new Type 1\r\n   *   hints recording session.\r\n   *\r\n   * @input:\r\n   *   hints ::\r\n   *     A handle to the Type 1 hints recorder.\r\n   *\r\n   * @note:\r\n   *   You should always call the @T1_Hints_CloseFunc method in order to\r\n   *   close an opened recording session.\r\n   *\r\n   */\r\n  typedef void\r\n  (*T1_Hints_OpenFunc)( T1_Hints  hints );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @functype:\r\n   *   T1_Hints_SetStemFunc\r\n   *\r\n   * @description:\r\n   *   A method of the @T1_Hints class used to record a new horizontal or\r\n   *   vertical stem.  This corresponds to the Type 1 `hstem' and `vstem'\r\n   *   operators.\r\n   *\r\n   * @input:\r\n   *   hints ::\r\n   *     A handle to the Type 1 hints recorder.\r\n   *\r\n   *   dimension ::\r\n   *     0 for horizontal stems (hstem), 1 for vertical ones (vstem).\r\n   *\r\n   *   coords ::\r\n   *     Array of 2 coordinates in 16.16 format, used as (position,length)\r\n   *     stem descriptor.\r\n   *\r\n   * @note:\r\n   *   Use vertical coordinates (y) for horizontal stems (dim=0).  Use\r\n   *   horizontal coordinates (x) for vertical stems (dim=1).\r\n   *\r\n   *   `coords[0]' is the absolute stem position (lowest coordinate);\r\n   *   `coords[1]' is the length.\r\n   *\r\n   *   The length can be negative, in which case it must be either -20 or\r\n   *   -21.  It is interpreted as a `ghost' stem, according to the Type 1\r\n   *   specification.\r\n   *\r\n   *   If the length is -21 (corresponding to a bottom ghost stem), then\r\n   *   the real stem position is `coords[0]+coords[1]'.\r\n   *\r\n   */\r\n  typedef void\r\n  (*T1_Hints_SetStemFunc)( T1_Hints   hints,\r\n                           FT_UInt    dimension,\r\n                           FT_Fixed*  coords );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @functype:\r\n   *   T1_Hints_SetStem3Func\r\n   *\r\n   * @description:\r\n   *   A method of the @T1_Hints class used to record three\r\n   *   counter-controlled horizontal or vertical stems at once.\r\n   *\r\n   * @input:\r\n   *   hints ::\r\n   *     A handle to the Type 1 hints recorder.\r\n   *\r\n   *   dimension ::\r\n   *     0 for horizontal stems, 1 for vertical ones.\r\n   *\r\n   *   coords ::\r\n   *     An array of 6 values in 16.16 format, holding 3 (position,length)\r\n   *     pairs for the counter-controlled stems.\r\n   *\r\n   * @note:\r\n   *   Use vertical coordinates (y) for horizontal stems (dim=0).  Use\r\n   *   horizontal coordinates (x) for vertical stems (dim=1).\r\n   *\r\n   *   The lengths cannot be negative (ghost stems are never\r\n   *   counter-controlled).\r\n   *\r\n   */\r\n  typedef void\r\n  (*T1_Hints_SetStem3Func)( T1_Hints   hints,\r\n                            FT_UInt    dimension,\r\n                            FT_Fixed*  coords );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @functype:\r\n   *   T1_Hints_ResetFunc\r\n   *\r\n   * @description:\r\n   *   A method of the @T1_Hints class used to reset the stems hints in a\r\n   *   recording session.\r\n   *\r\n   * @input:\r\n   *   hints ::\r\n   *     A handle to the Type 1 hints recorder.\r\n   *\r\n   *   end_point ::\r\n   *     The index of the last point in the input glyph in which the\r\n   *     previously defined hints apply.\r\n   *\r\n   */\r\n  typedef void\r\n  (*T1_Hints_ResetFunc)( T1_Hints  hints,\r\n                         FT_UInt   end_point );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @functype:\r\n   *   T1_Hints_CloseFunc\r\n   *\r\n   * @description:\r\n   *   A method of the @T1_Hints class used to close a hint recording\r\n   *   session.\r\n   *\r\n   * @input:\r\n   *   hints ::\r\n   *     A handle to the Type 1 hints recorder.\r\n   *\r\n   *   end_point ::\r\n   *     The index of the last point in the input glyph.\r\n   *\r\n   * @return:\r\n   *   FreeType error code.  0 means success.\r\n   *\r\n   * @note:\r\n   *   The error code is set to indicate that an error occurred during the\r\n   *   recording session.\r\n   *\r\n   */\r\n  typedef FT_Error\r\n  (*T1_Hints_CloseFunc)( T1_Hints  hints,\r\n                         FT_UInt   end_point );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @functype:\r\n   *   T1_Hints_ApplyFunc\r\n   *\r\n   * @description:\r\n   *   A method of the @T1_Hints class used to apply hints to the\r\n   *   corresponding glyph outline.  Must be called once all hints have been\r\n   *   recorded.\r\n   *\r\n   * @input:\r\n   *   hints ::\r\n   *     A handle to the Type 1 hints recorder.\r\n   *\r\n   *   outline ::\r\n   *     A pointer to the target outline descriptor.\r\n   *\r\n   *   globals ::\r\n   *     The hinter globals for this font.\r\n   *\r\n   *   hint_mode ::\r\n   *     Hinting information.\r\n   *\r\n   * @return:\r\n   *   FreeType error code.  0 means success.\r\n   *\r\n   * @note:\r\n   *   On input, all points within the outline are in font coordinates. On\r\n   *   output, they are in 1/64th of pixels.\r\n   *\r\n   *   The scaling transformation is taken from the `globals' object which\r\n   *   must correspond to the same font as the glyph.\r\n   *\r\n   */\r\n  typedef FT_Error\r\n  (*T1_Hints_ApplyFunc)( T1_Hints        hints,\r\n                         FT_Outline*     outline,\r\n                         PSH_Globals     globals,\r\n                         FT_Render_Mode  hint_mode );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @struct:\r\n   *   T1_Hints_FuncsRec\r\n   *\r\n   * @description:\r\n   *   The structure used to provide the API to @T1_Hints objects.\r\n   *\r\n   * @fields:\r\n   *   hints ::\r\n   *     A handle to the T1 Hints recorder.\r\n   *\r\n   *   open ::\r\n   *     The function to open a recording session.\r\n   *\r\n   *   close ::\r\n   *     The function to close a recording session.\r\n   *\r\n   *   stem ::\r\n   *     The function to set a simple stem.\r\n   *\r\n   *   stem3 ::\r\n   *     The function to set counter-controlled stems.\r\n   *\r\n   *   reset ::\r\n   *     The function to reset stem hints.\r\n   *\r\n   *   apply ::\r\n   *     The function to apply the hints to the corresponding glyph outline.\r\n   *\r\n   */\r\n  typedef struct  T1_Hints_FuncsRec_\r\n  {\r\n    T1_Hints               hints;\r\n    T1_Hints_OpenFunc      open;\r\n    T1_Hints_CloseFunc     close;\r\n    T1_Hints_SetStemFunc   stem;\r\n    T1_Hints_SetStem3Func  stem3;\r\n    T1_Hints_ResetFunc     reset;\r\n    T1_Hints_ApplyFunc     apply;\r\n\r\n  } T1_Hints_FuncsRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*****                                                               *****/\r\n  /*****                  PUBLIC TYPE 2 HINTS RECORDER                 *****/\r\n  /*****                                                               *****/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @type:\r\n   *   T2_Hints\r\n   *\r\n   * @description:\r\n   *   This is a handle to an opaque structure used to record glyph hints\r\n   *   from a Type 2 character glyph character string.\r\n   *\r\n   *   The methods used to operate on this object are defined by the\r\n   *   @T2_Hints_FuncsRec structure.  Recording glyph hints is normally\r\n   *   achieved through the following scheme:\r\n   *\r\n   *   - Open a new hint recording session by calling the `open' method.\r\n   *     This rewinds the recorder and prepare it for new input.\r\n   *\r\n   *   - For each hint found in the glyph charstring, call the corresponding\r\n   *     method (`stems', `hintmask', `counters').  Note that these\r\n   *     functions do not return an error code.\r\n   *\r\n   *   - Close the recording session by calling the `close' method.  It\r\n   *     returns an error code if the hints were invalid or something\r\n   *     strange happened (e.g., memory shortage).\r\n   *\r\n   *   The hints accumulated in the object can later be used by the\r\n   *   Postscript hinter.\r\n   *\r\n   */\r\n  typedef struct T2_HintsRec_*  T2_Hints;\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @type:\r\n   *   T2_Hints_Funcs\r\n   *\r\n   * @description:\r\n   *   A pointer to the @T2_Hints_FuncsRec structure that defines the API of\r\n   *   a given @T2_Hints object.\r\n   *\r\n   */\r\n  typedef const struct T2_Hints_FuncsRec_*  T2_Hints_Funcs;\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @functype:\r\n   *   T2_Hints_OpenFunc\r\n   *\r\n   * @description:\r\n   *   A method of the @T2_Hints class used to prepare it for a new Type 2\r\n   *   hints recording session.\r\n   *\r\n   * @input:\r\n   *   hints ::\r\n   *     A handle to the Type 2 hints recorder.\r\n   *\r\n   * @note:\r\n   *   You should always call the @T2_Hints_CloseFunc method in order to\r\n   *   close an opened recording session.\r\n   *\r\n   */\r\n  typedef void\r\n  (*T2_Hints_OpenFunc)( T2_Hints  hints );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @functype:\r\n   *   T2_Hints_StemsFunc\r\n   *\r\n   * @description:\r\n   *   A method of the @T2_Hints class used to set the table of stems in\r\n   *   either the vertical or horizontal dimension.  Equivalent to the\r\n   *   `hstem', `vstem', `hstemhm', and `vstemhm' Type 2 operators.\r\n   *\r\n   * @input:\r\n   *   hints ::\r\n   *     A handle to the Type 2 hints recorder.\r\n   *\r\n   *   dimension ::\r\n   *     0 for horizontal stems (hstem), 1 for vertical ones (vstem).\r\n   *\r\n   *   count ::\r\n   *     The number of stems.\r\n   *\r\n   *   coords ::\r\n   *     An array of `count' (position,length) pairs in 16.16 format.\r\n   *\r\n   * @note:\r\n   *   Use vertical coordinates (y) for horizontal stems (dim=0).  Use\r\n   *   horizontal coordinates (x) for vertical stems (dim=1).\r\n   *\r\n   *   There are `2*count' elements in the `coords' array.  Each even\r\n   *   element is an absolute position in font units, each odd element is a\r\n   *   length in font units.\r\n   *\r\n   *   A length can be negative, in which case it must be either -20 or\r\n   *   -21.  It is interpreted as a `ghost' stem, according to the Type 1\r\n   *   specification.\r\n   *\r\n   */\r\n  typedef void\r\n  (*T2_Hints_StemsFunc)( T2_Hints   hints,\r\n                         FT_UInt    dimension,\r\n                         FT_UInt    count,\r\n                         FT_Fixed*  coordinates );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @functype:\r\n   *   T2_Hints_MaskFunc\r\n   *\r\n   * @description:\r\n   *   A method of the @T2_Hints class used to set a given hintmask (this\r\n   *   corresponds to the `hintmask' Type 2 operator).\r\n   *\r\n   * @input:\r\n   *   hints ::\r\n   *     A handle to the Type 2 hints recorder.\r\n   *\r\n   *   end_point ::\r\n   *     The glyph index of the last point to which the previously defined\r\n   *     or activated hints apply.\r\n   *\r\n   *   bit_count ::\r\n   *     The number of bits in the hint mask.\r\n   *\r\n   *   bytes ::\r\n   *     An array of bytes modelling the hint mask.\r\n   *\r\n   * @note:\r\n   *   If the hintmask starts the charstring (before any glyph point\r\n   *   definition), the value of `end_point' should be 0.\r\n   *\r\n   *   `bit_count' is the number of meaningful bits in the `bytes' array; it\r\n   *   must be equal to the total number of hints defined so far (i.e.,\r\n   *   horizontal+verticals).\r\n   *\r\n   *   The `bytes' array can come directly from the Type 2 charstring and\r\n   *   respects the same format.\r\n   *\r\n   */\r\n  typedef void\r\n  (*T2_Hints_MaskFunc)( T2_Hints        hints,\r\n                        FT_UInt         end_point,\r\n                        FT_UInt         bit_count,\r\n                        const FT_Byte*  bytes );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @functype:\r\n   *   T2_Hints_CounterFunc\r\n   *\r\n   * @description:\r\n   *   A method of the @T2_Hints class used to set a given counter mask\r\n   *   (this corresponds to the `hintmask' Type 2 operator).\r\n   *\r\n   * @input:\r\n   *   hints ::\r\n   *     A handle to the Type 2 hints recorder.\r\n   *\r\n   *   end_point ::\r\n   *     A glyph index of the last point to which the previously defined or\r\n   *     active hints apply.\r\n   *\r\n   *   bit_count ::\r\n   *     The number of bits in the hint mask.\r\n   *\r\n   *   bytes ::\r\n   *     An array of bytes modelling the hint mask.\r\n   *\r\n   * @note:\r\n   *   If the hintmask starts the charstring (before any glyph point\r\n   *   definition), the value of `end_point' should be 0.\r\n   *\r\n   *   `bit_count' is the number of meaningful bits in the `bytes' array; it\r\n   *   must be equal to the total number of hints defined so far (i.e.,\r\n   *   horizontal+verticals).\r\n   *\r\n   *    The `bytes' array can come directly from the Type 2 charstring and\r\n   *    respects the same format.\r\n   *\r\n   */\r\n  typedef void\r\n  (*T2_Hints_CounterFunc)( T2_Hints        hints,\r\n                           FT_UInt         bit_count,\r\n                           const FT_Byte*  bytes );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @functype:\r\n   *   T2_Hints_CloseFunc\r\n   *\r\n   * @description:\r\n   *   A method of the @T2_Hints class used to close a hint recording\r\n   *   session.\r\n   *\r\n   * @input:\r\n   *   hints ::\r\n   *     A handle to the Type 2 hints recorder.\r\n   *\r\n   *   end_point ::\r\n   *     The index of the last point in the input glyph.\r\n   *\r\n   * @return:\r\n   *   FreeType error code.  0 means success.\r\n   *\r\n   * @note:\r\n   *   The error code is set to indicate that an error occurred during the\r\n   *   recording session.\r\n   *\r\n   */\r\n  typedef FT_Error\r\n  (*T2_Hints_CloseFunc)( T2_Hints  hints,\r\n                         FT_UInt   end_point );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @functype:\r\n   *   T2_Hints_ApplyFunc\r\n   *\r\n   * @description:\r\n   *   A method of the @T2_Hints class used to apply hints to the\r\n   *   corresponding glyph outline.  Must be called after the `close'\r\n   *   method.\r\n   *\r\n   * @input:\r\n   *   hints ::\r\n   *     A handle to the Type 2 hints recorder.\r\n   *\r\n   *   outline ::\r\n   *     A pointer to the target outline descriptor.\r\n   *\r\n   *   globals ::\r\n   *     The hinter globals for this font.\r\n   *\r\n   *   hint_mode ::\r\n   *     Hinting information.\r\n   *\r\n   * @return:\r\n   *   FreeType error code.  0 means success.\r\n   *\r\n   * @note:\r\n   *   On input, all points within the outline are in font coordinates. On\r\n   *   output, they are in 1/64th of pixels.\r\n   *\r\n   *   The scaling transformation is taken from the `globals' object which\r\n   *   must correspond to the same font than the glyph.\r\n   *\r\n   */\r\n  typedef FT_Error\r\n  (*T2_Hints_ApplyFunc)( T2_Hints        hints,\r\n                         FT_Outline*     outline,\r\n                         PSH_Globals     globals,\r\n                         FT_Render_Mode  hint_mode );\r\n\r\n\r\n  /*************************************************************************\r\n   *\r\n   * @struct:\r\n   *   T2_Hints_FuncsRec\r\n   *\r\n   * @description:\r\n   *   The structure used to provide the API to @T2_Hints objects.\r\n   *\r\n   * @fields:\r\n   *   hints ::\r\n   *     A handle to the T2 hints recorder object.\r\n   *\r\n   *   open ::\r\n   *     The function to open a recording session.\r\n   *\r\n   *   close ::\r\n   *     The function to close a recording session.\r\n   *\r\n   *   stems ::\r\n   *     The function to set the dimension's stems table.\r\n   *\r\n   *   hintmask ::\r\n   *     The function to set hint masks.\r\n   *\r\n   *   counter ::\r\n   *     The function to set counter masks.\r\n   *\r\n   *   apply ::\r\n   *     The function to apply the hints on the corresponding glyph outline.\r\n   *\r\n   */\r\n  typedef struct  T2_Hints_FuncsRec_\r\n  {\r\n    T2_Hints              hints;\r\n    T2_Hints_OpenFunc     open;\r\n    T2_Hints_CloseFunc    close;\r\n    T2_Hints_StemsFunc    stems;\r\n    T2_Hints_MaskFunc     hintmask;\r\n    T2_Hints_CounterFunc  counter;\r\n    T2_Hints_ApplyFunc    apply;\r\n\r\n  } T2_Hints_FuncsRec;\r\n\r\n\r\n  /* */\r\n\r\n\r\n  typedef struct  PSHinter_Interface_\r\n  {\r\n    PSH_Globals_Funcs  (*get_globals_funcs)( FT_Module  module );\r\n    T1_Hints_Funcs     (*get_t1_funcs)     ( FT_Module  module );\r\n    T2_Hints_Funcs     (*get_t2_funcs)     ( FT_Module  module );\r\n\r\n  } PSHinter_Interface;\r\n\r\n  typedef PSHinter_Interface*  PSHinter_Service;\r\n\r\n#ifndef FT_CONFIG_OPTION_PIC\r\n\r\n#define FT_DEFINE_PSHINTER_INTERFACE(class_, get_globals_funcs_,             \\\r\n                                     get_t1_funcs_, get_t2_funcs_)           \\\r\n  static const PSHinter_Interface class_ =                                   \\\r\n  {                                                                          \\\r\n    get_globals_funcs_, get_t1_funcs_, get_t2_funcs_                         \\\r\n  };\r\n\r\n#else /* FT_CONFIG_OPTION_PIC */ \r\n\r\n#define FT_DEFINE_PSHINTER_INTERFACE(class_, get_globals_funcs_,             \\\r\n                                     get_t1_funcs_, get_t2_funcs_)           \\\r\n  void                                                                       \\\r\n  FT_Init_Class_##class_( FT_Library library,                                \\\r\n                          PSHinter_Interface*  clazz)                        \\\r\n  {                                                                          \\\r\n    FT_UNUSED(library);                                                      \\\r\n    clazz->get_globals_funcs = get_globals_funcs_;                           \\\r\n    clazz->get_t1_funcs = get_t1_funcs_;                                     \\\r\n    clazz->get_t2_funcs = get_t2_funcs_;                                     \\\r\n  } \r\n\r\n#endif /* FT_CONFIG_OPTION_PIC */ \r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __PSHINTS_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/services/svbdf.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  svbdf.h                                                                */\r\n/*                                                                         */\r\n/*    The FreeType BDF services (specification).                           */\r\n/*                                                                         */\r\n/*  Copyright 2003 by                                                      */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __SVBDF_H__\r\n#define __SVBDF_H__\r\n\r\n#include FT_BDF_H\r\n#include FT_INTERNAL_SERVICE_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n#define FT_SERVICE_ID_BDF  \"bdf\"\r\n\r\n  typedef FT_Error\r\n  (*FT_BDF_GetCharsetIdFunc)( FT_Face       face,\r\n                              const char*  *acharset_encoding,\r\n                              const char*  *acharset_registry );\r\n\r\n  typedef FT_Error\r\n  (*FT_BDF_GetPropertyFunc)( FT_Face           face,\r\n                             const char*       prop_name,\r\n                             BDF_PropertyRec  *aproperty );\r\n\r\n\r\n  FT_DEFINE_SERVICE( BDF )\r\n  {\r\n    FT_BDF_GetCharsetIdFunc  get_charset_id;\r\n    FT_BDF_GetPropertyFunc   get_property;\r\n  };\r\n\r\n#ifndef FT_CONFIG_OPTION_PIC\r\n\r\n#define FT_DEFINE_SERVICE_BDFRec(class_, get_charset_id_, get_property_) \\\r\n  static const FT_Service_BDFRec class_ =                                \\\r\n  {                                                                      \\\r\n    get_charset_id_, get_property_                                       \\\r\n  };\r\n\r\n#else /* FT_CONFIG_OPTION_PIC */ \r\n\r\n#define FT_DEFINE_SERVICE_BDFRec(class_, get_charset_id_, get_property_) \\\r\n  void                                                                   \\\r\n  FT_Init_Class_##class_( FT_Service_BDFRec*  clazz )                    \\\r\n  {                                                                      \\\r\n    clazz->get_charset_id = get_charset_id_;                             \\\r\n    clazz->get_property = get_property_;                                 \\\r\n  } \r\n\r\n#endif /* FT_CONFIG_OPTION_PIC */ \r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n\r\n#endif /* __SVBDF_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/services/svcid.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  svcid.h                                                                */\r\n/*                                                                         */\r\n/*    The FreeType CID font services (specification).                      */\r\n/*                                                                         */\r\n/*  Copyright 2007, 2009 by Derek Clegg, Michael Toftdal.                  */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __SVCID_H__\r\n#define __SVCID_H__\r\n\r\n#include FT_INTERNAL_SERVICE_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n#define FT_SERVICE_ID_CID  \"CID\"\r\n\r\n  typedef FT_Error\r\n  (*FT_CID_GetRegistryOrderingSupplementFunc)( FT_Face       face,\r\n                                               const char*  *registry,\r\n                                               const char*  *ordering,\r\n                                               FT_Int       *supplement );\r\n  typedef FT_Error\r\n  (*FT_CID_GetIsInternallyCIDKeyedFunc)( FT_Face   face,\r\n                                         FT_Bool  *is_cid );\r\n  typedef FT_Error\r\n  (*FT_CID_GetCIDFromGlyphIndexFunc)( FT_Face   face,\r\n                                      FT_UInt   glyph_index,\r\n                                      FT_UInt  *cid );\r\n\r\n  FT_DEFINE_SERVICE( CID )\r\n  {\r\n    FT_CID_GetRegistryOrderingSupplementFunc  get_ros;\r\n    FT_CID_GetIsInternallyCIDKeyedFunc        get_is_cid;\r\n    FT_CID_GetCIDFromGlyphIndexFunc           get_cid_from_glyph_index;\r\n  };\r\n\r\n#ifndef FT_CONFIG_OPTION_PIC\r\n\r\n#define FT_DEFINE_SERVICE_CIDREC(class_, get_ros_,                           \\\r\n        get_is_cid_, get_cid_from_glyph_index_ )                             \\\r\n  static const FT_Service_CIDRec class_ =                                    \\\r\n  {                                                                          \\\r\n    get_ros_, get_is_cid_, get_cid_from_glyph_index_                         \\\r\n  };\r\n\r\n#else /* FT_CONFIG_OPTION_PIC */ \r\n\r\n#define FT_DEFINE_SERVICE_CIDREC(class_, get_ros_,                           \\\r\n        get_is_cid_, get_cid_from_glyph_index_ )                             \\\r\n  void                                                                       \\\r\n  FT_Init_Class_##class_( FT_Library library,                                \\\r\n                          FT_Service_CIDRec* clazz)                          \\\r\n  {                                                                          \\\r\n    FT_UNUSED(library);                                                      \\\r\n    clazz->get_ros = get_ros_;                                               \\\r\n    clazz->get_is_cid = get_is_cid_;                                         \\\r\n    clazz->get_cid_from_glyph_index = get_cid_from_glyph_index_;             \\\r\n  } \r\n\r\n#endif /* FT_CONFIG_OPTION_PIC */ \r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n\r\n#endif /* __SVCID_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/services/svgldict.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  svgldict.h                                                             */\r\n/*                                                                         */\r\n/*    The FreeType glyph dictionary services (specification).              */\r\n/*                                                                         */\r\n/*  Copyright 2003 by                                                      */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __SVGLDICT_H__\r\n#define __SVGLDICT_H__\r\n\r\n#include FT_INTERNAL_SERVICE_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*\r\n   *  A service used to retrieve glyph names, as well as to find the\r\n   *  index of a given glyph name in a font.\r\n   *\r\n   */\r\n\r\n#define FT_SERVICE_ID_GLYPH_DICT  \"glyph-dict\"\r\n\r\n\r\n  typedef FT_Error\r\n  (*FT_GlyphDict_GetNameFunc)( FT_Face     face,\r\n                               FT_UInt     glyph_index,\r\n                               FT_Pointer  buffer,\r\n                               FT_UInt     buffer_max );\r\n\r\n  typedef FT_UInt\r\n  (*FT_GlyphDict_NameIndexFunc)( FT_Face     face,\r\n                                 FT_String*  glyph_name );\r\n\r\n\r\n  FT_DEFINE_SERVICE( GlyphDict )\r\n  {\r\n    FT_GlyphDict_GetNameFunc    get_name;\r\n    FT_GlyphDict_NameIndexFunc  name_index;  /* optional */\r\n  };\r\n\r\n#ifndef FT_CONFIG_OPTION_PIC\r\n\r\n#define FT_DEFINE_SERVICE_GLYPHDICTREC(class_, get_name_, name_index_) \\\r\n  static const FT_Service_GlyphDictRec class_ =                        \\\r\n  {                                                                    \\\r\n    get_name_, name_index_                                             \\\r\n  };\r\n\r\n#else /* FT_CONFIG_OPTION_PIC */ \r\n\r\n#define FT_DEFINE_SERVICE_GLYPHDICTREC(class_, get_name_, name_index_) \\\r\n  void                                                                 \\\r\n  FT_Init_Class_##class_( FT_Library library,                          \\\r\n                          FT_Service_GlyphDictRec* clazz)              \\\r\n  {                                                                    \\\r\n    FT_UNUSED(library);                                                \\\r\n    clazz->get_name = get_name_;                                       \\\r\n    clazz->name_index = name_index_;                                   \\\r\n  } \r\n\r\n#endif /* FT_CONFIG_OPTION_PIC */ \r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n\r\n#endif /* __SVGLDICT_H__ */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/services/svgxval.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  svgxval.h                                                              */\r\n/*                                                                         */\r\n/*    FreeType API for validating TrueTypeGX/AAT tables (specification).   */\r\n/*                                                                         */\r\n/*  Copyright 2004, 2005 by                                                */\r\n/*  Masatake YAMATO, Red Hat K.K.,                                         */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n/***************************************************************************/\r\n/*                                                                         */\r\n/* gxvalid is derived from both gxlayout module and otvalid module.        */\r\n/* Development of gxlayout is supported by the Information-technology      */\r\n/* Promotion Agency(IPA), Japan.                                           */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __SVGXVAL_H__\r\n#define __SVGXVAL_H__\r\n\r\n#include FT_GX_VALIDATE_H\r\n#include FT_INTERNAL_VALIDATE_H\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n#define FT_SERVICE_ID_GX_VALIDATE           \"truetypegx-validate\"\r\n#define FT_SERVICE_ID_CLASSICKERN_VALIDATE  \"classickern-validate\"\r\n\r\n  typedef FT_Error\r\n  (*gxv_validate_func)( FT_Face   face,\r\n                        FT_UInt   gx_flags,\r\n                        FT_Bytes  tables[FT_VALIDATE_GX_LENGTH],\r\n                        FT_UInt   table_length );\r\n\r\n\r\n  typedef FT_Error\r\n  (*ckern_validate_func)( FT_Face   face,\r\n                          FT_UInt   ckern_flags,\r\n                          FT_Bytes  *ckern_table );\r\n\r\n\r\n  FT_DEFINE_SERVICE( GXvalidate )\r\n  {\r\n    gxv_validate_func  validate;\r\n  };\r\n\r\n  FT_DEFINE_SERVICE( CKERNvalidate )\r\n  {\r\n    ckern_validate_func  validate;\r\n  };\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n\r\n#endif /* __SVGXVAL_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/services/svkern.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  svkern.h                                                               */\r\n/*                                                                         */\r\n/*    The FreeType Kerning service (specification).                        */\r\n/*                                                                         */\r\n/*  Copyright 2006 by                                                      */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __SVKERN_H__\r\n#define __SVKERN_H__\r\n\r\n#include FT_INTERNAL_SERVICE_H\r\n#include FT_TRUETYPE_TABLES_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n#define FT_SERVICE_ID_KERNING  \"kerning\"\r\n\r\n\r\n  typedef FT_Error\r\n  (*FT_Kerning_TrackGetFunc)( FT_Face    face,\r\n                              FT_Fixed   point_size,\r\n                              FT_Int     degree,\r\n                              FT_Fixed*  akerning );\r\n\r\n  FT_DEFINE_SERVICE( Kerning )\r\n  {\r\n    FT_Kerning_TrackGetFunc  get_track;\r\n  };\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n\r\n#endif /* __SVKERN_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/services/svmm.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  svmm.h                                                                 */\r\n/*                                                                         */\r\n/*    The FreeType Multiple Masters and GX var services (specification).   */\r\n/*                                                                         */\r\n/*  Copyright 2003, 2004 by                                                */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __SVMM_H__\r\n#define __SVMM_H__\r\n\r\n#include FT_INTERNAL_SERVICE_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*\r\n   *  A service used to manage multiple-masters data in a given face.\r\n   *\r\n   *  See the related APIs in `ftmm.h' (FT_MULTIPLE_MASTERS_H).\r\n   *\r\n   */\r\n\r\n#define FT_SERVICE_ID_MULTI_MASTERS  \"multi-masters\"\r\n\r\n\r\n  typedef FT_Error\r\n  (*FT_Get_MM_Func)( FT_Face           face,\r\n                     FT_Multi_Master*  master );\r\n\r\n  typedef FT_Error\r\n  (*FT_Get_MM_Var_Func)( FT_Face      face,\r\n                         FT_MM_Var*  *master );\r\n\r\n  typedef FT_Error\r\n  (*FT_Set_MM_Design_Func)( FT_Face   face,\r\n                            FT_UInt   num_coords,\r\n                            FT_Long*  coords );\r\n\r\n  typedef FT_Error\r\n  (*FT_Set_Var_Design_Func)( FT_Face    face,\r\n                             FT_UInt    num_coords,\r\n                             FT_Fixed*  coords );\r\n\r\n  typedef FT_Error\r\n  (*FT_Set_MM_Blend_Func)( FT_Face   face,\r\n                           FT_UInt   num_coords,\r\n                           FT_Long*  coords );\r\n\r\n\r\n  FT_DEFINE_SERVICE( MultiMasters )\r\n  {\r\n    FT_Get_MM_Func          get_mm;\r\n    FT_Set_MM_Design_Func   set_mm_design;\r\n    FT_Set_MM_Blend_Func    set_mm_blend;\r\n    FT_Get_MM_Var_Func      get_mm_var;\r\n    FT_Set_Var_Design_Func  set_var_design;\r\n  };\r\n\r\n#ifndef FT_CONFIG_OPTION_PIC\r\n\r\n#define FT_DEFINE_SERVICE_MULTIMASTERSREC(class_, get_mm_, set_mm_design_,   \\\r\n        set_mm_blend_, get_mm_var_, set_var_design_)                         \\\r\n  static const FT_Service_MultiMastersRec class_ =                           \\\r\n  {                                                                          \\\r\n    get_mm_, set_mm_design_, set_mm_blend_, get_mm_var_, set_var_design_     \\\r\n  };\r\n\r\n#else /* FT_CONFIG_OPTION_PIC */ \r\n\r\n#define FT_DEFINE_SERVICE_MULTIMASTERSREC(class_, get_mm_, set_mm_design_,   \\\r\n        set_mm_blend_, get_mm_var_, set_var_design_)                         \\\r\n  void                                                                       \\\r\n  FT_Init_Class_##class_( FT_Service_MultiMastersRec*  clazz )               \\\r\n  {                                                                          \\\r\n    clazz->get_mm = get_mm_;                                                 \\\r\n    clazz->set_mm_design = set_mm_design_;                                   \\\r\n    clazz->set_mm_blend = set_mm_blend_;                                     \\\r\n    clazz->get_mm_var = get_mm_var_;                                         \\\r\n    clazz->set_var_design = set_var_design_;                                 \\\r\n  } \r\n\r\n#endif /* FT_CONFIG_OPTION_PIC */ \r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __SVMM_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/services/svotval.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  svotval.h                                                              */\r\n/*                                                                         */\r\n/*    The FreeType OpenType validation service (specification).            */\r\n/*                                                                         */\r\n/*  Copyright 2004, 2006 by                                                */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __SVOTVAL_H__\r\n#define __SVOTVAL_H__\r\n\r\n#include FT_OPENTYPE_VALIDATE_H\r\n#include FT_INTERNAL_VALIDATE_H\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n#define FT_SERVICE_ID_OPENTYPE_VALIDATE  \"opentype-validate\"\r\n\r\n\r\n  typedef FT_Error\r\n  (*otv_validate_func)( FT_Face volatile  face,\r\n                        FT_UInt           ot_flags,\r\n                        FT_Bytes         *base,\r\n                        FT_Bytes         *gdef,\r\n                        FT_Bytes         *gpos,\r\n                        FT_Bytes         *gsub,\r\n                        FT_Bytes         *jstf );\r\n\r\n\r\n  FT_DEFINE_SERVICE( OTvalidate )\r\n  {\r\n    otv_validate_func  validate;\r\n  };\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n\r\n#endif /* __SVOTVAL_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/services/svpfr.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  svpfr.h                                                                */\r\n/*                                                                         */\r\n/*    Internal PFR service functions (specification).                      */\r\n/*                                                                         */\r\n/*  Copyright 2003, 2006 by                                                */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __SVPFR_H__\r\n#define __SVPFR_H__\r\n\r\n#include FT_PFR_H\r\n#include FT_INTERNAL_SERVICE_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n#define FT_SERVICE_ID_PFR_METRICS  \"pfr-metrics\"\r\n\r\n\r\n  typedef FT_Error\r\n  (*FT_PFR_GetMetricsFunc)( FT_Face    face,\r\n                            FT_UInt   *aoutline,\r\n                            FT_UInt   *ametrics,\r\n                            FT_Fixed  *ax_scale,\r\n                            FT_Fixed  *ay_scale );\r\n\r\n  typedef FT_Error\r\n  (*FT_PFR_GetKerningFunc)( FT_Face     face,\r\n                            FT_UInt     left,\r\n                            FT_UInt     right,\r\n                            FT_Vector  *avector );\r\n\r\n  typedef FT_Error\r\n  (*FT_PFR_GetAdvanceFunc)( FT_Face   face,\r\n                            FT_UInt   gindex,\r\n                            FT_Pos   *aadvance );\r\n\r\n\r\n  FT_DEFINE_SERVICE( PfrMetrics )\r\n  {\r\n    FT_PFR_GetMetricsFunc  get_metrics;\r\n    FT_PFR_GetKerningFunc  get_kerning;\r\n    FT_PFR_GetAdvanceFunc  get_advance;\r\n\r\n  };\r\n\r\n /* */\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __SVPFR_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/services/svpostnm.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  svpostnm.h                                                             */\r\n/*                                                                         */\r\n/*    The FreeType PostScript name services (specification).               */\r\n/*                                                                         */\r\n/*  Copyright 2003, 2007 by                                                */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __SVPOSTNM_H__\r\n#define __SVPOSTNM_H__\r\n\r\n#include FT_INTERNAL_SERVICE_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n  /*\r\n   *  A trivial service used to retrieve the PostScript name of a given\r\n   *  font when available.  The `get_name' field should never be NULL.\r\n   *\r\n   *  The corresponding function can return NULL to indicate that the\r\n   *  PostScript name is not available.\r\n   *\r\n   *  The name is owned by the face and will be destroyed with it.\r\n   */\r\n\r\n#define FT_SERVICE_ID_POSTSCRIPT_FONT_NAME  \"postscript-font-name\"\r\n\r\n\r\n  typedef const char*\r\n  (*FT_PsName_GetFunc)( FT_Face  face );\r\n\r\n\r\n  FT_DEFINE_SERVICE( PsFontName )\r\n  {\r\n    FT_PsName_GetFunc  get_ps_font_name;\r\n  };\r\n\r\n#ifndef FT_CONFIG_OPTION_PIC\r\n\r\n#define FT_DEFINE_SERVICE_PSFONTNAMEREC(class_, get_ps_font_name_) \\\r\n  static const FT_Service_PsFontNameRec class_ =                   \\\r\n  {                                                                \\\r\n    get_ps_font_name_                                              \\\r\n  };\r\n\r\n#else /* FT_CONFIG_OPTION_PIC */ \r\n\r\n#define FT_DEFINE_SERVICE_PSFONTNAMEREC(class_, get_ps_font_name_) \\\r\n  void                                                             \\\r\n  FT_Init_Class_##class_( FT_Library library,                      \\\r\n                          FT_Service_PsFontNameRec* clazz)         \\\r\n  {                                                                \\\r\n    FT_UNUSED(library);                                            \\\r\n    clazz->get_ps_font_name = get_ps_font_name_;                   \\\r\n  } \r\n\r\n#endif /* FT_CONFIG_OPTION_PIC */ \r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n\r\n#endif /* __SVPOSTNM_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/services/svpscmap.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  svpscmap.h                                                             */\r\n/*                                                                         */\r\n/*    The FreeType PostScript charmap service (specification).             */\r\n/*                                                                         */\r\n/*  Copyright 2003, 2006 by                                                */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __SVPSCMAP_H__\r\n#define __SVPSCMAP_H__\r\n\r\n#include FT_INTERNAL_OBJECTS_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n#define FT_SERVICE_ID_POSTSCRIPT_CMAPS  \"postscript-cmaps\"\r\n\r\n\r\n  /*\r\n   *  Adobe glyph name to unicode value.\r\n   */\r\n  typedef FT_UInt32\r\n  (*PS_Unicode_ValueFunc)( const char*  glyph_name );\r\n\r\n  /*\r\n   *  Macintosh name id to glyph name.  NULL if invalid index.\r\n   */\r\n  typedef const char*\r\n  (*PS_Macintosh_NameFunc)( FT_UInt  name_index );\r\n\r\n  /*\r\n   *  Adobe standard string ID to glyph name.  NULL if invalid index.\r\n   */\r\n  typedef const char*\r\n  (*PS_Adobe_Std_StringsFunc)( FT_UInt  string_index );\r\n\r\n\r\n  /*\r\n   *  Simple unicode -> glyph index charmap built from font glyph names\r\n   *  table.\r\n   */\r\n  typedef struct  PS_UniMap_\r\n  {\r\n    FT_UInt32  unicode;      /* bit 31 set: is glyph variant */\r\n    FT_UInt    glyph_index;\r\n\r\n  } PS_UniMap;\r\n\r\n\r\n  typedef struct PS_UnicodesRec_*  PS_Unicodes;\r\n\r\n  typedef struct  PS_UnicodesRec_\r\n  {\r\n    FT_CMapRec  cmap;\r\n    FT_UInt     num_maps;\r\n    PS_UniMap*  maps;\r\n\r\n  } PS_UnicodesRec;\r\n\r\n\r\n  /*\r\n   *  A function which returns a glyph name for a given index.  Returns\r\n   *  NULL if invalid index.\r\n   */\r\n  typedef const char*\r\n  (*PS_GetGlyphNameFunc)( FT_Pointer  data,\r\n                          FT_UInt     string_index );\r\n\r\n  /*\r\n   *  A function used to release the glyph name returned by\r\n   *  PS_GetGlyphNameFunc, when needed\r\n   */\r\n  typedef void\r\n  (*PS_FreeGlyphNameFunc)( FT_Pointer  data,\r\n                           const char*  name );\r\n\r\n  typedef FT_Error\r\n  (*PS_Unicodes_InitFunc)( FT_Memory             memory,\r\n                           PS_Unicodes           unicodes,\r\n                           FT_UInt               num_glyphs,\r\n                           PS_GetGlyphNameFunc   get_glyph_name,\r\n                           PS_FreeGlyphNameFunc  free_glyph_name,\r\n                           FT_Pointer            glyph_data );\r\n\r\n  typedef FT_UInt\r\n  (*PS_Unicodes_CharIndexFunc)( PS_Unicodes  unicodes,\r\n                                FT_UInt32    unicode );\r\n\r\n  typedef FT_UInt32\r\n  (*PS_Unicodes_CharNextFunc)( PS_Unicodes  unicodes,\r\n                               FT_UInt32   *unicode );\r\n\r\n\r\n  FT_DEFINE_SERVICE( PsCMaps )\r\n  {\r\n    PS_Unicode_ValueFunc       unicode_value;\r\n\r\n    PS_Unicodes_InitFunc       unicodes_init;\r\n    PS_Unicodes_CharIndexFunc  unicodes_char_index;\r\n    PS_Unicodes_CharNextFunc   unicodes_char_next;\r\n\r\n    PS_Macintosh_NameFunc      macintosh_name;\r\n    PS_Adobe_Std_StringsFunc   adobe_std_strings;\r\n    const unsigned short*      adobe_std_encoding;\r\n    const unsigned short*      adobe_expert_encoding;\r\n  };\r\n\r\n\r\n#ifndef FT_CONFIG_OPTION_PIC\r\n\r\n#define FT_DEFINE_SERVICE_PSCMAPSREC(class_, unicode_value_, unicodes_init_, \\\r\n        unicodes_char_index_, unicodes_char_next_, macintosh_name_,          \\\r\n        adobe_std_strings_, adobe_std_encoding_, adobe_expert_encoding_)     \\\r\n  static const FT_Service_PsCMapsRec class_ =                                \\\r\n  {                                                                          \\\r\n    unicode_value_, unicodes_init_,                                          \\\r\n    unicodes_char_index_, unicodes_char_next_, macintosh_name_,              \\\r\n    adobe_std_strings_, adobe_std_encoding_, adobe_expert_encoding_          \\\r\n  };\r\n\r\n#else /* FT_CONFIG_OPTION_PIC */ \r\n\r\n#define FT_DEFINE_SERVICE_PSCMAPSREC(class_, unicode_value_, unicodes_init_, \\\r\n        unicodes_char_index_, unicodes_char_next_, macintosh_name_,          \\\r\n        adobe_std_strings_, adobe_std_encoding_, adobe_expert_encoding_)     \\\r\n  void                                                                       \\\r\n  FT_Init_Class_##class_( FT_Library library,                                \\\r\n                          FT_Service_PsCMapsRec* clazz)                      \\\r\n  {                                                                          \\\r\n    FT_UNUSED(library);                                                      \\\r\n    clazz->unicode_value = unicode_value_;                                   \\\r\n    clazz->unicodes_init = unicodes_init_;                                   \\\r\n    clazz->unicodes_char_index = unicodes_char_index_;                       \\\r\n    clazz->unicodes_char_next = unicodes_char_next_;                         \\\r\n    clazz->macintosh_name = macintosh_name_;                                 \\\r\n    clazz->adobe_std_strings = adobe_std_strings_;                           \\\r\n    clazz->adobe_std_encoding = adobe_std_encoding_;                         \\\r\n    clazz->adobe_expert_encoding = adobe_expert_encoding_;                   \\\r\n  } \r\n\r\n#endif /* FT_CONFIG_OPTION_PIC */ \r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n\r\n#endif /* __SVPSCMAP_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/services/svpsinfo.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  svpsinfo.h                                                             */\r\n/*                                                                         */\r\n/*    The FreeType PostScript info service (specification).                */\r\n/*                                                                         */\r\n/*  Copyright 2003, 2004, 2009, 2011 by                                    */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __SVPSINFO_H__\r\n#define __SVPSINFO_H__\r\n\r\n#include FT_INTERNAL_SERVICE_H\r\n#include FT_INTERNAL_TYPE1_TYPES_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n#define FT_SERVICE_ID_POSTSCRIPT_INFO  \"postscript-info\"\r\n\r\n\r\n  typedef FT_Error\r\n  (*PS_GetFontInfoFunc)( FT_Face          face,\r\n                         PS_FontInfoRec*  afont_info );\r\n\r\n  typedef FT_Error\r\n  (*PS_GetFontExtraFunc)( FT_Face           face,\r\n                          PS_FontExtraRec*  afont_extra );\r\n\r\n  typedef FT_Int\r\n  (*PS_HasGlyphNamesFunc)( FT_Face   face );\r\n\r\n  typedef FT_Error\r\n  (*PS_GetFontPrivateFunc)( FT_Face         face,\r\n                            PS_PrivateRec*  afont_private );\r\n\r\n  typedef FT_Long\r\n  (*PS_GetFontValueFunc)( FT_Face       face,\r\n                          PS_Dict_Keys  key,\r\n                          FT_UInt       idx,\r\n                          void         *value,\r\n                          FT_Long       value_len );\r\n\r\n\r\n  FT_DEFINE_SERVICE( PsInfo )\r\n  {\r\n    PS_GetFontInfoFunc     ps_get_font_info;\r\n    PS_GetFontExtraFunc    ps_get_font_extra;\r\n    PS_HasGlyphNamesFunc   ps_has_glyph_names;\r\n    PS_GetFontPrivateFunc  ps_get_font_private;\r\n    PS_GetFontValueFunc    ps_get_font_value;\r\n  };\r\n\r\n#ifndef FT_CONFIG_OPTION_PIC\r\n\r\n#define FT_DEFINE_SERVICE_PSINFOREC(class_, get_font_info_,      \\\r\n        ps_get_font_extra_, has_glyph_names_, get_font_private_, \\\r\n        get_font_value_)                                         \\\r\n  static const FT_Service_PsInfoRec class_ =                     \\\r\n  {                                                              \\\r\n    get_font_info_, ps_get_font_extra_, has_glyph_names_,        \\\r\n    get_font_private_, get_font_value_                           \\\r\n  };\r\n\r\n#else /* FT_CONFIG_OPTION_PIC */ \r\n\r\n#define FT_DEFINE_SERVICE_PSINFOREC(class_, get_font_info_,      \\\r\n        ps_get_font_extra_, has_glyph_names_, get_font_private_, \\\r\n        get_font_value_)                                         \\\r\n  void                                                           \\\r\n  FT_Init_Class_##class_( FT_Library library,                    \\\r\n                          FT_Service_PsInfoRec*  clazz)          \\\r\n  {                                                              \\\r\n    FT_UNUSED(library);                                          \\\r\n    clazz->ps_get_font_info = get_font_info_;                    \\\r\n    clazz->ps_get_font_extra = ps_get_font_extra_;               \\\r\n    clazz->ps_has_glyph_names = has_glyph_names_;                \\\r\n    clazz->ps_get_font_private = get_font_private_;              \\\r\n    clazz->ps_get_font_value = get_font_value_;                  \\\r\n  } \r\n\r\n#endif /* FT_CONFIG_OPTION_PIC */ \r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n\r\n#endif /* __SVPSINFO_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/services/svsfnt.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  svsfnt.h                                                               */\r\n/*                                                                         */\r\n/*    The FreeType SFNT table loading service (specification).             */\r\n/*                                                                         */\r\n/*  Copyright 2003, 2004 by                                                */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __SVSFNT_H__\r\n#define __SVSFNT_H__\r\n\r\n#include FT_INTERNAL_SERVICE_H\r\n#include FT_TRUETYPE_TABLES_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*\r\n   *  SFNT table loading service.\r\n   */\r\n\r\n#define FT_SERVICE_ID_SFNT_TABLE  \"sfnt-table\"\r\n\r\n\r\n  /*\r\n   * Used to implement FT_Load_Sfnt_Table().\r\n   */\r\n  typedef FT_Error\r\n  (*FT_SFNT_TableLoadFunc)( FT_Face    face,\r\n                            FT_ULong   tag,\r\n                            FT_Long    offset,\r\n                            FT_Byte*   buffer,\r\n                            FT_ULong*  length );\r\n\r\n  /*\r\n   * Used to implement FT_Get_Sfnt_Table().\r\n   */\r\n  typedef void*\r\n  (*FT_SFNT_TableGetFunc)( FT_Face      face,\r\n                           FT_Sfnt_Tag  tag );\r\n\r\n\r\n  /*\r\n   * Used to implement FT_Sfnt_Table_Info().\r\n   */\r\n  typedef FT_Error\r\n  (*FT_SFNT_TableInfoFunc)( FT_Face    face,\r\n                            FT_UInt    idx,\r\n                            FT_ULong  *tag,\r\n                            FT_ULong  *offset,\r\n                            FT_ULong  *length );\r\n\r\n\r\n  FT_DEFINE_SERVICE( SFNT_Table )\r\n  {\r\n    FT_SFNT_TableLoadFunc  load_table;\r\n    FT_SFNT_TableGetFunc   get_table;\r\n    FT_SFNT_TableInfoFunc  table_info;\r\n  };\r\n\r\n#ifndef FT_CONFIG_OPTION_PIC\r\n\r\n#define FT_DEFINE_SERVICE_SFNT_TABLEREC(class_, load_, get_, info_)  \\\r\n  static const FT_Service_SFNT_TableRec class_ =                     \\\r\n  {                                                                  \\\r\n    load_, get_, info_                                               \\\r\n  };\r\n\r\n#else /* FT_CONFIG_OPTION_PIC */ \r\n\r\n#define FT_DEFINE_SERVICE_SFNT_TABLEREC(class_, load_, get_, info_) \\\r\n  void                                                              \\\r\n  FT_Init_Class_##class_( FT_Service_SFNT_TableRec*  clazz )        \\\r\n  {                                                                 \\\r\n    clazz->load_table = load_;                                      \\\r\n    clazz->get_table = get_;                                        \\\r\n    clazz->table_info = info_;                                      \\\r\n  } \r\n\r\n#endif /* FT_CONFIG_OPTION_PIC */ \r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n\r\n#endif /* __SVSFNT_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/services/svttcmap.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  svttcmap.h                                                             */\r\n/*                                                                         */\r\n/*    The FreeType TrueType/sfnt cmap extra information service.           */\r\n/*                                                                         */\r\n/*  Copyright 2003 by                                                      */\r\n/*  Masatake YAMATO, Redhat K.K.                                           */\r\n/*                                                                         */\r\n/*  Copyright 2003, 2008 by                                                */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n/* Development of this service is support of\r\n   Information-technology Promotion Agency, Japan. */\r\n\r\n#ifndef __SVTTCMAP_H__\r\n#define __SVTTCMAP_H__\r\n\r\n#include FT_INTERNAL_SERVICE_H\r\n#include FT_TRUETYPE_TABLES_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n#define FT_SERVICE_ID_TT_CMAP \"tt-cmaps\"\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_CMapInfo                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to store TrueType/sfnt specific cmap information  */\r\n  /*    which is not covered by the generic @FT_CharMap structure.  This   */\r\n  /*    structure can be accessed with the @FT_Get_TT_CMap_Info function.  */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    language ::                                                        */\r\n  /*      The language ID used in Mac fonts.  Definitions of values are in */\r\n  /*      freetype/ttnameid.h.                                             */\r\n  /*                                                                       */\r\n  /*    format ::                                                          */\r\n  /*      The cmap format.  OpenType 1.5 defines the formats 0 (byte       */\r\n  /*      encoding table), 2~(high-byte mapping through table), 4~(segment */\r\n  /*      mapping to delta values), 6~(trimmed table mapping), 8~(mixed    */\r\n  /*      16-bit and 32-bit coverage), 10~(trimmed array), 12~(segmented   */\r\n  /*      coverage), and 14 (Unicode Variation Sequences).                 */\r\n  /*                                                                       */\r\n  typedef struct  TT_CMapInfo_\r\n  {\r\n    FT_ULong language;\r\n    FT_Long  format;\r\n\r\n  } TT_CMapInfo;\r\n\r\n\r\n  typedef FT_Error\r\n  (*TT_CMap_Info_GetFunc)( FT_CharMap    charmap,\r\n                           TT_CMapInfo  *cmap_info );\r\n\r\n\r\n  FT_DEFINE_SERVICE( TTCMaps )\r\n  {\r\n    TT_CMap_Info_GetFunc  get_cmap_info;\r\n  };\r\n\r\n#ifndef FT_CONFIG_OPTION_PIC\r\n\r\n#define FT_DEFINE_SERVICE_TTCMAPSREC(class_, get_cmap_info_)  \\\r\n  static const FT_Service_TTCMapsRec class_ =                 \\\r\n  {                                                           \\\r\n    get_cmap_info_                                            \\\r\n  };\r\n\r\n#else /* FT_CONFIG_OPTION_PIC */ \r\n\r\n#define FT_DEFINE_SERVICE_TTCMAPSREC(class_, get_cmap_info_) \\\r\n  void                                                       \\\r\n  FT_Init_Class_##class_( FT_Library library,                \\\r\n                          FT_Service_TTCMapsRec*  clazz)     \\\r\n  {                                                          \\\r\n    FT_UNUSED(library);                                      \\\r\n    clazz->get_cmap_info = get_cmap_info_;                   \\\r\n  } \r\n\r\n#endif /* FT_CONFIG_OPTION_PIC */ \r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __SVTTCMAP_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/services/svtteng.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  svtteng.h                                                              */\r\n/*                                                                         */\r\n/*    The FreeType TrueType engine query service (specification).          */\r\n/*                                                                         */\r\n/*  Copyright 2006 by                                                      */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __SVTTENG_H__\r\n#define __SVTTENG_H__\r\n\r\n#include FT_INTERNAL_SERVICE_H\r\n#include FT_MODULE_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*\r\n   *  SFNT table loading service.\r\n   */\r\n\r\n#define FT_SERVICE_ID_TRUETYPE_ENGINE  \"truetype-engine\"\r\n\r\n  /*\r\n   * Used to implement FT_Get_TrueType_Engine_Type\r\n   */\r\n\r\n  FT_DEFINE_SERVICE( TrueTypeEngine )\r\n  {\r\n    FT_TrueTypeEngineType  engine_type;\r\n  };\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n\r\n#endif /* __SVTTENG_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/services/svttglyf.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  svttglyf.h                                                             */\r\n/*                                                                         */\r\n/*    The FreeType TrueType glyph service.                                 */\r\n/*                                                                         */\r\n/*  Copyright 2007 by David Turner.                                        */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n#ifndef __SVTTGLYF_H__\r\n#define __SVTTGLYF_H__\r\n\r\n#include FT_INTERNAL_SERVICE_H\r\n#include FT_TRUETYPE_TABLES_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n#define FT_SERVICE_ID_TT_GLYF \"tt-glyf\"\r\n\r\n\r\n  typedef FT_ULong\r\n  (*TT_Glyf_GetLocationFunc)( FT_Face    face,\r\n                              FT_UInt    gindex,\r\n                              FT_ULong  *psize );\r\n\r\n  FT_DEFINE_SERVICE( TTGlyf )\r\n  {\r\n    TT_Glyf_GetLocationFunc  get_location;\r\n  };\r\n\r\n#ifndef FT_CONFIG_OPTION_PIC\r\n\r\n#define FT_DEFINE_SERVICE_TTGLYFREC(class_, get_location_ )   \\\r\n  static const FT_Service_TTGlyfRec class_ =                  \\\r\n  {                                                           \\\r\n    get_location_                                             \\\r\n  };\r\n\r\n#else /* FT_CONFIG_OPTION_PIC */ \r\n\r\n#define FT_DEFINE_SERVICE_TTGLYFREC(class_, get_location_ )   \\\r\n  void                                                        \\\r\n  FT_Init_Class_##class_( FT_Service_TTGlyfRec*  clazz )      \\\r\n  {                                                           \\\r\n    clazz->get_location = get_location_;                      \\\r\n  } \r\n\r\n#endif /* FT_CONFIG_OPTION_PIC */ \r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __SVTTGLYF_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/services/svwinfnt.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  svwinfnt.h                                                             */\r\n/*                                                                         */\r\n/*    The FreeType Windows FNT/FONT service (specification).               */\r\n/*                                                                         */\r\n/*  Copyright 2003 by                                                      */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __SVWINFNT_H__\r\n#define __SVWINFNT_H__\r\n\r\n#include FT_INTERNAL_SERVICE_H\r\n#include FT_WINFONTS_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n#define FT_SERVICE_ID_WINFNT  \"winfonts\"\r\n\r\n  typedef FT_Error\r\n  (*FT_WinFnt_GetHeaderFunc)( FT_Face               face,\r\n                              FT_WinFNT_HeaderRec  *aheader );\r\n\r\n\r\n  FT_DEFINE_SERVICE( WinFnt )\r\n  {\r\n    FT_WinFnt_GetHeaderFunc  get_header;\r\n  };\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n\r\n#endif /* __SVWINFNT_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/services/svxf86nm.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  svxf86nm.h                                                             */\r\n/*                                                                         */\r\n/*    The FreeType XFree86 services (specification only).                  */\r\n/*                                                                         */\r\n/*  Copyright 2003 by                                                      */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __SVXF86NM_H__\r\n#define __SVXF86NM_H__\r\n\r\n#include FT_INTERNAL_SERVICE_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*\r\n   *  A trivial service used to return the name of a face's font driver,\r\n   *  according to the XFree86 nomenclature.  Note that the service data\r\n   *  is a simple constant string pointer.\r\n   */\r\n\r\n#define FT_SERVICE_ID_XF86_NAME  \"xf86-driver-name\"\r\n\r\n#define FT_XF86_FORMAT_TRUETYPE  \"TrueType\"\r\n#define FT_XF86_FORMAT_TYPE_1    \"Type 1\"\r\n#define FT_XF86_FORMAT_BDF       \"BDF\"\r\n#define FT_XF86_FORMAT_PCF       \"PCF\"\r\n#define FT_XF86_FORMAT_TYPE_42   \"Type 42\"\r\n#define FT_XF86_FORMAT_CID       \"CID Type 1\"\r\n#define FT_XF86_FORMAT_CFF       \"CFF\"\r\n#define FT_XF86_FORMAT_PFR       \"PFR\"\r\n#define FT_XF86_FORMAT_WINFNT    \"Windows FNT\"\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n\r\n#endif /* __SVXF86NM_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/sfnt.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  sfnt.h                                                                 */\r\n/*                                                                         */\r\n/*    High-level `sfnt' driver interface (specification).                  */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006 by                   */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __SFNT_H__\r\n#define __SFNT_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_INTERNAL_DRIVER_H\r\n#include FT_INTERNAL_TRUETYPE_TYPES_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_Init_Face_Func                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    First part of the SFNT face object initialization.  This finds     */\r\n  /*    the face in a SFNT file or collection, and load its format tag in  */\r\n  /*    face->format_tag.                                                  */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    stream     :: The input stream.                                    */\r\n  /*                                                                       */\r\n  /*    face       :: A handle to the target face object.                  */\r\n  /*                                                                       */\r\n  /*    face_index :: The index of the TrueType font, if we are opening a  */\r\n  /*                  collection.                                          */\r\n  /*                                                                       */\r\n  /*    num_params :: The number of additional parameters.                 */\r\n  /*                                                                       */\r\n  /*    params     :: Optional additional parameters.                      */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0 means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The stream cursor must be at the font file's origin.               */\r\n  /*                                                                       */\r\n  /*    This function recognizes fonts embedded in a `TrueType             */\r\n  /*    collection'.                                                       */\r\n  /*                                                                       */\r\n  /*    Once the format tag has been validated by the font driver, it      */\r\n  /*    should then call the TT_Load_Face_Func() callback to read the rest */\r\n  /*    of the SFNT tables in the object.                                  */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*TT_Init_Face_Func)( FT_Stream      stream,\r\n                        TT_Face        face,\r\n                        FT_Int         face_index,\r\n                        FT_Int         num_params,\r\n                        FT_Parameter*  params );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_Load_Face_Func                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Second part of the SFNT face object initialization.  This loads    */\r\n  /*    the common SFNT tables (head, OS/2, maxp, metrics, etc.) in the    */\r\n  /*    face object.                                                       */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    stream     :: The input stream.                                    */\r\n  /*                                                                       */\r\n  /*    face       :: A handle to the target face object.                  */\r\n  /*                                                                       */\r\n  /*    face_index :: The index of the TrueType font, if we are opening a  */\r\n  /*                  collection.                                          */\r\n  /*                                                                       */\r\n  /*    num_params :: The number of additional parameters.                 */\r\n  /*                                                                       */\r\n  /*    params     :: Optional additional parameters.                      */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0 means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    This function must be called after TT_Init_Face_Func().            */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*TT_Load_Face_Func)( FT_Stream      stream,\r\n                        TT_Face        face,\r\n                        FT_Int         face_index,\r\n                        FT_Int         num_params,\r\n                        FT_Parameter*  params );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_Done_Face_Func                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A callback used to delete the common SFNT data from a face.        */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face :: A handle to the target face object.                        */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    This function does NOT destroy the face object.                    */\r\n  /*                                                                       */\r\n  typedef void\r\n  (*TT_Done_Face_Func)( TT_Face  face );\r\n\r\n\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_Load_SFNT_HeaderRec_Func                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Loads the header of a SFNT font file.  Supports collections.       */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face       :: A handle to the target face object.                  */\r\n  /*                                                                       */\r\n  /*    stream     :: The input stream.                                    */\r\n  /*                                                                       */\r\n  /*    face_index :: The index of the TrueType font, if we are opening a  */\r\n  /*                  collection.                                          */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    sfnt       :: The SFNT header.                                     */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0 means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The stream cursor must be at the font file's origin.               */\r\n  /*                                                                       */\r\n  /*    This function recognizes fonts embedded in a `TrueType             */\r\n  /*    collection'.                                                       */\r\n  /*                                                                       */\r\n  /*    This function checks that the header is valid by looking at the    */\r\n  /*    values of `search_range', `entry_selector', and `range_shift'.     */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*TT_Load_SFNT_HeaderRec_Func)( TT_Face      face,\r\n                                  FT_Stream    stream,\r\n                                  FT_Long      face_index,\r\n                                  SFNT_Header  sfnt );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_Load_Directory_Func                                             */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Loads the table directory into a face object.                      */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face   :: A handle to the target face object.                      */\r\n  /*                                                                       */\r\n  /*    stream :: The input stream.                                        */\r\n  /*                                                                       */\r\n  /*    sfnt   :: The SFNT header.                                         */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0 means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The stream cursor must be on the first byte after the 4-byte font  */\r\n  /*    format tag.  This is the case just after a call to                 */\r\n  /*    TT_Load_Format_Tag().                                              */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*TT_Load_Directory_Func)( TT_Face      face,\r\n                             FT_Stream    stream,\r\n                             SFNT_Header  sfnt );\r\n\r\n#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_Load_Any_Func                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Load any font table into client memory.                            */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face   :: The face object to look for.                             */\r\n  /*                                                                       */\r\n  /*    tag    :: The tag of table to load.  Use the value 0 if you want   */\r\n  /*              to access the whole font file, else set this parameter   */\r\n  /*              to a valid TrueType table tag that you can forge with    */\r\n  /*              the MAKE_TT_TAG macro.                                   */\r\n  /*                                                                       */\r\n  /*    offset :: The starting offset in the table (or the file if         */\r\n  /*              tag == 0).                                               */\r\n  /*                                                                       */\r\n  /*    length :: The address of the decision variable:                    */\r\n  /*                                                                       */\r\n  /*                If length == NULL:                                     */\r\n  /*                  Loads the whole table.  Returns an error if          */\r\n  /*                  `offset' == 0!                                       */\r\n  /*                                                                       */\r\n  /*                If *length == 0:                                       */\r\n  /*                  Exits immediately; returning the length of the given */\r\n  /*                  table or of the font file, depending on the value of */\r\n  /*                  `tag'.                                               */\r\n  /*                                                                       */\r\n  /*                If *length != 0:                                       */\r\n  /*                  Loads the next `length' bytes of table or font,      */\r\n  /*                  starting at offset `offset' (in table or font too).  */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    buffer :: The address of target buffer.                            */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    TrueType error code.  0 means success.                             */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*TT_Load_Any_Func)( TT_Face    face,\r\n                       FT_ULong   tag,\r\n                       FT_Long    offset,\r\n                       FT_Byte   *buffer,\r\n                       FT_ULong*  length );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_Find_SBit_Image_Func                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Check whether an embedded bitmap (an `sbit') exists for a given    */\r\n  /*    glyph, at a given strike.                                          */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face          :: The target face object.                           */\r\n  /*                                                                       */\r\n  /*    glyph_index   :: The glyph index.                                  */\r\n  /*                                                                       */\r\n  /*    strike_index  :: The current strike index.                         */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    arange        :: The SBit range containing the glyph index.        */\r\n  /*                                                                       */\r\n  /*    astrike       :: The SBit strike containing the glyph index.       */\r\n  /*                                                                       */\r\n  /*    aglyph_offset :: The offset of the glyph data in `EBDT' table.     */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0 means success.  Returns                    */\r\n  /*    SFNT_Err_Invalid_Argument if no sbit exists for the requested      */\r\n  /*    glyph.                                                             */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*TT_Find_SBit_Image_Func)( TT_Face          face,\r\n                              FT_UInt          glyph_index,\r\n                              FT_ULong         strike_index,\r\n                              TT_SBit_Range   *arange,\r\n                              TT_SBit_Strike  *astrike,\r\n                              FT_ULong        *aglyph_offset );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_Load_SBit_Metrics_Func                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Get the big metrics for a given embedded bitmap.                   */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    stream      :: The input stream.                                   */\r\n  /*                                                                       */\r\n  /*    range       :: The SBit range containing the glyph.                */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    big_metrics :: A big SBit metrics structure for the glyph.         */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0 means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The stream cursor must be positioned at the glyph's offset within  */\r\n  /*    the `EBDT' table before the call.                                  */\r\n  /*                                                                       */\r\n  /*    If the image format uses variable metrics, the stream cursor is    */\r\n  /*    positioned just after the metrics header in the `EBDT' table on    */\r\n  /*    function exit.                                                     */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*TT_Load_SBit_Metrics_Func)( FT_Stream        stream,\r\n                                TT_SBit_Range    range,\r\n                                TT_SBit_Metrics  metrics );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_Load_SBit_Image_Func                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Load a given glyph sbit image from the font resource.  This also   */\r\n  /*    returns its metrics.                                               */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face ::                                                            */\r\n  /*      The target face object.                                          */\r\n  /*                                                                       */\r\n  /*    strike_index ::                                                    */\r\n  /*      The strike index.                                                */\r\n  /*                                                                       */\r\n  /*    glyph_index ::                                                     */\r\n  /*      The current glyph index.                                         */\r\n  /*                                                                       */\r\n  /*    load_flags ::                                                      */\r\n  /*      The current load flags.                                          */\r\n  /*                                                                       */\r\n  /*    stream ::                                                          */\r\n  /*      The input stream.                                                */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    amap ::                                                            */\r\n  /*      The target pixmap.                                               */\r\n  /*                                                                       */\r\n  /*    ametrics ::                                                        */\r\n  /*      A big sbit metrics structure for the glyph image.                */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0 means success.  Returns an error if no     */\r\n  /*    glyph sbit exists for the index.                                   */\r\n  /*                                                                       */\r\n  /*  <Note>                                                               */\r\n  /*    The `map.buffer' field is always freed before the glyph is loaded. */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*TT_Load_SBit_Image_Func)( TT_Face              face,\r\n                              FT_ULong             strike_index,\r\n                              FT_UInt              glyph_index,\r\n                              FT_UInt              load_flags,\r\n                              FT_Stream            stream,\r\n                              FT_Bitmap           *amap,\r\n                              TT_SBit_MetricsRec  *ametrics );\r\n\r\n\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_Set_SBit_Strike_OldFunc                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Select an sbit strike for a given size request.                    */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face          :: The target face object.                           */\r\n  /*                                                                       */\r\n  /*    req           :: The size request.                                 */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    astrike_index :: The index of the sbit strike.                     */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0 means success.  Returns an error if no     */\r\n  /*    sbit strike exists for the selected ppem values.                   */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*TT_Set_SBit_Strike_OldFunc)( TT_Face    face,\r\n                                 FT_UInt    x_ppem,\r\n                                 FT_UInt    y_ppem,\r\n                                 FT_ULong*  astrike_index );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_CharMap_Load_Func                                               */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Loads a given TrueType character map into memory.                  */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face   :: A handle to the parent face object.                      */\r\n  /*                                                                       */\r\n  /*    stream :: A handle to the current stream object.                   */\r\n  /*                                                                       */\r\n  /* <InOut>                                                               */\r\n  /*    cmap   :: A pointer to a cmap object.                              */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0 means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The function assumes that the stream is already in use (i.e.,      */\r\n  /*    opened).  In case of error, all partially allocated tables are     */\r\n  /*    released.                                                          */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*TT_CharMap_Load_Func)( TT_Face    face,\r\n                           void*      cmap,\r\n                           FT_Stream  input );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_CharMap_Free_Func                                               */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Destroys a character mapping table.                                */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face :: A handle to the parent face object.                        */\r\n  /*                                                                       */\r\n  /*    cmap :: A handle to a cmap object.                                 */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0 means success.                             */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*TT_CharMap_Free_Func)( TT_Face       face,\r\n                           void*         cmap );\r\n\r\n#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_Set_SBit_Strike_Func                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Select an sbit strike for a given size request.                    */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face          :: The target face object.                           */\r\n  /*                                                                       */\r\n  /*    req           :: The size request.                                 */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    astrike_index :: The index of the sbit strike.                     */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0 means success.  Returns an error if no     */\r\n  /*    sbit strike exists for the selected ppem values.                   */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*TT_Set_SBit_Strike_Func)( TT_Face          face,\r\n                              FT_Size_Request  req,\r\n                              FT_ULong*        astrike_index );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_Load_Strike_Metrics_Func                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Load the metrics of a given strike.                                */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face          :: The target face object.                           */\r\n  /*                                                                       */\r\n  /*    strike_index  :: The strike index.                                 */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    metrics       :: the metrics of the strike.                        */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0 means success.  Returns an error if no     */\r\n  /*    such sbit strike exists.                                           */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*TT_Load_Strike_Metrics_Func)( TT_Face           face,\r\n                                  FT_ULong          strike_index,\r\n                                  FT_Size_Metrics*  metrics );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_Get_PS_Name_Func                                                */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Get the PostScript glyph name of a glyph.                          */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    idx  :: The glyph index.                                           */\r\n  /*                                                                       */\r\n  /*    PSname :: The address of a string pointer.  Will be NULL in case   */\r\n  /*              of error, otherwise it is a pointer to the glyph name.   */\r\n  /*                                                                       */\r\n  /*              You must not modify the returned string!                 */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    FreeType error code.  0 means success.                             */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*TT_Get_PS_Name_Func)( TT_Face      face,\r\n                          FT_UInt      idx,\r\n                          FT_String**  PSname );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_Load_Metrics_Func                                               */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Load a metrics table, which is a table with a horizontal and a     */\r\n  /*    vertical version.                                                  */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face     :: A handle to the target face object.                    */\r\n  /*                                                                       */\r\n  /*    stream   :: The input stream.                                      */\r\n  /*                                                                       */\r\n  /*    vertical :: A boolean flag.  If set, load the vertical one.        */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0 means success.                             */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*TT_Load_Metrics_Func)( TT_Face    face,\r\n                           FT_Stream  stream,\r\n                           FT_Bool    vertical );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_Get_Metrics_Func                                                */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Load the horizontal or vertical header in a face object.           */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face     :: A handle to the target face object.                    */\r\n  /*                                                                       */\r\n  /*    stream   :: The input stream.                                      */\r\n  /*                                                                       */\r\n  /*    vertical :: A boolean flag.  If set, load vertical metrics.        */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0 means success.                             */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*TT_Get_Metrics_Func)( TT_Face     face,\r\n                          FT_Bool     vertical,\r\n                          FT_UInt     gindex,\r\n                          FT_Short*   abearing,\r\n                          FT_UShort*  aadvance );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_Load_Table_Func                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Load a given TrueType table.                                       */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face   :: A handle to the target face object.                      */\r\n  /*                                                                       */\r\n  /*    stream :: The input stream.                                        */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0 means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The function uses `face->goto_table' to seek the stream to the     */\r\n  /*    start of the table, except while loading the font directory.       */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*TT_Load_Table_Func)( TT_Face    face,\r\n                         FT_Stream  stream );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_Free_Table_Func                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Free a given TrueType table.                                       */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face :: A handle to the target face object.                        */\r\n  /*                                                                       */\r\n  typedef void\r\n  (*TT_Free_Table_Func)( TT_Face  face );\r\n\r\n\r\n  /*\r\n   * @functype:\r\n   *    TT_Face_GetKerningFunc\r\n   *\r\n   * @description:\r\n   *    Return the horizontal kerning value between two glyphs.\r\n   *\r\n   * @input:\r\n   *    face        :: A handle to the source face object.\r\n   *    left_glyph  :: The left glyph index.\r\n   *    right_glyph :: The right glyph index.\r\n   *\r\n   * @return:\r\n   *    The kerning value in font units.\r\n   */\r\n  typedef FT_Int\r\n  (*TT_Face_GetKerningFunc)( TT_Face  face,\r\n                             FT_UInt  left_glyph,\r\n                             FT_UInt  right_glyph );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    SFNT_Interface                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This structure holds pointers to the functions used to load and    */\r\n  /*    free the basic tables that are required in a `sfnt' font file.     */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    Check the various xxx_Func() descriptions for details.             */\r\n  /*                                                                       */\r\n  typedef struct  SFNT_Interface_\r\n  {\r\n    TT_Loader_GotoTableFunc      goto_table;\r\n\r\n    TT_Init_Face_Func            init_face;\r\n    TT_Load_Face_Func            load_face;\r\n    TT_Done_Face_Func            done_face;\r\n    FT_Module_Requester          get_interface;\r\n\r\n    TT_Load_Any_Func             load_any;\r\n\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n    TT_Load_SFNT_HeaderRec_Func  load_sfnt_header;\r\n    TT_Load_Directory_Func       load_directory;\r\n#endif\r\n\r\n    /* these functions are called by `load_face' but they can also  */\r\n    /* be called from external modules, if there is a need to do so */\r\n    TT_Load_Table_Func           load_head;\r\n    TT_Load_Metrics_Func         load_hhea;\r\n    TT_Load_Table_Func           load_cmap;\r\n    TT_Load_Table_Func           load_maxp;\r\n    TT_Load_Table_Func           load_os2;\r\n    TT_Load_Table_Func           load_post;\r\n\r\n    TT_Load_Table_Func           load_name;\r\n    TT_Free_Table_Func           free_name;\r\n\r\n    /* optional tables */\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n    TT_Load_Table_Func           load_hdmx_stub;\r\n    TT_Free_Table_Func           free_hdmx_stub;\r\n#endif\r\n\r\n    /* this field was called `load_kerning' up to version 2.1.10 */\r\n    TT_Load_Table_Func           load_kern;\r\n\r\n    TT_Load_Table_Func           load_gasp;\r\n    TT_Load_Table_Func           load_pclt;\r\n\r\n    /* see `ttload.h'; this field was called `load_bitmap_header' up to */\r\n    /* version 2.1.10                                                   */\r\n    TT_Load_Table_Func           load_bhed;\r\n\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n\r\n    /* see `ttsbit.h' */\r\n    TT_Set_SBit_Strike_OldFunc   set_sbit_strike_stub;\r\n    TT_Load_Table_Func           load_sbits_stub;\r\n\r\n    /*\r\n     *  The following two fields appeared in version 2.1.8, and were placed\r\n     *  between `load_sbits' and `load_sbit_image'.  We support them as a\r\n     *  special exception since they are used by Xfont library within the\r\n     *  X.Org xserver, and because the probability that other rogue clients\r\n     *  use the other version 2.1.7 fields below is _extremely_ low.\r\n     *\r\n     *  Note that this forces us to disable an interesting memory-saving\r\n     *  optimization though...\r\n     */\r\n\r\n    TT_Find_SBit_Image_Func      find_sbit_image;\r\n    TT_Load_SBit_Metrics_Func    load_sbit_metrics;\r\n\r\n#endif\r\n\r\n    TT_Load_SBit_Image_Func      load_sbit_image;\r\n\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n    TT_Free_Table_Func           free_sbits_stub;\r\n#endif\r\n\r\n    /* see `ttpost.h' */\r\n    TT_Get_PS_Name_Func          get_psname;\r\n    TT_Free_Table_Func           free_psnames;\r\n\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n    TT_CharMap_Load_Func         load_charmap_stub;\r\n    TT_CharMap_Free_Func         free_charmap_stub;\r\n#endif\r\n\r\n    /* starting here, the structure differs from version 2.1.7 */\r\n\r\n    /* this field was introduced in version 2.1.8, named `get_psname' */\r\n    TT_Face_GetKerningFunc       get_kerning;\r\n\r\n    /* new elements introduced after version 2.1.10 */\r\n\r\n    /* load the font directory, i.e., the offset table and */\r\n    /* the table directory                                 */\r\n    TT_Load_Table_Func           load_font_dir;\r\n    TT_Load_Metrics_Func         load_hmtx;\r\n\r\n    TT_Load_Table_Func           load_eblc;\r\n    TT_Free_Table_Func           free_eblc;\r\n\r\n    TT_Set_SBit_Strike_Func      set_sbit_strike;\r\n    TT_Load_Strike_Metrics_Func  load_strike_metrics;\r\n\r\n    TT_Get_Metrics_Func          get_metrics;\r\n\r\n  } SFNT_Interface;\r\n\r\n\r\n  /* transitional */\r\n  typedef SFNT_Interface*   SFNT_Service;\r\n\r\n#ifndef FT_CONFIG_OPTION_PIC\r\n\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n#define FT_DEFINE_DRIVERS_OLD_INTERNAL(a) \\\r\n  a, \r\n#else\r\n  #define FT_DEFINE_DRIVERS_OLD_INTERNAL(a)\r\n#endif\r\n#define FT_INTERNAL(a) \\\r\n  a, \r\n\r\n#define FT_DEFINE_SFNT_INTERFACE(class_,                                     \\\r\n    goto_table_, init_face_, load_face_, done_face_, get_interface_,         \\\r\n    load_any_, load_sfnt_header_, load_directory_, load_head_,               \\\r\n    load_hhea_, load_cmap_, load_maxp_, load_os2_, load_post_,               \\\r\n    load_name_, free_name_, load_hdmx_stub_, free_hdmx_stub_,                \\\r\n    load_kern_, load_gasp_, load_pclt_, load_bhed_,                          \\\r\n    set_sbit_strike_stub_, load_sbits_stub_, find_sbit_image_,               \\\r\n    load_sbit_metrics_, load_sbit_image_, free_sbits_stub_,                  \\\r\n    get_psname_, free_psnames_, load_charmap_stub_, free_charmap_stub_,      \\\r\n    get_kerning_, load_font_dir_, load_hmtx_, load_eblc_, free_eblc_,        \\\r\n    set_sbit_strike_, load_strike_metrics_, get_metrics_ )                   \\\r\n  static const SFNT_Interface class_ =                                       \\\r\n  {                                                                          \\\r\n    FT_INTERNAL(goto_table_) \\\r\n    FT_INTERNAL(init_face_) \\\r\n    FT_INTERNAL(load_face_) \\\r\n    FT_INTERNAL(done_face_) \\\r\n    FT_INTERNAL(get_interface_) \\\r\n    FT_INTERNAL(load_any_) \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNAL(load_sfnt_header_) \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNAL(load_directory_) \\\r\n    FT_INTERNAL(load_head_) \\\r\n    FT_INTERNAL(load_hhea_) \\\r\n    FT_INTERNAL(load_cmap_) \\\r\n    FT_INTERNAL(load_maxp_) \\\r\n    FT_INTERNAL(load_os2_) \\\r\n    FT_INTERNAL(load_post_) \\\r\n    FT_INTERNAL(load_name_) \\\r\n    FT_INTERNAL(free_name_) \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNAL(load_hdmx_stub_) \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNAL(free_hdmx_stub_) \\\r\n    FT_INTERNAL(load_kern_) \\\r\n    FT_INTERNAL(load_gasp_) \\\r\n    FT_INTERNAL(load_pclt_) \\\r\n    FT_INTERNAL(load_bhed_) \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNAL(set_sbit_strike_stub_) \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNAL(load_sbits_stub_) \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNAL(find_sbit_image_) \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNAL(load_sbit_metrics_) \\\r\n    FT_INTERNAL(load_sbit_image_) \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNAL(free_sbits_stub_) \\\r\n    FT_INTERNAL(get_psname_) \\\r\n    FT_INTERNAL(free_psnames_) \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNAL(load_charmap_stub_) \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNAL(free_charmap_stub_) \\\r\n    FT_INTERNAL(get_kerning_) \\\r\n    FT_INTERNAL(load_font_dir_) \\\r\n    FT_INTERNAL(load_hmtx_) \\\r\n    FT_INTERNAL(load_eblc_) \\\r\n    FT_INTERNAL(free_eblc_) \\\r\n    FT_INTERNAL(set_sbit_strike_) \\\r\n    FT_INTERNAL(load_strike_metrics_) \\\r\n    FT_INTERNAL(get_metrics_) \\\r\n  };\r\n\r\n#else /* FT_CONFIG_OPTION_PIC */ \r\n\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n#define FT_DEFINE_DRIVERS_OLD_INTERNAL(a, a_) \\\r\n  clazz->a = a_;\r\n#else\r\n  #define FT_DEFINE_DRIVERS_OLD_INTERNAL(a, a_)\r\n#endif\r\n#define FT_INTERNAL(a, a_) \\\r\n  clazz->a = a_;\r\n\r\n#define FT_DEFINE_SFNT_INTERFACE(class_,                                     \\\r\n    goto_table_, init_face_, load_face_, done_face_, get_interface_,         \\\r\n    load_any_, load_sfnt_header_, load_directory_, load_head_,               \\\r\n    load_hhea_, load_cmap_, load_maxp_, load_os2_, load_post_,               \\\r\n    load_name_, free_name_, load_hdmx_stub_, free_hdmx_stub_,                \\\r\n    load_kern_, load_gasp_, load_pclt_, load_bhed_,                          \\\r\n    set_sbit_strike_stub_, load_sbits_stub_, find_sbit_image_,               \\\r\n    load_sbit_metrics_, load_sbit_image_, free_sbits_stub_,                  \\\r\n    get_psname_, free_psnames_, load_charmap_stub_, free_charmap_stub_,      \\\r\n    get_kerning_, load_font_dir_, load_hmtx_, load_eblc_, free_eblc_,        \\\r\n    set_sbit_strike_, load_strike_metrics_, get_metrics_ )                   \\\r\n  void                                                                       \\\r\n  FT_Init_Class_##class_( FT_Library library, SFNT_Interface*  clazz )       \\\r\n  {                                                                          \\\r\n    FT_UNUSED(library);                                                      \\\r\n    FT_INTERNAL(goto_table,goto_table_) \\\r\n    FT_INTERNAL(init_face,init_face_) \\\r\n    FT_INTERNAL(load_face,load_face_) \\\r\n    FT_INTERNAL(done_face,done_face_) \\\r\n    FT_INTERNAL(get_interface,get_interface_) \\\r\n    FT_INTERNAL(load_any,load_any_) \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNAL(load_sfnt_header,load_sfnt_header_) \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNAL(load_directory,load_directory_) \\\r\n    FT_INTERNAL(load_head,load_head_) \\\r\n    FT_INTERNAL(load_hhea,load_hhea_) \\\r\n    FT_INTERNAL(load_cmap,load_cmap_) \\\r\n    FT_INTERNAL(load_maxp,load_maxp_) \\\r\n    FT_INTERNAL(load_os2,load_os2_) \\\r\n    FT_INTERNAL(load_post,load_post_) \\\r\n    FT_INTERNAL(load_name,load_name_) \\\r\n    FT_INTERNAL(free_name,free_name_) \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNAL(load_hdmx_stub,load_hdmx_stub_) \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNAL(free_hdmx_stub,free_hdmx_stub_) \\\r\n    FT_INTERNAL(load_kern,load_kern_) \\\r\n    FT_INTERNAL(load_gasp,load_gasp_) \\\r\n    FT_INTERNAL(load_pclt,load_pclt_) \\\r\n    FT_INTERNAL(load_bhed,load_bhed_) \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNAL(set_sbit_strike_stub,set_sbit_strike_stub_) \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNAL(load_sbits_stub,load_sbits_stub_) \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNAL(find_sbit_image,find_sbit_image_) \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNAL(load_sbit_metrics,load_sbit_metrics_) \\\r\n    FT_INTERNAL(load_sbit_image,load_sbit_image_) \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNAL(free_sbits_stub,free_sbits_stub_) \\\r\n    FT_INTERNAL(get_psname,get_psname_) \\\r\n    FT_INTERNAL(free_psnames,free_psnames_) \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNAL(load_charmap_stub,load_charmap_stub_) \\\r\n    FT_DEFINE_DRIVERS_OLD_INTERNAL(free_charmap_stub,free_charmap_stub_) \\\r\n    FT_INTERNAL(get_kerning,get_kerning_) \\\r\n    FT_INTERNAL(load_font_dir,load_font_dir_) \\\r\n    FT_INTERNAL(load_hmtx,load_hmtx_) \\\r\n    FT_INTERNAL(load_eblc,load_eblc_) \\\r\n    FT_INTERNAL(free_eblc,free_eblc_) \\\r\n    FT_INTERNAL(set_sbit_strike,set_sbit_strike_) \\\r\n    FT_INTERNAL(load_strike_metrics,load_strike_metrics_) \\\r\n    FT_INTERNAL(get_metrics,get_metrics_) \\\r\n  } \r\n\r\n#endif /* FT_CONFIG_OPTION_PIC */ \r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __SFNT_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/t1types.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  t1types.h                                                              */\r\n/*                                                                         */\r\n/*    Basic Type1/Type2 type definitions and interface (specification      */\r\n/*    only).                                                               */\r\n/*                                                                         */\r\n/*  Copyright 1996-2004, 2006, 2008, 2009, 2011 by                         */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __T1TYPES_H__\r\n#define __T1TYPES_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_TYPE1_TABLES_H\r\n#include FT_INTERNAL_POSTSCRIPT_HINTS_H\r\n#include FT_INTERNAL_SERVICE_H\r\n#include FT_SERVICE_POSTSCRIPT_CMAPS_H\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /***                                                                   ***/\r\n  /***                                                                   ***/\r\n  /***              REQUIRED TYPE1/TYPE2 TABLES DEFINITIONS              ***/\r\n  /***                                                                   ***/\r\n  /***                                                                   ***/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    T1_EncodingRec                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure modeling a custom encoding.                            */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    num_chars  :: The number of character codes in the encoding.       */\r\n  /*                  Usually 256.                                         */\r\n  /*                                                                       */\r\n  /*    code_first :: The lowest valid character code in the encoding.     */\r\n  /*                                                                       */\r\n  /*    code_last  :: The highest valid character code in the encoding     */\r\n  /*                  + 1. When equal to code_first there are no valid     */\r\n  /*                  character codes.                                     */\r\n  /*                                                                       */\r\n  /*    char_index :: An array of corresponding glyph indices.             */\r\n  /*                                                                       */\r\n  /*    char_name  :: An array of corresponding glyph names.               */\r\n  /*                                                                       */\r\n  typedef struct  T1_EncodingRecRec_\r\n  {\r\n    FT_Int       num_chars;\r\n    FT_Int       code_first;\r\n    FT_Int       code_last;\r\n\r\n    FT_UShort*   char_index;\r\n    FT_String**  char_name;\r\n\r\n  } T1_EncodingRec, *T1_Encoding;\r\n\r\n\r\n  /* used to hold extra data of PS_FontInfoRec that\r\n   * cannot be stored in the publicly defined structure.\r\n   *\r\n   * Note these can't be blended with multiple-masters.\r\n   */\r\n  typedef struct  PS_FontExtraRec_\r\n  {\r\n    FT_UShort  fs_type;\r\n\r\n  } PS_FontExtraRec;\r\n\r\n\r\n  typedef struct  T1_FontRec_\r\n  {\r\n    PS_FontInfoRec   font_info;         /* font info dictionary   */\r\n    PS_FontExtraRec  font_extra;        /* font info extra fields */\r\n    PS_PrivateRec    private_dict;      /* private dictionary     */\r\n    FT_String*       font_name;         /* top-level dictionary   */\r\n\r\n    T1_EncodingType  encoding_type;\r\n    T1_EncodingRec   encoding;\r\n\r\n    FT_Byte*         subrs_block;\r\n    FT_Byte*         charstrings_block;\r\n    FT_Byte*         glyph_names_block;\r\n\r\n    FT_Int           num_subrs;\r\n    FT_Byte**        subrs;\r\n    FT_PtrDist*      subrs_len;\r\n\r\n    FT_Int           num_glyphs;\r\n    FT_String**      glyph_names;       /* array of glyph names       */\r\n    FT_Byte**        charstrings;       /* array of glyph charstrings */\r\n    FT_PtrDist*      charstrings_len;\r\n\r\n    FT_Byte          paint_type;\r\n    FT_Byte          font_type;\r\n    FT_Matrix        font_matrix;\r\n    FT_Vector        font_offset;\r\n    FT_BBox          font_bbox;\r\n    FT_Long          font_id;\r\n\r\n    FT_Fixed         stroke_width;\r\n\r\n  } T1_FontRec, *T1_Font;\r\n\r\n\r\n  typedef struct  CID_SubrsRec_\r\n  {\r\n    FT_UInt    num_subrs;\r\n    FT_Byte**  code;\r\n\r\n  } CID_SubrsRec, *CID_Subrs;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /***                                                                   ***/\r\n  /***                                                                   ***/\r\n  /***                AFM FONT INFORMATION STRUCTURES                    ***/\r\n  /***                                                                   ***/\r\n  /***                                                                   ***/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n  typedef struct  AFM_TrackKernRec_\r\n  {\r\n    FT_Int    degree;\r\n    FT_Fixed  min_ptsize;\r\n    FT_Fixed  min_kern;\r\n    FT_Fixed  max_ptsize;\r\n    FT_Fixed  max_kern;\r\n\r\n  } AFM_TrackKernRec, *AFM_TrackKern;\r\n\r\n  typedef struct  AFM_KernPairRec_\r\n  {\r\n    FT_Int  index1;\r\n    FT_Int  index2;\r\n    FT_Int  x;\r\n    FT_Int  y;\r\n\r\n  } AFM_KernPairRec, *AFM_KernPair;\r\n\r\n  typedef struct  AFM_FontInfoRec_\r\n  {\r\n    FT_Bool        IsCIDFont;\r\n    FT_BBox        FontBBox;\r\n    FT_Fixed       Ascender;\r\n    FT_Fixed       Descender;\r\n    AFM_TrackKern  TrackKerns;   /* free if non-NULL */\r\n    FT_Int         NumTrackKern;\r\n    AFM_KernPair   KernPairs;    /* free if non-NULL */\r\n    FT_Int         NumKernPair;\r\n\r\n  } AFM_FontInfoRec, *AFM_FontInfo;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /***                                                                   ***/\r\n  /***                                                                   ***/\r\n  /***                ORIGINAL T1_FACE CLASS DEFINITION                  ***/\r\n  /***                                                                   ***/\r\n  /***                                                                   ***/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  typedef struct T1_FaceRec_*   T1_Face;\r\n  typedef struct CID_FaceRec_*  CID_Face;\r\n\r\n\r\n  typedef struct  T1_FaceRec_\r\n  {\r\n    FT_FaceRec      root;\r\n    T1_FontRec      type1;\r\n    const void*     psnames;\r\n    const void*     psaux;\r\n    const void*     afm_data;\r\n    FT_CharMapRec   charmaprecs[2];\r\n    FT_CharMap      charmaps[2];\r\n\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n    PS_Unicodes     unicode_map;\r\n#endif\r\n\r\n    /* support for Multiple Masters fonts */\r\n    PS_Blend        blend;\r\n\r\n    /* undocumented, optional: indices of subroutines that express      */\r\n    /* the NormalizeDesignVector and the ConvertDesignVector procedure, */\r\n    /* respectively, as Type 2 charstrings; -1 if keywords not present  */\r\n    FT_Int           ndv_idx;\r\n    FT_Int           cdv_idx;\r\n\r\n    /* undocumented, optional: has the same meaning as len_buildchar */\r\n    /* for Type 2 fonts; manipulated by othersubrs 19, 24, and 25    */\r\n    FT_UInt          len_buildchar;\r\n    FT_Long*         buildchar;\r\n\r\n    /* since version 2.1 - interface to PostScript hinter */\r\n    const void*     pshinter;\r\n\r\n  } T1_FaceRec;\r\n\r\n\r\n  typedef struct  CID_FaceRec_\r\n  {\r\n    FT_FaceRec       root;\r\n    void*            psnames;\r\n    void*            psaux;\r\n    CID_FaceInfoRec  cid;\r\n    PS_FontExtraRec  font_extra;\r\n#if 0\r\n    void*            afm_data;\r\n#endif\r\n    CID_Subrs        subrs;\r\n\r\n    /* since version 2.1 - interface to PostScript hinter */\r\n    void*            pshinter;\r\n\r\n    /* since version 2.1.8, but was originally positioned after `afm_data' */\r\n    FT_Byte*         binary_data; /* used if hex data has been converted */\r\n    FT_Stream        cid_stream;\r\n\r\n  } CID_FaceRec;\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __T1TYPES_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/internal/tttypes.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  tttypes.h                                                              */\r\n/*                                                                         */\r\n/*    Basic SFNT/TrueType type definitions and interface (specification    */\r\n/*    only).                                                               */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2002, 2004, 2005, 2006, 2007, 2008 by             */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __TTTYPES_H__\r\n#define __TTTYPES_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_TRUETYPE_TABLES_H\r\n#include FT_INTERNAL_OBJECTS_H\r\n\r\n#ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT\r\n#include FT_MULTIPLE_MASTERS_H\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /***                                                                   ***/\r\n  /***                                                                   ***/\r\n  /***             REQUIRED TRUETYPE/OPENTYPE TABLES DEFINITIONS         ***/\r\n  /***                                                                   ***/\r\n  /***                                                                   ***/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TTC_HeaderRec                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    TrueType collection header.  This table contains the offsets of    */\r\n  /*    the font headers of each distinct TrueType face in the file.       */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    tag     :: Must be `ttc ' to indicate a TrueType collection.       */\r\n  /*                                                                       */\r\n  /*    version :: The version number.                                     */\r\n  /*                                                                       */\r\n  /*    count   :: The number of faces in the collection.  The             */\r\n  /*               specification says this should be an unsigned long, but */\r\n  /*               we use a signed long since we need the value -1 for     */\r\n  /*               specific purposes.                                      */\r\n  /*                                                                       */\r\n  /*    offsets :: The offsets of the font headers, one per face.          */\r\n  /*                                                                       */\r\n  typedef struct  TTC_HeaderRec_\r\n  {\r\n    FT_ULong   tag;\r\n    FT_Fixed   version;\r\n    FT_Long    count;\r\n    FT_ULong*  offsets;\r\n\r\n  } TTC_HeaderRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    SFNT_HeaderRec                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    SFNT file format header.                                           */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    format_tag     :: The font format tag.                             */\r\n  /*                                                                       */\r\n  /*    num_tables     :: The number of tables in file.                    */\r\n  /*                                                                       */\r\n  /*    search_range   :: Must be `16 * (max power of 2 <= num_tables)'.   */\r\n  /*                                                                       */\r\n  /*    entry_selector :: Must be log2 of `search_range / 16'.             */\r\n  /*                                                                       */\r\n  /*    range_shift    :: Must be `num_tables * 16 - search_range'.        */\r\n  /*                                                                       */\r\n  typedef struct  SFNT_HeaderRec_\r\n  {\r\n    FT_ULong   format_tag;\r\n    FT_UShort  num_tables;\r\n    FT_UShort  search_range;\r\n    FT_UShort  entry_selector;\r\n    FT_UShort  range_shift;\r\n\r\n    FT_ULong   offset;  /* not in file */\r\n\r\n  } SFNT_HeaderRec, *SFNT_Header;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_TableRec                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This structure describes a given table of a TrueType font.         */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    Tag      :: A four-bytes tag describing the table.                 */\r\n  /*                                                                       */\r\n  /*    CheckSum :: The table checksum.  This value can be ignored.        */\r\n  /*                                                                       */\r\n  /*    Offset   :: The offset of the table from the start of the TrueType */\r\n  /*                font in its resource.                                  */\r\n  /*                                                                       */\r\n  /*    Length   :: The table length (in bytes).                           */\r\n  /*                                                                       */\r\n  typedef struct  TT_TableRec_\r\n  {\r\n    FT_ULong  Tag;        /*        table type */\r\n    FT_ULong  CheckSum;   /*    table checksum */\r\n    FT_ULong  Offset;     /* table file offset */\r\n    FT_ULong  Length;     /*      table length */\r\n\r\n  } TT_TableRec, *TT_Table;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_LongMetricsRec                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure modeling the long metrics of the `hmtx' and `vmtx'     */\r\n  /*    TrueType tables.  The values are expressed in font units.          */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    advance :: The advance width or height for the glyph.              */\r\n  /*                                                                       */\r\n  /*    bearing :: The left-side or top-side bearing for the glyph.        */\r\n  /*                                                                       */\r\n  typedef struct  TT_LongMetricsRec_\r\n  {\r\n    FT_UShort  advance;\r\n    FT_Short   bearing;\r\n\r\n  } TT_LongMetricsRec, *TT_LongMetrics;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    TT_ShortMetrics                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A simple type to model the short metrics of the `hmtx' and `vmtx'  */\r\n  /*    tables.                                                            */\r\n  /*                                                                       */\r\n  typedef FT_Short  TT_ShortMetrics;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_NameEntryRec                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure modeling TrueType name records.  Name records are used */\r\n  /*    to store important strings like family name, style name,           */\r\n  /*    copyright, etc. in _localized_ versions (i.e., language, encoding, */\r\n  /*    etc).                                                              */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    platformID   :: The ID of the name's encoding platform.            */\r\n  /*                                                                       */\r\n  /*    encodingID   :: The platform-specific ID for the name's encoding.  */\r\n  /*                                                                       */\r\n  /*    languageID   :: The platform-specific ID for the name's language.  */\r\n  /*                                                                       */\r\n  /*    nameID       :: The ID specifying what kind of name this is.       */\r\n  /*                                                                       */\r\n  /*    stringLength :: The length of the string in bytes.                 */\r\n  /*                                                                       */\r\n  /*    stringOffset :: The offset to the string in the `name' table.      */\r\n  /*                                                                       */\r\n  /*    string       :: A pointer to the string's bytes.  Note that these  */\r\n  /*                    are usually UTF-16 encoded characters.             */\r\n  /*                                                                       */\r\n  typedef struct  TT_NameEntryRec_\r\n  {\r\n    FT_UShort  platformID;\r\n    FT_UShort  encodingID;\r\n    FT_UShort  languageID;\r\n    FT_UShort  nameID;\r\n    FT_UShort  stringLength;\r\n    FT_ULong   stringOffset;\r\n\r\n    /* this last field is not defined in the spec */\r\n    /* but used by the FreeType engine            */\r\n\r\n    FT_Byte*   string;\r\n\r\n  } TT_NameEntryRec, *TT_NameEntry;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_NameTableRec                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure modeling the TrueType name table.                      */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    format         :: The format of the name table.                    */\r\n  /*                                                                       */\r\n  /*    numNameRecords :: The number of names in table.                    */\r\n  /*                                                                       */\r\n  /*    storageOffset  :: The offset of the name table in the `name'       */\r\n  /*                      TrueType table.                                  */\r\n  /*                                                                       */\r\n  /*    names          :: An array of name records.                        */\r\n  /*                                                                       */\r\n  /*    stream         :: the file's input stream.                         */\r\n  /*                                                                       */\r\n  typedef struct  TT_NameTableRec_\r\n  {\r\n    FT_UShort         format;\r\n    FT_UInt           numNameRecords;\r\n    FT_UInt           storageOffset;\r\n    TT_NameEntryRec*  names;\r\n    FT_Stream         stream;\r\n\r\n  } TT_NameTableRec, *TT_NameTable;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /***                                                                   ***/\r\n  /***                                                                   ***/\r\n  /***             OPTIONAL TRUETYPE/OPENTYPE TABLES DEFINITIONS         ***/\r\n  /***                                                                   ***/\r\n  /***                                                                   ***/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_GaspRangeRec                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A tiny structure used to model a gasp range according to the       */\r\n  /*    TrueType specification.                                            */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    maxPPEM  :: The maximum ppem value to which `gaspFlag' applies.    */\r\n  /*                                                                       */\r\n  /*    gaspFlag :: A flag describing the grid-fitting and anti-aliasing   */\r\n  /*                modes to be used.                                      */\r\n  /*                                                                       */\r\n  typedef struct  TT_GaspRangeRec_\r\n  {\r\n    FT_UShort  maxPPEM;\r\n    FT_UShort  gaspFlag;\r\n\r\n  } TT_GaspRangeRec, *TT_GaspRange;\r\n\r\n\r\n#define TT_GASP_GRIDFIT  0x01\r\n#define TT_GASP_DOGRAY   0x02\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_GaspRec                                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure modeling the TrueType `gasp' table used to specify     */\r\n  /*    grid-fitting and anti-aliasing behaviour.                          */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    version    :: The version number.                                  */\r\n  /*                                                                       */\r\n  /*    numRanges  :: The number of gasp ranges in table.                  */\r\n  /*                                                                       */\r\n  /*    gaspRanges :: An array of gasp ranges.                             */\r\n  /*                                                                       */\r\n  typedef struct  TT_Gasp_\r\n  {\r\n    FT_UShort     version;\r\n    FT_UShort     numRanges;\r\n    TT_GaspRange  gaspRanges;\r\n\r\n  } TT_GaspRec;\r\n\r\n\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_HdmxEntryRec                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A small structure used to model the pre-computed widths of a given */\r\n  /*    size.  They are found in the `hdmx' table.                         */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    ppem      :: The pixels per EM value at which these metrics apply. */\r\n  /*                                                                       */\r\n  /*    max_width :: The maximum advance width for this metric.            */\r\n  /*                                                                       */\r\n  /*    widths    :: An array of widths.  Note: These are 8-bit bytes.     */\r\n  /*                                                                       */\r\n  typedef struct  TT_HdmxEntryRec_\r\n  {\r\n    FT_Byte   ppem;\r\n    FT_Byte   max_width;\r\n    FT_Byte*  widths;\r\n\r\n  } TT_HdmxEntryRec, *TT_HdmxEntry;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_HdmxRec                                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to model the `hdmx' table, which contains         */\r\n  /*    pre-computed widths for a set of given sizes/dimensions.           */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    version     :: The version number.                                 */\r\n  /*                                                                       */\r\n  /*    num_records :: The number of hdmx records.                         */\r\n  /*                                                                       */\r\n  /*    records     :: An array of hdmx records.                           */\r\n  /*                                                                       */\r\n  typedef struct  TT_HdmxRec_\r\n  {\r\n    FT_UShort     version;\r\n    FT_Short      num_records;\r\n    TT_HdmxEntry  records;\r\n\r\n  } TT_HdmxRec, *TT_Hdmx;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_Kern0_PairRec                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to model a kerning pair for the kerning table     */\r\n  /*    format 0.  The engine now loads this table if it finds one in the  */\r\n  /*    font file.                                                         */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    left  :: The index of the left glyph in pair.                      */\r\n  /*                                                                       */\r\n  /*    right :: The index of the right glyph in pair.                     */\r\n  /*                                                                       */\r\n  /*    value :: The kerning distance.  A positive value spaces the        */\r\n  /*             glyphs, a negative one makes them closer.                 */\r\n  /*                                                                       */\r\n  typedef struct  TT_Kern0_PairRec_\r\n  {\r\n    FT_UShort  left;   /* index of left  glyph in pair */\r\n    FT_UShort  right;  /* index of right glyph in pair */\r\n    FT_FWord   value;  /* kerning value                */\r\n\r\n  } TT_Kern0_PairRec, *TT_Kern0_Pair;\r\n\r\n#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /***                                                                   ***/\r\n  /***                                                                   ***/\r\n  /***                    EMBEDDED BITMAPS SUPPORT                       ***/\r\n  /***                                                                   ***/\r\n  /***                                                                   ***/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_SBit_MetricsRec                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to hold the big metrics of a given glyph bitmap   */\r\n  /*    in a TrueType or OpenType font.  These are usually found in the    */\r\n  /*    `EBDT' (Microsoft) or `bloc' (Apple) table.                        */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    height       :: The glyph height in pixels.                        */\r\n  /*                                                                       */\r\n  /*    width        :: The glyph width in pixels.                         */\r\n  /*                                                                       */\r\n  /*    horiBearingX :: The horizontal left bearing.                       */\r\n  /*                                                                       */\r\n  /*    horiBearingY :: The horizontal top bearing.                        */\r\n  /*                                                                       */\r\n  /*    horiAdvance  :: The horizontal advance.                            */\r\n  /*                                                                       */\r\n  /*    vertBearingX :: The vertical left bearing.                         */\r\n  /*                                                                       */\r\n  /*    vertBearingY :: The vertical top bearing.                          */\r\n  /*                                                                       */\r\n  /*    vertAdvance  :: The vertical advance.                              */\r\n  /*                                                                       */\r\n  typedef struct  TT_SBit_MetricsRec_\r\n  {\r\n    FT_Byte  height;\r\n    FT_Byte  width;\r\n\r\n    FT_Char  horiBearingX;\r\n    FT_Char  horiBearingY;\r\n    FT_Byte  horiAdvance;\r\n\r\n    FT_Char  vertBearingX;\r\n    FT_Char  vertBearingY;\r\n    FT_Byte  vertAdvance;\r\n\r\n  } TT_SBit_MetricsRec, *TT_SBit_Metrics;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_SBit_SmallMetricsRec                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to hold the small metrics of a given glyph bitmap */\r\n  /*    in a TrueType or OpenType font.  These are usually found in the    */\r\n  /*    `EBDT' (Microsoft) or the `bdat' (Apple) table.                    */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    height   :: The glyph height in pixels.                            */\r\n  /*                                                                       */\r\n  /*    width    :: The glyph width in pixels.                             */\r\n  /*                                                                       */\r\n  /*    bearingX :: The left-side bearing.                                 */\r\n  /*                                                                       */\r\n  /*    bearingY :: The top-side bearing.                                  */\r\n  /*                                                                       */\r\n  /*    advance  :: The advance width or height.                           */\r\n  /*                                                                       */\r\n  typedef struct  TT_SBit_Small_Metrics_\r\n  {\r\n    FT_Byte  height;\r\n    FT_Byte  width;\r\n\r\n    FT_Char  bearingX;\r\n    FT_Char  bearingY;\r\n    FT_Byte  advance;\r\n\r\n  } TT_SBit_SmallMetricsRec, *TT_SBit_SmallMetrics;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_SBit_LineMetricsRec                                             */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to describe the text line metrics of a given      */\r\n  /*    bitmap strike, for either a horizontal or vertical layout.         */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    ascender                :: The ascender in pixels.                 */\r\n  /*                                                                       */\r\n  /*    descender               :: The descender in pixels.                */\r\n  /*                                                                       */\r\n  /*    max_width               :: The maximum glyph width in pixels.      */\r\n  /*                                                                       */\r\n  /*    caret_slope_enumerator  :: Rise of the caret slope, typically set  */\r\n  /*                               to 1 for non-italic fonts.              */\r\n  /*                                                                       */\r\n  /*    caret_slope_denominator :: Rise of the caret slope, typically set  */\r\n  /*                               to 0 for non-italic fonts.              */\r\n  /*                                                                       */\r\n  /*    caret_offset            :: Offset in pixels to move the caret for  */\r\n  /*                               proper positioning.                     */\r\n  /*                                                                       */\r\n  /*    min_origin_SB           :: Minimum of horiBearingX (resp.          */\r\n  /*                               vertBearingY).                          */\r\n  /*    min_advance_SB          :: Minimum of                              */\r\n  /*                                                                       */\r\n  /*                                 horizontal advance -                  */\r\n  /*                                   ( horiBearingX + width )            */\r\n  /*                                                                       */\r\n  /*                               resp.                                   */\r\n  /*                                                                       */\r\n  /*                                 vertical advance -                    */\r\n  /*                                   ( vertBearingY + height )           */\r\n  /*                                                                       */\r\n  /*    max_before_BL           :: Maximum of horiBearingY (resp.          */\r\n  /*                               vertBearingY).                          */\r\n  /*                                                                       */\r\n  /*    min_after_BL            :: Minimum of                              */\r\n  /*                                                                       */\r\n  /*                                 horiBearingY - height                 */\r\n  /*                                                                       */\r\n  /*                               resp.                                   */\r\n  /*                                                                       */\r\n  /*                                 vertBearingX - width                  */\r\n  /*                                                                       */\r\n  /*    pads                    :: Unused (to make the size of the record  */\r\n  /*                               a multiple of 32 bits.                  */\r\n  /*                                                                       */\r\n  typedef struct  TT_SBit_LineMetricsRec_\r\n  {\r\n    FT_Char  ascender;\r\n    FT_Char  descender;\r\n    FT_Byte  max_width;\r\n    FT_Char  caret_slope_numerator;\r\n    FT_Char  caret_slope_denominator;\r\n    FT_Char  caret_offset;\r\n    FT_Char  min_origin_SB;\r\n    FT_Char  min_advance_SB;\r\n    FT_Char  max_before_BL;\r\n    FT_Char  min_after_BL;\r\n    FT_Char  pads[2];\r\n\r\n  } TT_SBit_LineMetricsRec, *TT_SBit_LineMetrics;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_SBit_RangeRec                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A TrueType/OpenType subIndexTable as defined in the `EBLC'         */\r\n  /*    (Microsoft) or `bloc' (Apple) tables.                              */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    first_glyph   :: The first glyph index in the range.               */\r\n  /*                                                                       */\r\n  /*    last_glyph    :: The last glyph index in the range.                */\r\n  /*                                                                       */\r\n  /*    index_format  :: The format of index table.  Valid values are 1    */\r\n  /*                     to 5.                                             */\r\n  /*                                                                       */\r\n  /*    image_format  :: The format of `EBDT' image data.                  */\r\n  /*                                                                       */\r\n  /*    image_offset  :: The offset to image data in `EBDT'.               */\r\n  /*                                                                       */\r\n  /*    image_size    :: For index formats 2 and 5.  This is the size in   */\r\n  /*                     bytes of each glyph bitmap.                       */\r\n  /*                                                                       */\r\n  /*    big_metrics   :: For index formats 2 and 5.  This is the big       */\r\n  /*                     metrics for each glyph bitmap.                    */\r\n  /*                                                                       */\r\n  /*    num_glyphs    :: For index formats 4 and 5.  This is the number of */\r\n  /*                     glyphs in the code array.                         */\r\n  /*                                                                       */\r\n  /*    glyph_offsets :: For index formats 1 and 3.                        */\r\n  /*                                                                       */\r\n  /*    glyph_codes   :: For index formats 4 and 5.                        */\r\n  /*                                                                       */\r\n  /*    table_offset  :: The offset of the index table in the `EBLC'       */\r\n  /*                     table.  Only used during strike loading.          */\r\n  /*                                                                       */\r\n  typedef struct  TT_SBit_RangeRec_\r\n  {\r\n    FT_UShort           first_glyph;\r\n    FT_UShort           last_glyph;\r\n\r\n    FT_UShort           index_format;\r\n    FT_UShort           image_format;\r\n    FT_ULong            image_offset;\r\n\r\n    FT_ULong            image_size;\r\n    TT_SBit_MetricsRec  metrics;\r\n    FT_ULong            num_glyphs;\r\n\r\n    FT_ULong*           glyph_offsets;\r\n    FT_UShort*          glyph_codes;\r\n\r\n    FT_ULong            table_offset;\r\n\r\n  } TT_SBit_RangeRec, *TT_SBit_Range;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_SBit_StrikeRec                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used describe a given bitmap strike in the `EBLC'      */\r\n  /*    (Microsoft) or `bloc' (Apple) tables.                              */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*   num_index_ranges :: The number of index ranges.                     */\r\n  /*                                                                       */\r\n  /*   index_ranges     :: An array of glyph index ranges.                 */\r\n  /*                                                                       */\r\n  /*   color_ref        :: Unused.  `color_ref' is put in for future       */\r\n  /*                       enhancements, but these fields are already      */\r\n  /*                       in use by other platforms (e.g. Newton).        */\r\n  /*                       For details, please see                         */\r\n  /*                                                                       */\r\n  /*                         http://fonts.apple.com/                       */\r\n  /*                                TTRefMan/RM06/Chap6bloc.html           */\r\n  /*                                                                       */\r\n  /*   hori             :: The line metrics for horizontal layouts.        */\r\n  /*                                                                       */\r\n  /*   vert             :: The line metrics for vertical layouts.          */\r\n  /*                                                                       */\r\n  /*   start_glyph      :: The lowest glyph index for this strike.         */\r\n  /*                                                                       */\r\n  /*   end_glyph        :: The highest glyph index for this strike.        */\r\n  /*                                                                       */\r\n  /*   x_ppem           :: The number of horizontal pixels per EM.         */\r\n  /*                                                                       */\r\n  /*   y_ppem           :: The number of vertical pixels per EM.           */\r\n  /*                                                                       */\r\n  /*   bit_depth        :: The bit depth.  Valid values are 1, 2, 4,       */\r\n  /*                       and 8.                                          */\r\n  /*                                                                       */\r\n  /*   flags            :: Is this a vertical or horizontal strike?  For   */\r\n  /*                       details, please see                             */\r\n  /*                                                                       */\r\n  /*                         http://fonts.apple.com/                       */\r\n  /*                                TTRefMan/RM06/Chap6bloc.html           */\r\n  /*                                                                       */\r\n  typedef struct  TT_SBit_StrikeRec_\r\n  {\r\n    FT_Int                  num_ranges;\r\n    TT_SBit_Range           sbit_ranges;\r\n    FT_ULong                ranges_offset;\r\n\r\n    FT_ULong                color_ref;\r\n\r\n    TT_SBit_LineMetricsRec  hori;\r\n    TT_SBit_LineMetricsRec  vert;\r\n\r\n    FT_UShort               start_glyph;\r\n    FT_UShort               end_glyph;\r\n\r\n    FT_Byte                 x_ppem;\r\n    FT_Byte                 y_ppem;\r\n\r\n    FT_Byte                 bit_depth;\r\n    FT_Char                 flags;\r\n\r\n  } TT_SBit_StrikeRec, *TT_SBit_Strike;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_SBit_ComponentRec                                               */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A simple structure to describe a compound sbit element.            */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    glyph_code :: The element's glyph index.                           */\r\n  /*                                                                       */\r\n  /*    x_offset   :: The element's left bearing.                          */\r\n  /*                                                                       */\r\n  /*    y_offset   :: The element's top bearing.                           */\r\n  /*                                                                       */\r\n  typedef struct  TT_SBit_ComponentRec_\r\n  {\r\n    FT_UShort  glyph_code;\r\n    FT_Char    x_offset;\r\n    FT_Char    y_offset;\r\n\r\n  } TT_SBit_ComponentRec, *TT_SBit_Component;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_SBit_ScaleRec                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used describe a given bitmap scaling table, as defined */\r\n  /*    in the `EBSC' table.                                               */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    hori              :: The horizontal line metrics.                  */\r\n  /*                                                                       */\r\n  /*    vert              :: The vertical line metrics.                    */\r\n  /*                                                                       */\r\n  /*    x_ppem            :: The number of horizontal pixels per EM.       */\r\n  /*                                                                       */\r\n  /*    y_ppem            :: The number of vertical pixels per EM.         */\r\n  /*                                                                       */\r\n  /*    x_ppem_substitute :: Substitution x_ppem value.                    */\r\n  /*                                                                       */\r\n  /*    y_ppem_substitute :: Substitution y_ppem value.                    */\r\n  /*                                                                       */\r\n  typedef struct  TT_SBit_ScaleRec_\r\n  {\r\n    TT_SBit_LineMetricsRec  hori;\r\n    TT_SBit_LineMetricsRec  vert;\r\n\r\n    FT_Byte                 x_ppem;\r\n    FT_Byte                 y_ppem;\r\n\r\n    FT_Byte                 x_ppem_substitute;\r\n    FT_Byte                 y_ppem_substitute;\r\n\r\n  } TT_SBit_ScaleRec, *TT_SBit_Scale;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /***                                                                   ***/\r\n  /***                                                                   ***/\r\n  /***                  POSTSCRIPT GLYPH NAMES SUPPORT                   ***/\r\n  /***                                                                   ***/\r\n  /***                                                                   ***/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_Post_20Rec                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Postscript names sub-table, format 2.0.  Stores the PS name of     */\r\n  /*    each glyph in the font face.                                       */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    num_glyphs    :: The number of named glyphs in the table.          */\r\n  /*                                                                       */\r\n  /*    num_names     :: The number of PS names stored in the table.       */\r\n  /*                                                                       */\r\n  /*    glyph_indices :: The indices of the glyphs in the names arrays.    */\r\n  /*                                                                       */\r\n  /*    glyph_names   :: The PS names not in Mac Encoding.                 */\r\n  /*                                                                       */\r\n  typedef struct  TT_Post_20Rec_\r\n  {\r\n    FT_UShort   num_glyphs;\r\n    FT_UShort   num_names;\r\n    FT_UShort*  glyph_indices;\r\n    FT_Char**   glyph_names;\r\n\r\n  } TT_Post_20Rec, *TT_Post_20;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_Post_25Rec                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Postscript names sub-table, format 2.5.  Stores the PS name of     */\r\n  /*    each glyph in the font face.                                       */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    num_glyphs :: The number of glyphs in the table.                   */\r\n  /*                                                                       */\r\n  /*    offsets    :: An array of signed offsets in a normal Mac           */\r\n  /*                  Postscript name encoding.                            */\r\n  /*                                                                       */\r\n  typedef struct  TT_Post_25_\r\n  {\r\n    FT_UShort  num_glyphs;\r\n    FT_Char*   offsets;\r\n\r\n  } TT_Post_25Rec, *TT_Post_25;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_Post_NamesRec                                                   */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Postscript names table, either format 2.0 or 2.5.                  */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    loaded    :: A flag to indicate whether the PS names are loaded.   */\r\n  /*                                                                       */\r\n  /*    format_20 :: The sub-table used for format 2.0.                    */\r\n  /*                                                                       */\r\n  /*    format_25 :: The sub-table used for format 2.5.                    */\r\n  /*                                                                       */\r\n  typedef struct  TT_Post_NamesRec_\r\n  {\r\n    FT_Bool  loaded;\r\n\r\n    union\r\n    {\r\n      TT_Post_20Rec  format_20;\r\n      TT_Post_25Rec  format_25;\r\n\r\n    } names;\r\n\r\n  } TT_Post_NamesRec, *TT_Post_Names;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /***                                                                   ***/\r\n  /***                                                                   ***/\r\n  /***                    GX VARIATION TABLE SUPPORT                     ***/\r\n  /***                                                                   ***/\r\n  /***                                                                   ***/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n#ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT\r\n  typedef struct GX_BlendRec_  *GX_Blend;\r\n#endif\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /***                                                                   ***/\r\n  /***                                                                   ***/\r\n  /***              EMBEDDED BDF PROPERTIES TABLE SUPPORT                ***/\r\n  /***                                                                   ***/\r\n  /***                                                                   ***/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n  /*\r\n   * These types are used to support a `BDF ' table that isn't part of the\r\n   * official TrueType specification.  It is mainly used in SFNT-based\r\n   * bitmap fonts that were generated from a set of BDF fonts.\r\n   *\r\n   * The format of the table is as follows.\r\n   *\r\n   *   USHORT   version      `BDF ' table version number, should be 0x0001.\r\n   *   USHORT   strikeCount  Number of strikes (bitmap sizes) in this table.\r\n   *   ULONG    stringTable  Offset (from start of BDF table) to string\r\n   *                         table.\r\n   *\r\n   * This is followed by an array of `strikeCount' descriptors, having the\r\n   * following format.\r\n   *\r\n   *   USHORT   ppem         Vertical pixels per EM for this strike.\r\n   *   USHORT   numItems     Number of items for this strike (properties and\r\n   *                         atoms).  Maximum is 255.\r\n   *\r\n   * This array in turn is followed by `strikeCount' value sets.  Each\r\n   * `value set' is an array of `numItems' items with the following format.\r\n   *\r\n   *   ULONG    item_name    Offset in string table to item name.\r\n   *   USHORT   item_type    The item type.  Possible values are\r\n   *                            0 => string (e.g., COMMENT)\r\n   *                            1 => atom   (e.g., FONT or even SIZE)\r\n   *                            2 => int32\r\n   *                            3 => uint32\r\n   *                         0x10 => A flag to indicate a properties.  This\r\n   *                                 is ORed with the above values.\r\n   *   ULONG    item_value   For strings  => Offset into string table without\r\n   *                                         the corresponding double quotes.\r\n   *                         For atoms    => Offset into string table.\r\n   *                         For integers => Direct value.\r\n   *\r\n   * All strings in the string table consist of bytes and are\r\n   * zero-terminated.\r\n   *\r\n   */\r\n\r\n#ifdef TT_CONFIG_OPTION_BDF\r\n\r\n  typedef struct  TT_BDFRec_\r\n  {\r\n    FT_Byte*   table;\r\n    FT_Byte*   table_end;\r\n    FT_Byte*   strings;\r\n    FT_ULong   strings_size;\r\n    FT_UInt    num_strikes;\r\n    FT_Bool    loaded;\r\n\r\n  } TT_BDFRec, *TT_BDF;\r\n\r\n#endif /* TT_CONFIG_OPTION_BDF */\r\n\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /***                                                                   ***/\r\n  /***                                                                   ***/\r\n  /***                  ORIGINAL TT_FACE CLASS DEFINITION                ***/\r\n  /***                                                                   ***/\r\n  /***                                                                   ***/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* This structure/class is defined here because it is common to the      */\r\n  /* following formats: TTF, OpenType-TT, and OpenType-CFF.                */\r\n  /*                                                                       */\r\n  /* Note, however, that the classes TT_Size and TT_GlyphSlot are not      */\r\n  /* shared between font drivers, and are thus defined in `ttobjs.h'.      */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Type>                                                                */\r\n  /*    TT_Face                                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle to a TrueType face/font object.  A TT_Face encapsulates   */\r\n  /*    the resolution and scaling independent parts of a TrueType font    */\r\n  /*    resource.                                                          */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The TT_Face structure is also used as a `parent class' for the     */\r\n  /*    OpenType-CFF class (T2_Face).                                      */\r\n  /*                                                                       */\r\n  typedef struct TT_FaceRec_*  TT_Face;\r\n\r\n\r\n  /* a function type used for the truetype bytecode interpreter hooks */\r\n  typedef FT_Error\r\n  (*TT_Interpreter)( void*  exec_context );\r\n\r\n  /* forward declaration */\r\n  typedef struct TT_LoaderRec_*  TT_Loader;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_Loader_GotoTableFunc                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Seeks a stream to the start of a given TrueType table.             */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face   :: A handle to the target face object.                      */\r\n  /*                                                                       */\r\n  /*    tag    :: A 4-byte tag used to name the table.                     */\r\n  /*                                                                       */\r\n  /*    stream :: The input stream.                                        */\r\n  /*                                                                       */\r\n  /* <Output>                                                              */\r\n  /*    length :: The length of the table in bytes.  Set to 0 if not       */\r\n  /*              needed.                                                  */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0 means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The stream cursor must be at the font file's origin.               */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*TT_Loader_GotoTableFunc)( TT_Face    face,\r\n                              FT_ULong   tag,\r\n                              FT_Stream  stream,\r\n                              FT_ULong*  length );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_Loader_StartGlyphFunc                                           */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Seeks a stream to the start of a given glyph element, and opens a  */\r\n  /*    frame for it.                                                      */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    loader      :: The current TrueType glyph loader object.           */\r\n  /*                                                                       */\r\n  /*    glyph index :: The index of the glyph to access.                   */\r\n  /*                                                                       */\r\n  /*    offset      :: The offset of the glyph according to the            */\r\n  /*                   `locations' table.                                  */\r\n  /*                                                                       */\r\n  /*    byte_count  :: The size of the frame in bytes.                     */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0 means success.                             */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    This function is normally equivalent to FT_STREAM_SEEK(offset)     */\r\n  /*    followed by FT_FRAME_ENTER(byte_count) with the loader's stream,   */\r\n  /*    but alternative formats (e.g. compressed ones) might use something */\r\n  /*    different.                                                         */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*TT_Loader_StartGlyphFunc)( TT_Loader  loader,\r\n                               FT_UInt    glyph_index,\r\n                               FT_ULong   offset,\r\n                               FT_UInt    byte_count );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_Loader_ReadGlyphFunc                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Reads one glyph element (its header, a simple glyph, or a          */\r\n  /*    composite) from the loader's current stream frame.                 */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    loader :: The current TrueType glyph loader object.                */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    FreeType error code.  0 means success.                             */\r\n  /*                                                                       */\r\n  typedef FT_Error\r\n  (*TT_Loader_ReadGlyphFunc)( TT_Loader  loader );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <FuncType>                                                            */\r\n  /*    TT_Loader_EndGlyphFunc                                             */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Closes the current loader stream frame for the glyph.              */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    loader :: The current TrueType glyph loader object.                */\r\n  /*                                                                       */\r\n  typedef void\r\n  (*TT_Loader_EndGlyphFunc)( TT_Loader  loader );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /*                         TrueType Face Type                            */\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_Face                                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    The TrueType face class.  These objects model the resolution and   */\r\n  /*    point-size independent data found in a TrueType font file.         */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    root                 :: The base FT_Face structure, managed by the */\r\n  /*                            base layer.                                */\r\n  /*                                                                       */\r\n  /*    ttc_header           :: The TrueType collection header, used when  */\r\n  /*                            the file is a `ttc' rather than a `ttf'.   */\r\n  /*                            For ordinary font files, the field         */\r\n  /*                            `ttc_header.count' is set to 0.            */\r\n  /*                                                                       */\r\n  /*    format_tag           :: The font format tag.                       */\r\n  /*                                                                       */\r\n  /*    num_tables           :: The number of TrueType tables in this font */\r\n  /*                            file.                                      */\r\n  /*                                                                       */\r\n  /*    dir_tables           :: The directory of TrueType tables for this  */\r\n  /*                            font file.                                 */\r\n  /*                                                                       */\r\n  /*    header               :: The font's font header (`head' table).     */\r\n  /*                            Read on font opening.                      */\r\n  /*                                                                       */\r\n  /*    horizontal           :: The font's horizontal header (`hhea'       */\r\n  /*                            table).  This field also contains the      */\r\n  /*                            associated horizontal metrics table        */\r\n  /*                            (`hmtx').                                  */\r\n  /*                                                                       */\r\n  /*    max_profile          :: The font's maximum profile table.  Read on */\r\n  /*                            font opening.  Note that some maximum      */\r\n  /*                            values cannot be taken directly from this  */\r\n  /*                            table.  We thus define additional fields   */\r\n  /*                            below to hold the computed maxima.         */\r\n  /*                                                                       */\r\n  /*    vertical_info        :: A boolean which is set when the font file  */\r\n  /*                            contains vertical metrics.  If not, the    */\r\n  /*                            value of the `vertical' field is           */\r\n  /*                            undefined.                                 */\r\n  /*                                                                       */\r\n  /*    vertical             :: The font's vertical header (`vhea' table). */\r\n  /*                            This field also contains the associated    */\r\n  /*                            vertical metrics table (`vmtx'), if found. */\r\n  /*                            IMPORTANT: The contents of this field is   */\r\n  /*                            undefined if the `verticalInfo' field is   */\r\n  /*                            unset.                                     */\r\n  /*                                                                       */\r\n  /*    num_names            :: The number of name records within this     */\r\n  /*                            TrueType font.                             */\r\n  /*                                                                       */\r\n  /*    name_table           :: The table of name records (`name').        */\r\n  /*                                                                       */\r\n  /*    os2                  :: The font's OS/2 table (`OS/2').            */\r\n  /*                                                                       */\r\n  /*    postscript           :: The font's PostScript table (`post'        */\r\n  /*                            table).  The PostScript glyph names are    */\r\n  /*                            not loaded by the driver on face opening.  */\r\n  /*                            See the `ttpost' module for more details.  */\r\n  /*                                                                       */\r\n  /*    cmap_table           :: Address of the face's `cmap' SFNT table    */\r\n  /*                            in memory (it's an extracted frame).       */\r\n  /*                                                                       */\r\n  /*    cmap_size            :: The size in bytes of the `cmap_table'      */\r\n  /*                            described above.                           */\r\n  /*                                                                       */\r\n  /*    goto_table           :: A function called by each TrueType table   */\r\n  /*                            loader to position a stream's cursor to    */\r\n  /*                            the start of a given table according to    */\r\n  /*                            its tag.  It defaults to TT_Goto_Face but  */\r\n  /*                            can be different for strange formats (e.g. */\r\n  /*                            Type 42).                                  */\r\n  /*                                                                       */\r\n  /*    access_glyph_frame   :: A function used to access the frame of a   */\r\n  /*                            given glyph within the face's font file.   */\r\n  /*                                                                       */\r\n  /*    forget_glyph_frame   :: A function used to forget the frame of a   */\r\n  /*                            given glyph when all data has been loaded. */\r\n  /*                                                                       */\r\n  /*    read_glyph_header    :: A function used to read a glyph header.    */\r\n  /*                            It must be called between an `access' and  */\r\n  /*                            `forget'.                                  */\r\n  /*                                                                       */\r\n  /*    read_simple_glyph    :: A function used to read a simple glyph.    */\r\n  /*                            It must be called after the header was     */\r\n  /*                            read, and before the `forget'.             */\r\n  /*                                                                       */\r\n  /*    read_composite_glyph :: A function used to read a composite glyph. */\r\n  /*                            It must be called after the header was     */\r\n  /*                            read, and before the `forget'.             */\r\n  /*                                                                       */\r\n  /*    sfnt                 :: A pointer to the SFNT service.             */\r\n  /*                                                                       */\r\n  /*    psnames              :: A pointer to the PostScript names service. */\r\n  /*                                                                       */\r\n  /*    hdmx                 :: The face's horizontal device metrics       */\r\n  /*                            (`hdmx' table).  This table is optional in */\r\n  /*                            TrueType/OpenType fonts.                   */\r\n  /*                                                                       */\r\n  /*    gasp                 :: The grid-fitting and scaling properties    */\r\n  /*                            table (`gasp').  This table is optional in */\r\n  /*                            TrueType/OpenType fonts.                   */\r\n  /*                                                                       */\r\n  /*    pclt                 :: The `pclt' SFNT table.                     */\r\n  /*                                                                       */\r\n  /*    num_sbit_strikes     :: The number of sbit strikes, i.e., bitmap   */\r\n  /*                            sizes, embedded in this font.              */\r\n  /*                                                                       */\r\n  /*    sbit_strikes         :: An array of sbit strikes embedded in this  */\r\n  /*                            font.  This table is optional in a         */\r\n  /*                            TrueType/OpenType font.                    */\r\n  /*                                                                       */\r\n  /*    num_sbit_scales      :: The number of sbit scales for this font.   */\r\n  /*                                                                       */\r\n  /*    sbit_scales          :: Array of sbit scales embedded in this      */\r\n  /*                            font.  This table is optional in a         */\r\n  /*                            TrueType/OpenType font.                    */\r\n  /*                                                                       */\r\n  /*    postscript_names     :: A table used to store the Postscript names */\r\n  /*                            of  the glyphs for this font.  See the     */\r\n  /*                            file  `ttconfig.h' for comments on the     */\r\n  /*                            TT_CONFIG_OPTION_POSTSCRIPT_NAMES option.  */\r\n  /*                                                                       */\r\n  /*    num_locations        :: The number of glyph locations in this      */\r\n  /*                            TrueType file.  This should be             */\r\n  /*                            identical to the number of glyphs.         */\r\n  /*                            Ignored for Type 2 fonts.                  */\r\n  /*                                                                       */\r\n  /*    glyph_locations      :: An array of longs.  These are offsets to   */\r\n  /*                            glyph data within the `glyf' table.        */\r\n  /*                            Ignored for Type 2 font faces.             */\r\n  /*                                                                       */\r\n  /*    glyf_len             :: The length of the `glyf' table.  Needed    */\r\n  /*                            for malformed `loca' tables.               */\r\n  /*                                                                       */\r\n  /*    font_program_size    :: Size in bytecodes of the face's font       */\r\n  /*                            program.  0 if none defined.  Ignored for  */\r\n  /*                            Type 2 fonts.                              */\r\n  /*                                                                       */\r\n  /*    font_program         :: The face's font program (bytecode stream)  */\r\n  /*                            executed at load time, also used during    */\r\n  /*                            glyph rendering.  Comes from the `fpgm'    */\r\n  /*                            table.  Ignored for Type 2 font fonts.     */\r\n  /*                                                                       */\r\n  /*    cvt_program_size     :: The size in bytecodes of the face's cvt    */\r\n  /*                            program.  Ignored for Type 2 fonts.        */\r\n  /*                                                                       */\r\n  /*    cvt_program          :: The face's cvt program (bytecode stream)   */\r\n  /*                            executed each time an instance/size is     */\r\n  /*                            changed/reset.  Comes from the `prep'      */\r\n  /*                            table.  Ignored for Type 2 fonts.          */\r\n  /*                                                                       */\r\n  /*    cvt_size             :: Size of the control value table (in        */\r\n  /*                            entries).   Ignored for Type 2 fonts.      */\r\n  /*                                                                       */\r\n  /*    cvt                  :: The face's original control value table.   */\r\n  /*                            Coordinates are expressed in unscaled font */\r\n  /*                            units.  Comes from the `cvt ' table.       */\r\n  /*                            Ignored for Type 2 fonts.                  */\r\n  /*                                                                       */\r\n  /*    num_kern_pairs       :: The number of kerning pairs present in the */\r\n  /*                            font file.  The engine only loads the      */\r\n  /*                            first horizontal format 0 kern table it    */\r\n  /*                            finds in the font file.  Ignored for       */\r\n  /*                            Type 2 fonts.                              */\r\n  /*                                                                       */\r\n  /*    kern_table_index     :: The index of the kerning table in the font */\r\n  /*                            kerning directory.  Ignored for Type 2     */\r\n  /*                            fonts.                                     */\r\n  /*                                                                       */\r\n  /*    interpreter          :: A pointer to the TrueType bytecode         */\r\n  /*                            interpreters field is also used to hook    */\r\n  /*                            the debugger in `ttdebug'.                 */\r\n  /*                                                                       */\r\n  /*    unpatented_hinting   :: If true, use only unpatented methods in    */\r\n  /*                            the bytecode interpreter.                  */\r\n  /*                                                                       */\r\n  /*    doblend              :: A boolean which is set if the font should  */\r\n  /*                            be blended (this is for GX var).           */\r\n  /*                                                                       */\r\n  /*    blend                :: Contains the data needed to control GX     */\r\n  /*                            variation tables (rather like Multiple     */\r\n  /*                            Master data).                              */\r\n  /*                                                                       */\r\n  /*    extra                :: Reserved for third-party font drivers.     */\r\n  /*                                                                       */\r\n  /*    postscript_name      :: The PS name of the font.  Used by the      */\r\n  /*                            postscript name service.                   */\r\n  /*                                                                       */\r\n  typedef struct  TT_FaceRec_\r\n  {\r\n    FT_FaceRec            root;\r\n\r\n    TTC_HeaderRec         ttc_header;\r\n\r\n    FT_ULong              format_tag;\r\n    FT_UShort             num_tables;\r\n    TT_Table              dir_tables;\r\n\r\n    TT_Header             header;       /* TrueType header table          */\r\n    TT_HoriHeader         horizontal;   /* TrueType horizontal header     */\r\n\r\n    TT_MaxProfile         max_profile;\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n    FT_ULong              max_components;  /* stubbed to 0 */\r\n#endif\r\n\r\n    FT_Bool               vertical_info;\r\n    TT_VertHeader         vertical;     /* TT Vertical header, if present */\r\n\r\n    FT_UShort             num_names;    /* number of name records  */\r\n    TT_NameTableRec       name_table;   /* name table              */\r\n\r\n    TT_OS2                os2;          /* TrueType OS/2 table            */\r\n    TT_Postscript         postscript;   /* TrueType Postscript table      */\r\n\r\n    FT_Byte*              cmap_table;   /* extracted `cmap' table */\r\n    FT_ULong              cmap_size;\r\n\r\n    TT_Loader_GotoTableFunc   goto_table;\r\n\r\n    TT_Loader_StartGlyphFunc  access_glyph_frame;\r\n    TT_Loader_EndGlyphFunc    forget_glyph_frame;\r\n    TT_Loader_ReadGlyphFunc   read_glyph_header;\r\n    TT_Loader_ReadGlyphFunc   read_simple_glyph;\r\n    TT_Loader_ReadGlyphFunc   read_composite_glyph;\r\n\r\n    /* a typeless pointer to the SFNT_Interface table used to load */\r\n    /* the basic TrueType tables in the face object                */\r\n    void*                 sfnt;\r\n\r\n    /* a typeless pointer to the FT_Service_PsCMapsRec table used to */\r\n    /* handle glyph names <-> unicode & Mac values                   */\r\n    void*                 psnames;\r\n\r\n\r\n    /***********************************************************************/\r\n    /*                                                                     */\r\n    /* Optional TrueType/OpenType tables                                   */\r\n    /*                                                                     */\r\n    /***********************************************************************/\r\n\r\n    /* horizontal device metrics */\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n    TT_HdmxRec            hdmx;\r\n#endif\r\n\r\n    /* grid-fitting and scaling table */\r\n    TT_GaspRec            gasp;                 /* the `gasp' table */\r\n\r\n    /* PCL 5 table */\r\n    TT_PCLT               pclt;\r\n\r\n    /* embedded bitmaps support */\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n    FT_ULong              num_sbit_strikes;\r\n    TT_SBit_Strike        sbit_strikes;\r\n#endif\r\n\r\n    FT_ULong              num_sbit_scales;\r\n    TT_SBit_Scale         sbit_scales;\r\n\r\n    /* postscript names table */\r\n    TT_Post_NamesRec      postscript_names;\r\n\r\n\r\n    /***********************************************************************/\r\n    /*                                                                     */\r\n    /* TrueType-specific fields (ignored by the OTF-Type2 driver)          */\r\n    /*                                                                     */\r\n    /***********************************************************************/\r\n\r\n    /* the glyph locations */\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n    FT_UShort             num_locations_stub;\r\n    FT_Long*              glyph_locations_stub;\r\n#endif\r\n\r\n    /* the font program, if any */\r\n    FT_ULong              font_program_size;\r\n    FT_Byte*              font_program;\r\n\r\n    /* the cvt program, if any */\r\n    FT_ULong              cvt_program_size;\r\n    FT_Byte*              cvt_program;\r\n\r\n    /* the original, unscaled, control value table */\r\n    FT_ULong              cvt_size;\r\n    FT_Short*             cvt;\r\n\r\n#ifdef FT_CONFIG_OPTION_OLD_INTERNALS\r\n    /* the format 0 kerning table, if any */\r\n    FT_Int                num_kern_pairs;\r\n    FT_Int                kern_table_index;\r\n    TT_Kern0_Pair         kern_pairs;\r\n#endif\r\n\r\n    /* A pointer to the bytecode interpreter to use.  This is also */\r\n    /* used to hook the debugger for the `ttdebug' utility.        */\r\n    TT_Interpreter        interpreter;\r\n\r\n#ifdef TT_CONFIG_OPTION_UNPATENTED_HINTING\r\n    /* Use unpatented hinting only. */\r\n    FT_Bool               unpatented_hinting;\r\n#endif\r\n\r\n    /***********************************************************************/\r\n    /*                                                                     */\r\n    /* Other tables or fields. This is used by derivative formats like     */\r\n    /* OpenType.                                                           */\r\n    /*                                                                     */\r\n    /***********************************************************************/\r\n\r\n    FT_Generic            extra;\r\n\r\n    const char*           postscript_name;\r\n\r\n    /* since version 2.1.8, but was originally placed after */\r\n    /* `glyph_locations_stub'                               */\r\n    FT_ULong              glyf_len;\r\n\r\n    /* since version 2.1.8, but was originally placed before `extra' */\r\n#ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT\r\n    FT_Bool               doblend;\r\n    GX_Blend              blend;\r\n#endif\r\n\r\n    /* since version 2.2 */\r\n\r\n    FT_Byte*              horz_metrics;\r\n    FT_ULong              horz_metrics_size;\r\n\r\n    FT_Byte*              vert_metrics;\r\n    FT_ULong              vert_metrics_size;\r\n\r\n    FT_ULong              num_locations; /* in broken TTF, gid > 0xFFFF */ \r\n    FT_Byte*              glyph_locations;\r\n\r\n    FT_Byte*              hdmx_table;\r\n    FT_ULong              hdmx_table_size;\r\n    FT_UInt               hdmx_record_count;\r\n    FT_ULong              hdmx_record_size;\r\n    FT_Byte*              hdmx_record_sizes;\r\n\r\n    FT_Byte*              sbit_table;\r\n    FT_ULong              sbit_table_size;\r\n    FT_UInt               sbit_num_strikes;\r\n\r\n    FT_Byte*              kern_table;\r\n    FT_ULong              kern_table_size;\r\n    FT_UInt               num_kern_tables;\r\n    FT_UInt32             kern_avail_bits;\r\n    FT_UInt32             kern_order_bits;\r\n\r\n#ifdef TT_CONFIG_OPTION_BDF\r\n    TT_BDFRec             bdf;\r\n#endif /* TT_CONFIG_OPTION_BDF */\r\n\r\n    /* since 2.3.0 */\r\n    FT_ULong              horz_metrics_offset;\r\n    FT_ULong              vert_metrics_offset;\r\n\r\n  } TT_FaceRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /*  <Struct>                                                             */\r\n  /*     TT_GlyphZoneRec                                                   */\r\n  /*                                                                       */\r\n  /*  <Description>                                                        */\r\n  /*     A glyph zone is used to load, scale and hint glyph outline        */\r\n  /*     coordinates.                                                      */\r\n  /*                                                                       */\r\n  /*  <Fields>                                                             */\r\n  /*     memory       :: A handle to the memory manager.                   */\r\n  /*                                                                       */\r\n  /*     max_points   :: The maximal size in points of the zone.           */\r\n  /*                                                                       */\r\n  /*     max_contours :: Max size in links contours of the zone.           */\r\n  /*                                                                       */\r\n  /*     n_points     :: The current number of points in the zone.         */\r\n  /*                                                                       */\r\n  /*     n_contours   :: The current number of contours in the zone.       */\r\n  /*                                                                       */\r\n  /*     org          :: The original glyph coordinates (font              */\r\n  /*                     units/scaled).                                    */\r\n  /*                                                                       */\r\n  /*     cur          :: The current glyph coordinates (scaled/hinted).    */\r\n  /*                                                                       */\r\n  /*     tags         :: The point control tags.                           */\r\n  /*                                                                       */\r\n  /*     contours     :: The contours end points.                          */\r\n  /*                                                                       */\r\n  /*     first_point  :: Offset of the current subglyph's first point.     */\r\n  /*                                                                       */\r\n  typedef struct  TT_GlyphZoneRec_\r\n  {\r\n    FT_Memory   memory;\r\n    FT_UShort   max_points;\r\n    FT_UShort   max_contours;\r\n    FT_UShort   n_points;    /* number of points in zone    */\r\n    FT_Short    n_contours;  /* number of contours          */\r\n\r\n    FT_Vector*  org;         /* original point coordinates  */\r\n    FT_Vector*  cur;         /* current point coordinates   */\r\n    FT_Vector*  orus;        /* original (unscaled) point coordinates */\r\n\r\n    FT_Byte*    tags;        /* current touch flags         */\r\n    FT_UShort*  contours;    /* contour end points          */\r\n\r\n    FT_UShort   first_point; /* offset of first (#0) point  */\r\n\r\n  } TT_GlyphZoneRec, *TT_GlyphZone;\r\n\r\n\r\n  /* handle to execution context */\r\n  typedef struct TT_ExecContextRec_*  TT_ExecContext;\r\n\r\n  /* glyph loader structure */\r\n  typedef struct  TT_LoaderRec_\r\n  {\r\n    FT_Face          face;\r\n    FT_Size          size;\r\n    FT_GlyphSlot     glyph;\r\n    FT_GlyphLoader   gloader;\r\n\r\n    FT_ULong         load_flags;\r\n    FT_UInt          glyph_index;\r\n\r\n    FT_Stream        stream;\r\n    FT_Int           byte_len;\r\n\r\n    FT_Short         n_contours;\r\n    FT_BBox          bbox;\r\n    FT_Int           left_bearing;\r\n    FT_Int           advance;\r\n    FT_Int           linear;\r\n    FT_Bool          linear_def;\r\n    FT_Bool          preserve_pps;\r\n    FT_Vector        pp1;\r\n    FT_Vector        pp2;\r\n\r\n    FT_ULong         glyf_offset;\r\n\r\n    /* the zone where we load our glyphs */\r\n    TT_GlyphZoneRec  base;\r\n    TT_GlyphZoneRec  zone;\r\n\r\n    TT_ExecContext   exec;\r\n    FT_Byte*         instructions;\r\n    FT_ULong         ins_pos;\r\n\r\n    /* for possible extensibility in other formats */\r\n    void*            other;\r\n\r\n    /* since version 2.1.8 */\r\n    FT_Int           top_bearing;\r\n    FT_Int           vadvance;\r\n    FT_Vector        pp3;\r\n    FT_Vector        pp4;\r\n\r\n    /* since version 2.2.1 */\r\n    FT_Byte*         cursor;\r\n    FT_Byte*         limit;\r\n\r\n  } TT_LoaderRec;\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __TTTYPES_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/t1tables.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  t1tables.h                                                             */\r\n/*                                                                         */\r\n/*    Basic Type 1/Type 2 tables definitions and interface (specification  */\r\n/*    only).                                                               */\r\n/*                                                                         */\r\n/*  Copyright 1996-2004, 2006, 2008, 2009, 2011 by                         */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __T1TABLES_H__\r\n#define __T1TABLES_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    type1_tables                                                       */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    Type 1 Tables                                                      */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    Type~1 (PostScript) specific font tables.                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This section contains the definition of Type 1-specific tables,    */\r\n  /*    including structures related to other PostScript font formats.     */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /* Note that we separate font data in PS_FontInfoRec and PS_PrivateRec */\r\n  /* structures in order to support Multiple Master fonts.               */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    PS_FontInfoRec                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to model a Type~1 or Type~2 FontInfo dictionary.  */\r\n  /*    Note that for Multiple Master fonts, each instance has its own     */\r\n  /*    FontInfo dictionary.                                               */\r\n  /*                                                                       */\r\n  typedef struct  PS_FontInfoRec_\r\n  {\r\n    FT_String*  version;\r\n    FT_String*  notice;\r\n    FT_String*  full_name;\r\n    FT_String*  family_name;\r\n    FT_String*  weight;\r\n    FT_Long     italic_angle;\r\n    FT_Bool     is_fixed_pitch;\r\n    FT_Short    underline_position;\r\n    FT_UShort   underline_thickness;\r\n\r\n  } PS_FontInfoRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    PS_FontInfo                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle to a @PS_FontInfoRec structure.                           */\r\n  /*                                                                       */\r\n  typedef struct PS_FontInfoRec_*  PS_FontInfo;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    T1_FontInfo                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This type is equivalent to @PS_FontInfoRec.  It is deprecated but  */\r\n  /*    kept to maintain source compatibility between various versions of  */\r\n  /*    FreeType.                                                          */\r\n  /*                                                                       */\r\n  typedef PS_FontInfoRec  T1_FontInfo;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    PS_PrivateRec                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to model a Type~1 or Type~2 private dictionary.   */\r\n  /*    Note that for Multiple Master fonts, each instance has its own     */\r\n  /*    Private dictionary.                                                */\r\n  /*                                                                       */\r\n  typedef struct  PS_PrivateRec_\r\n  {\r\n    FT_Int     unique_id;\r\n    FT_Int     lenIV;\r\n\r\n    FT_Byte    num_blue_values;\r\n    FT_Byte    num_other_blues;\r\n    FT_Byte    num_family_blues;\r\n    FT_Byte    num_family_other_blues;\r\n\r\n    FT_Short   blue_values[14];\r\n    FT_Short   other_blues[10];\r\n\r\n    FT_Short   family_blues      [14];\r\n    FT_Short   family_other_blues[10];\r\n\r\n    FT_Fixed   blue_scale;\r\n    FT_Int     blue_shift;\r\n    FT_Int     blue_fuzz;\r\n\r\n    FT_UShort  standard_width[1];\r\n    FT_UShort  standard_height[1];\r\n\r\n    FT_Byte    num_snap_widths;\r\n    FT_Byte    num_snap_heights;\r\n    FT_Bool    force_bold;\r\n    FT_Bool    round_stem_up;\r\n\r\n    FT_Short   snap_widths [13];  /* including std width  */\r\n    FT_Short   snap_heights[13];  /* including std height */\r\n\r\n    FT_Fixed   expansion_factor;\r\n\r\n    FT_Long    language_group;\r\n    FT_Long    password;\r\n\r\n    FT_Short   min_feature[2];\r\n\r\n  } PS_PrivateRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    PS_Private                                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle to a @PS_PrivateRec structure.                            */\r\n  /*                                                                       */\r\n  typedef struct PS_PrivateRec_*  PS_Private;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    T1_Private                                                         */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*   This type is equivalent to @PS_PrivateRec.  It is deprecated but    */\r\n  /*   kept to maintain source compatibility between various versions of   */\r\n  /*   FreeType.                                                           */\r\n  /*                                                                       */\r\n  typedef PS_PrivateRec  T1_Private;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Enum>                                                                */\r\n  /*    T1_Blend_Flags                                                     */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A set of flags used to indicate which fields are present in a      */\r\n  /*    given blend dictionary (font info or private).  Used to support    */\r\n  /*    Multiple Masters fonts.                                            */\r\n  /*                                                                       */\r\n  typedef enum  T1_Blend_Flags_\r\n  {\r\n    /*# required fields in a FontInfo blend dictionary */\r\n    T1_BLEND_UNDERLINE_POSITION = 0,\r\n    T1_BLEND_UNDERLINE_THICKNESS,\r\n    T1_BLEND_ITALIC_ANGLE,\r\n\r\n    /*# required fields in a Private blend dictionary */\r\n    T1_BLEND_BLUE_VALUES,\r\n    T1_BLEND_OTHER_BLUES,\r\n    T1_BLEND_STANDARD_WIDTH,\r\n    T1_BLEND_STANDARD_HEIGHT,\r\n    T1_BLEND_STEM_SNAP_WIDTHS,\r\n    T1_BLEND_STEM_SNAP_HEIGHTS,\r\n    T1_BLEND_BLUE_SCALE,\r\n    T1_BLEND_BLUE_SHIFT,\r\n    T1_BLEND_FAMILY_BLUES,\r\n    T1_BLEND_FAMILY_OTHER_BLUES,\r\n    T1_BLEND_FORCE_BOLD,\r\n\r\n    /*# never remove */\r\n    T1_BLEND_MAX\r\n\r\n  } T1_Blend_Flags;\r\n\r\n  /* */\r\n\r\n\r\n  /*# backwards compatible definitions */\r\n#define t1_blend_underline_position   T1_BLEND_UNDERLINE_POSITION\r\n#define t1_blend_underline_thickness  T1_BLEND_UNDERLINE_THICKNESS\r\n#define t1_blend_italic_angle         T1_BLEND_ITALIC_ANGLE\r\n#define t1_blend_blue_values          T1_BLEND_BLUE_VALUES\r\n#define t1_blend_other_blues          T1_BLEND_OTHER_BLUES\r\n#define t1_blend_standard_widths      T1_BLEND_STANDARD_WIDTH\r\n#define t1_blend_standard_height      T1_BLEND_STANDARD_HEIGHT\r\n#define t1_blend_stem_snap_widths     T1_BLEND_STEM_SNAP_WIDTHS\r\n#define t1_blend_stem_snap_heights    T1_BLEND_STEM_SNAP_HEIGHTS\r\n#define t1_blend_blue_scale           T1_BLEND_BLUE_SCALE\r\n#define t1_blend_blue_shift           T1_BLEND_BLUE_SHIFT\r\n#define t1_blend_family_blues         T1_BLEND_FAMILY_BLUES\r\n#define t1_blend_family_other_blues   T1_BLEND_FAMILY_OTHER_BLUES\r\n#define t1_blend_force_bold           T1_BLEND_FORCE_BOLD\r\n#define t1_blend_max                  T1_BLEND_MAX\r\n\r\n\r\n  /* maximum number of Multiple Masters designs, as defined in the spec */\r\n#define T1_MAX_MM_DESIGNS     16\r\n\r\n  /* maximum number of Multiple Masters axes, as defined in the spec */\r\n#define T1_MAX_MM_AXIS        4\r\n\r\n  /* maximum number of elements in a design map */\r\n#define T1_MAX_MM_MAP_POINTS  20\r\n\r\n\r\n  /* this structure is used to store the BlendDesignMap entry for an axis */\r\n  typedef struct  PS_DesignMap_\r\n  {\r\n    FT_Byte    num_points;\r\n    FT_Long*   design_points;\r\n    FT_Fixed*  blend_points;\r\n\r\n  } PS_DesignMapRec, *PS_DesignMap;\r\n\r\n  /* backwards-compatible definition */\r\n  typedef PS_DesignMapRec  T1_DesignMap;\r\n\r\n\r\n  typedef struct  PS_BlendRec_\r\n  {\r\n    FT_UInt          num_designs;\r\n    FT_UInt          num_axis;\r\n\r\n    FT_String*       axis_names[T1_MAX_MM_AXIS];\r\n    FT_Fixed*        design_pos[T1_MAX_MM_DESIGNS];\r\n    PS_DesignMapRec  design_map[T1_MAX_MM_AXIS];\r\n\r\n    FT_Fixed*        weight_vector;\r\n    FT_Fixed*        default_weight_vector;\r\n\r\n    PS_FontInfo      font_infos[T1_MAX_MM_DESIGNS + 1];\r\n    PS_Private       privates  [T1_MAX_MM_DESIGNS + 1];\r\n\r\n    FT_ULong         blend_bitflags;\r\n\r\n    FT_BBox*         bboxes    [T1_MAX_MM_DESIGNS + 1];\r\n\r\n    /* since 2.3.0 */\r\n\r\n    /* undocumented, optional: the default design instance;   */\r\n    /* corresponds to default_weight_vector --                */\r\n    /* num_default_design_vector == 0 means it is not present */\r\n    /* in the font and associated metrics files               */\r\n    FT_UInt          default_design_vector[T1_MAX_MM_DESIGNS];\r\n    FT_UInt          num_default_design_vector;\r\n\r\n  } PS_BlendRec, *PS_Blend;\r\n\r\n\r\n  /* backwards-compatible definition */\r\n  typedef PS_BlendRec  T1_Blend;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    CID_FaceDictRec                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to represent data in a CID top-level dictionary.  */\r\n  /*                                                                       */\r\n  typedef struct  CID_FaceDictRec_\r\n  {\r\n    PS_PrivateRec  private_dict;\r\n\r\n    FT_UInt        len_buildchar;\r\n    FT_Fixed       forcebold_threshold;\r\n    FT_Pos         stroke_width;\r\n    FT_Fixed       expansion_factor;\r\n\r\n    FT_Byte        paint_type;\r\n    FT_Byte        font_type;\r\n    FT_Matrix      font_matrix;\r\n    FT_Vector      font_offset;\r\n\r\n    FT_UInt        num_subrs;\r\n    FT_ULong       subrmap_offset;\r\n    FT_Int         sd_bytes;\r\n\r\n  } CID_FaceDictRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    CID_FaceDict                                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle to a @CID_FaceDictRec structure.                          */\r\n  /*                                                                       */\r\n  typedef struct CID_FaceDictRec_*  CID_FaceDict;\r\n\r\n  /* */\r\n\r\n\r\n  /* backwards-compatible definition */\r\n  typedef CID_FaceDictRec  CID_FontDict;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    CID_FaceInfoRec                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to represent CID Face information.                */\r\n  /*                                                                       */\r\n  typedef struct  CID_FaceInfoRec_\r\n  {\r\n    FT_String*      cid_font_name;\r\n    FT_Fixed        cid_version;\r\n    FT_Int          cid_font_type;\r\n\r\n    FT_String*      registry;\r\n    FT_String*      ordering;\r\n    FT_Int          supplement;\r\n\r\n    PS_FontInfoRec  font_info;\r\n    FT_BBox         font_bbox;\r\n    FT_ULong        uid_base;\r\n\r\n    FT_Int          num_xuid;\r\n    FT_ULong        xuid[16];\r\n\r\n    FT_ULong        cidmap_offset;\r\n    FT_Int          fd_bytes;\r\n    FT_Int          gd_bytes;\r\n    FT_ULong        cid_count;\r\n\r\n    FT_Int          num_dicts;\r\n    CID_FaceDict    font_dicts;\r\n\r\n    FT_ULong        data_offset;\r\n\r\n  } CID_FaceInfoRec;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    CID_FaceInfo                                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A handle to a @CID_FaceInfoRec structure.                          */\r\n  /*                                                                       */\r\n  typedef struct CID_FaceInfoRec_*  CID_FaceInfo;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    CID_Info                                                           */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*   This type is equivalent to @CID_FaceInfoRec.  It is deprecated but  */\r\n  /*   kept to maintain source compatibility between various versions of   */\r\n  /*   FreeType.                                                           */\r\n  /*                                                                       */\r\n  typedef CID_FaceInfoRec  CID_Info;\r\n\r\n\r\n  /************************************************************************\r\n   *\r\n   * @function:\r\n   *    FT_Has_PS_Glyph_Names\r\n   *\r\n   * @description:\r\n   *    Return true if a given face provides reliable PostScript glyph\r\n   *    names.  This is similar to using the @FT_HAS_GLYPH_NAMES macro,\r\n   *    except that certain fonts (mostly TrueType) contain incorrect\r\n   *    glyph name tables.\r\n   *\r\n   *    When this function returns true, the caller is sure that the glyph\r\n   *    names returned by @FT_Get_Glyph_Name are reliable.\r\n   *\r\n   * @input:\r\n   *    face ::\r\n   *       face handle\r\n   *\r\n   * @return:\r\n   *    Boolean.  True if glyph names are reliable.\r\n   *\r\n   */\r\n  FT_EXPORT( FT_Int )\r\n  FT_Has_PS_Glyph_Names( FT_Face  face );\r\n\r\n\r\n  /************************************************************************\r\n   *\r\n   * @function:\r\n   *    FT_Get_PS_Font_Info\r\n   *\r\n   * @description:\r\n   *    Retrieve the @PS_FontInfoRec structure corresponding to a given\r\n   *    PostScript font.\r\n   *\r\n   * @input:\r\n   *    face ::\r\n   *       PostScript face handle.\r\n   *\r\n   * @output:\r\n   *    afont_info ::\r\n   *       Output font info structure pointer.\r\n   *\r\n   * @return:\r\n   *    FreeType error code.  0~means success.\r\n   *\r\n   * @note:\r\n   *    The string pointers within the font info structure are owned by\r\n   *    the face and don't need to be freed by the caller.\r\n   *\r\n   *    If the font's format is not PostScript-based, this function will\r\n   *    return the `FT_Err_Invalid_Argument' error code.\r\n   *\r\n   */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Get_PS_Font_Info( FT_Face      face,\r\n                       PS_FontInfo  afont_info );\r\n\r\n\r\n  /************************************************************************\r\n   *\r\n   * @function:\r\n   *    FT_Get_PS_Font_Private\r\n   *\r\n   * @description:\r\n   *    Retrieve the @PS_PrivateRec structure corresponding to a given\r\n   *    PostScript font.\r\n   *\r\n   * @input:\r\n   *    face ::\r\n   *       PostScript face handle.\r\n   *\r\n   * @output:\r\n   *    afont_private ::\r\n   *       Output private dictionary structure pointer.\r\n   *\r\n   * @return:\r\n   *    FreeType error code.  0~means success.\r\n   *\r\n   * @note:\r\n   *    The string pointers within the @PS_PrivateRec structure are owned by\r\n   *    the face and don't need to be freed by the caller.\r\n   *\r\n   *    If the font's format is not PostScript-based, this function returns\r\n   *    the `FT_Err_Invalid_Argument' error code.\r\n   *\r\n   */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Get_PS_Font_Private( FT_Face     face,\r\n                          PS_Private  afont_private );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Enum>                                                                */\r\n  /*    T1_EncodingType                                                    */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    An enumeration describing the `Encoding' entry in a Type 1         */\r\n  /*    dictionary.                                                        */\r\n  /*                                                                       */\r\n  typedef enum  T1_EncodingType_\r\n  {\r\n    T1_ENCODING_TYPE_NONE = 0,\r\n    T1_ENCODING_TYPE_ARRAY,\r\n    T1_ENCODING_TYPE_STANDARD,\r\n    T1_ENCODING_TYPE_ISOLATIN1,\r\n    T1_ENCODING_TYPE_EXPERT\r\n\r\n  } T1_EncodingType;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Enum>                                                                */\r\n  /*    PS_Dict_Keys                                                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    An enumeration used in calls to @FT_Get_PS_Font_Value to identify  */\r\n  /*    the Type~1 dictionary entry to retrieve.                           */\r\n  /*                                                                       */\r\n  typedef enum  PS_Dict_Keys_\r\n  {\r\n    /* conventionally in the font dictionary */\r\n    PS_DICT_FONT_TYPE,              /* FT_Byte         */\r\n    PS_DICT_FONT_MATRIX,            /* FT_Fixed        */\r\n    PS_DICT_FONT_BBOX,              /* FT_Fixed        */\r\n    PS_DICT_PAINT_TYPE,             /* FT_Byte         */\r\n    PS_DICT_FONT_NAME,              /* FT_String*      */\r\n    PS_DICT_UNIQUE_ID,              /* FT_Int          */\r\n    PS_DICT_NUM_CHAR_STRINGS,       /* FT_Int          */\r\n    PS_DICT_CHAR_STRING_KEY,        /* FT_String*      */\r\n    PS_DICT_CHAR_STRING,            /* FT_String*      */\r\n    PS_DICT_ENCODING_TYPE,          /* T1_EncodingType */\r\n    PS_DICT_ENCODING_ENTRY,         /* FT_String*      */\r\n\r\n    /* conventionally in the font Private dictionary */\r\n    PS_DICT_NUM_SUBRS,              /* FT_Int     */\r\n    PS_DICT_SUBR,                   /* FT_String* */\r\n    PS_DICT_STD_HW,                 /* FT_UShort  */\r\n    PS_DICT_STD_VW,                 /* FT_UShort  */\r\n    PS_DICT_NUM_BLUE_VALUES,        /* FT_Byte    */\r\n    PS_DICT_BLUE_VALUE,             /* FT_Short   */\r\n    PS_DICT_BLUE_FUZZ,              /* FT_Int     */\r\n    PS_DICT_NUM_OTHER_BLUES,        /* FT_Byte    */\r\n    PS_DICT_OTHER_BLUE,             /* FT_Short   */\r\n    PS_DICT_NUM_FAMILY_BLUES,       /* FT_Byte    */\r\n    PS_DICT_FAMILY_BLUE,            /* FT_Short   */\r\n    PS_DICT_NUM_FAMILY_OTHER_BLUES, /* FT_Byte    */\r\n    PS_DICT_FAMILY_OTHER_BLUE,      /* FT_Short   */\r\n    PS_DICT_BLUE_SCALE,             /* FT_Fixed   */\r\n    PS_DICT_BLUE_SHIFT,             /* FT_Int     */\r\n    PS_DICT_NUM_STEM_SNAP_H,        /* FT_Byte    */\r\n    PS_DICT_STEM_SNAP_H,            /* FT_Short   */\r\n    PS_DICT_NUM_STEM_SNAP_V,        /* FT_Byte    */\r\n    PS_DICT_STEM_SNAP_V,            /* FT_Short   */\r\n    PS_DICT_FORCE_BOLD,             /* FT_Bool    */\r\n    PS_DICT_RND_STEM_UP,            /* FT_Bool    */\r\n    PS_DICT_MIN_FEATURE,            /* FT_Short   */\r\n    PS_DICT_LEN_IV,                 /* FT_Int     */\r\n    PS_DICT_PASSWORD,               /* FT_Long    */\r\n    PS_DICT_LANGUAGE_GROUP,         /* FT_Long    */\r\n\r\n    /* conventionally in the font FontInfo dictionary */\r\n    PS_DICT_VERSION,                /* FT_String* */\r\n    PS_DICT_NOTICE,                 /* FT_String* */\r\n    PS_DICT_FULL_NAME,              /* FT_String* */\r\n    PS_DICT_FAMILY_NAME,            /* FT_String* */\r\n    PS_DICT_WEIGHT,                 /* FT_String  */\r\n    PS_DICT_IS_FIXED_PITCH,         /* FT_Bool    */\r\n    PS_DICT_UNDERLINE_POSITION,     /* FT_Short   */\r\n    PS_DICT_UNDERLINE_THICKNESS,    /* FT_UShort  */\r\n    PS_DICT_FS_TYPE,                /* FT_UShort  */\r\n    PS_DICT_ITALIC_ANGLE,           /* FT_Long    */\r\n\r\n    PS_DICT_MAX = PS_DICT_ITALIC_ANGLE\r\n\r\n  } PS_Dict_Keys;\r\n\r\n\r\n  /************************************************************************\r\n   *\r\n   * @function:\r\n   *    FT_Get_PS_Font_Value\r\n   *\r\n   * @description:\r\n   *    Retrieve the value for the supplied key from a PostScript font.\r\n   *\r\n   * @input:\r\n   *    face ::\r\n   *       PostScript face handle.\r\n   *\r\n   *    key ::\r\n   *       An enumeration value representing the dictionary key to retrieve.\r\n   *\r\n   *    idx ::\r\n   *       For array values, this specifies the index to be returned.\r\n   *\r\n   *    value ::\r\n   *       A pointer to memory into which to write the value.\r\n   *\r\n   *    valen_len ::\r\n   *       The size, in bytes, of the memory supplied for the value.\r\n   *\r\n   * @output:\r\n   *    value ::\r\n   *       The value matching the above key, if it exists.\r\n   *\r\n   * @return:\r\n   *    The amount of memory (in bytes) required to hold the requested\r\n   *    value (if it exists, -1 otherwise).\r\n   *\r\n   * @note:\r\n   *    The values returned are not pointers into the internal structures of\r\n   *    the face, but are `fresh' copies, so that the memory containing them\r\n   *    belongs to the calling application.  This also enforces the\r\n   *    `read-only' nature of these values, i.e., this function cannot be\r\n   *    used to manipulate the face.\r\n   *\r\n   *    `value' is a void pointer because the values returned can be of\r\n   *    various types.\r\n   *\r\n   *    If either `value' is NULL or `value_len' is too small, just the\r\n   *    required memory size for the requested entry is returned.\r\n   *\r\n   *    The `idx' parameter is used, not only to retrieve elements of, for\r\n   *    example, the FontMatrix or FontBBox, but also to retrieve name keys\r\n   *    from the CharStrings dictionary, and the charstrings themselves.  It\r\n   *    is ignored for atomic values.\r\n   *\r\n   *    PS_DICT_BLUE_SCALE returns a value that is scaled up by 1000.  To\r\n   *    get the value as in the font stream, you need to divide by\r\n   *    65536000.0 (to remove the FT_Fixed scale, and the x1000 scale).\r\n   *\r\n   *    IMPORTANT: Only key/value pairs read by the FreeType interpreter can\r\n   *    be retrieved.  So, for example, PostScript procedures such as NP,\r\n   *    ND, and RD are not available.  Arbitrary keys are, obviously, not be\r\n   *    available either.\r\n   *\r\n   *    If the font's format is not PostScript-based, this function returns\r\n   *    the `FT_Err_Invalid_Argument' error code.\r\n   *\r\n   */\r\n  FT_EXPORT( FT_Long )\r\n  FT_Get_PS_Font_Value( FT_Face       face,\r\n                        PS_Dict_Keys  key,\r\n                        FT_UInt       idx,\r\n                        void         *value,\r\n                        FT_Long       value_len );\r\n\r\n  /* */\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __T1TABLES_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ttnameid.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ttnameid.h                                                             */\r\n/*                                                                         */\r\n/*    TrueType name ID definitions (specification only).                   */\r\n/*                                                                         */\r\n/*  Copyright 1996-2002, 2003, 2004, 2006, 2007, 2008 by                   */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __TTNAMEID_H__\r\n#define __TTNAMEID_H__\r\n\r\n\r\n#include <ft2build.h>\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    truetype_tables                                                    */\r\n  /*                                                                       */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Possible values for the `platform' identifier code in the name        */\r\n  /* records of the TTF `name' table.                                      */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /***********************************************************************\r\n   *\r\n   * @enum:\r\n   *   TT_PLATFORM_XXX\r\n   *\r\n   * @description:\r\n   *   A list of valid values for the `platform_id' identifier code in\r\n   *   @FT_CharMapRec and @FT_SfntName structures.\r\n   *\r\n   * @values:\r\n   *   TT_PLATFORM_APPLE_UNICODE ::\r\n   *     Used by Apple to indicate a Unicode character map and/or name entry.\r\n   *     See @TT_APPLE_ID_XXX for corresponding `encoding_id' values.  Note\r\n   *     that name entries in this format are coded as big-endian UCS-2\r\n   *     character codes _only_.\r\n   *\r\n   *   TT_PLATFORM_MACINTOSH ::\r\n   *     Used by Apple to indicate a MacOS-specific charmap and/or name entry.\r\n   *     See @TT_MAC_ID_XXX for corresponding `encoding_id' values.  Note that\r\n   *     most TrueType fonts contain an Apple roman charmap to be usable on\r\n   *     MacOS systems (even if they contain a Microsoft charmap as well).\r\n   *\r\n   *   TT_PLATFORM_ISO ::\r\n   *     This value was used to specify ISO/IEC 10646 charmaps.  It is however\r\n   *     now deprecated.  See @TT_ISO_ID_XXX for a list of corresponding\r\n   *     `encoding_id' values.\r\n   *\r\n   *   TT_PLATFORM_MICROSOFT ::\r\n   *     Used by Microsoft to indicate Windows-specific charmaps.  See\r\n   *     @TT_MS_ID_XXX for a list of corresponding `encoding_id' values.\r\n   *     Note that most fonts contain a Unicode charmap using\r\n   *     (TT_PLATFORM_MICROSOFT, @TT_MS_ID_UNICODE_CS).\r\n   *\r\n   *   TT_PLATFORM_CUSTOM ::\r\n   *     Used to indicate application-specific charmaps.\r\n   *\r\n   *   TT_PLATFORM_ADOBE ::\r\n   *     This value isn't part of any font format specification, but is used\r\n   *     by FreeType to report Adobe-specific charmaps in an @FT_CharMapRec\r\n   *     structure.  See @TT_ADOBE_ID_XXX.\r\n   */\r\n\r\n#define TT_PLATFORM_APPLE_UNICODE  0\r\n#define TT_PLATFORM_MACINTOSH      1\r\n#define TT_PLATFORM_ISO            2 /* deprecated */\r\n#define TT_PLATFORM_MICROSOFT      3\r\n#define TT_PLATFORM_CUSTOM         4\r\n#define TT_PLATFORM_ADOBE          7 /* artificial */\r\n\r\n\r\n  /***********************************************************************\r\n   *\r\n   * @enum:\r\n   *   TT_APPLE_ID_XXX\r\n   *\r\n   * @description:\r\n   *   A list of valid values for the `encoding_id' for\r\n   *   @TT_PLATFORM_APPLE_UNICODE charmaps and name entries.\r\n   *\r\n   * @values:\r\n   *   TT_APPLE_ID_DEFAULT ::\r\n   *     Unicode version 1.0.\r\n   *\r\n   *   TT_APPLE_ID_UNICODE_1_1 ::\r\n   *     Unicode 1.1; specifies Hangul characters starting at U+34xx.\r\n   *\r\n   *   TT_APPLE_ID_ISO_10646 ::\r\n   *     Deprecated (identical to preceding).\r\n   *\r\n   *   TT_APPLE_ID_UNICODE_2_0 ::\r\n   *     Unicode 2.0 and beyond (UTF-16 BMP only).\r\n   *\r\n   *   TT_APPLE_ID_UNICODE_32 ::\r\n   *     Unicode 3.1 and beyond, using UTF-32.\r\n   *\r\n   *   TT_APPLE_ID_VARIANT_SELECTOR ::\r\n   *     From Adobe, not Apple.  Not a normal cmap.  Specifies variations\r\n   *     on a real cmap.\r\n   */\r\n\r\n#define TT_APPLE_ID_DEFAULT           0 /* Unicode 1.0 */\r\n#define TT_APPLE_ID_UNICODE_1_1       1 /* specify Hangul at U+34xx */\r\n#define TT_APPLE_ID_ISO_10646         2 /* deprecated */\r\n#define TT_APPLE_ID_UNICODE_2_0       3 /* or later */\r\n#define TT_APPLE_ID_UNICODE_32        4 /* 2.0 or later, full repertoire */\r\n#define TT_APPLE_ID_VARIANT_SELECTOR  5 /* variation selector data */\r\n\r\n\r\n  /***********************************************************************\r\n   *\r\n   * @enum:\r\n   *   TT_MAC_ID_XXX\r\n   *\r\n   * @description:\r\n   *   A list of valid values for the `encoding_id' for\r\n   *   @TT_PLATFORM_MACINTOSH charmaps and name entries.\r\n   *\r\n   * @values:\r\n   *   TT_MAC_ID_ROMAN ::\r\n   *   TT_MAC_ID_JAPANESE ::\r\n   *   TT_MAC_ID_TRADITIONAL_CHINESE ::\r\n   *   TT_MAC_ID_KOREAN ::\r\n   *   TT_MAC_ID_ARABIC ::\r\n   *   TT_MAC_ID_HEBREW ::\r\n   *   TT_MAC_ID_GREEK ::\r\n   *   TT_MAC_ID_RUSSIAN ::\r\n   *   TT_MAC_ID_RSYMBOL ::\r\n   *   TT_MAC_ID_DEVANAGARI ::\r\n   *   TT_MAC_ID_GURMUKHI ::\r\n   *   TT_MAC_ID_GUJARATI ::\r\n   *   TT_MAC_ID_ORIYA ::\r\n   *   TT_MAC_ID_BENGALI ::\r\n   *   TT_MAC_ID_TAMIL ::\r\n   *   TT_MAC_ID_TELUGU ::\r\n   *   TT_MAC_ID_KANNADA ::\r\n   *   TT_MAC_ID_MALAYALAM ::\r\n   *   TT_MAC_ID_SINHALESE ::\r\n   *   TT_MAC_ID_BURMESE ::\r\n   *   TT_MAC_ID_KHMER ::\r\n   *   TT_MAC_ID_THAI ::\r\n   *   TT_MAC_ID_LAOTIAN ::\r\n   *   TT_MAC_ID_GEORGIAN ::\r\n   *   TT_MAC_ID_ARMENIAN ::\r\n   *   TT_MAC_ID_MALDIVIAN ::\r\n   *   TT_MAC_ID_SIMPLIFIED_CHINESE ::\r\n   *   TT_MAC_ID_TIBETAN ::\r\n   *   TT_MAC_ID_MONGOLIAN ::\r\n   *   TT_MAC_ID_GEEZ ::\r\n   *   TT_MAC_ID_SLAVIC ::\r\n   *   TT_MAC_ID_VIETNAMESE ::\r\n   *   TT_MAC_ID_SINDHI ::\r\n   *   TT_MAC_ID_UNINTERP ::\r\n   */\r\n\r\n#define TT_MAC_ID_ROMAN                 0\r\n#define TT_MAC_ID_JAPANESE              1\r\n#define TT_MAC_ID_TRADITIONAL_CHINESE   2\r\n#define TT_MAC_ID_KOREAN                3\r\n#define TT_MAC_ID_ARABIC                4\r\n#define TT_MAC_ID_HEBREW                5\r\n#define TT_MAC_ID_GREEK                 6\r\n#define TT_MAC_ID_RUSSIAN               7\r\n#define TT_MAC_ID_RSYMBOL               8\r\n#define TT_MAC_ID_DEVANAGARI            9\r\n#define TT_MAC_ID_GURMUKHI             10\r\n#define TT_MAC_ID_GUJARATI             11\r\n#define TT_MAC_ID_ORIYA                12\r\n#define TT_MAC_ID_BENGALI              13\r\n#define TT_MAC_ID_TAMIL                14\r\n#define TT_MAC_ID_TELUGU               15\r\n#define TT_MAC_ID_KANNADA              16\r\n#define TT_MAC_ID_MALAYALAM            17\r\n#define TT_MAC_ID_SINHALESE            18\r\n#define TT_MAC_ID_BURMESE              19\r\n#define TT_MAC_ID_KHMER                20\r\n#define TT_MAC_ID_THAI                 21\r\n#define TT_MAC_ID_LAOTIAN              22\r\n#define TT_MAC_ID_GEORGIAN             23\r\n#define TT_MAC_ID_ARMENIAN             24\r\n#define TT_MAC_ID_MALDIVIAN            25\r\n#define TT_MAC_ID_SIMPLIFIED_CHINESE   25\r\n#define TT_MAC_ID_TIBETAN              26\r\n#define TT_MAC_ID_MONGOLIAN            27\r\n#define TT_MAC_ID_GEEZ                 28\r\n#define TT_MAC_ID_SLAVIC               29\r\n#define TT_MAC_ID_VIETNAMESE           30\r\n#define TT_MAC_ID_SINDHI               31\r\n#define TT_MAC_ID_UNINTERP             32\r\n\r\n\r\n  /***********************************************************************\r\n   *\r\n   * @enum:\r\n   *   TT_ISO_ID_XXX\r\n   *\r\n   * @description:\r\n   *   A list of valid values for the `encoding_id' for\r\n   *   @TT_PLATFORM_ISO charmaps and name entries.\r\n   *\r\n   *   Their use is now deprecated.\r\n   *\r\n   * @values:\r\n   *   TT_ISO_ID_7BIT_ASCII ::\r\n   *     ASCII.\r\n   *   TT_ISO_ID_10646 ::\r\n   *     ISO/10646.\r\n   *   TT_ISO_ID_8859_1 ::\r\n   *     Also known as Latin-1.\r\n   */\r\n\r\n#define TT_ISO_ID_7BIT_ASCII  0\r\n#define TT_ISO_ID_10646       1\r\n#define TT_ISO_ID_8859_1      2\r\n\r\n\r\n  /***********************************************************************\r\n   *\r\n   * @enum:\r\n   *   TT_MS_ID_XXX\r\n   *\r\n   * @description:\r\n   *   A list of valid values for the `encoding_id' for\r\n   *   @TT_PLATFORM_MICROSOFT charmaps and name entries.\r\n   *\r\n   * @values:\r\n   *   TT_MS_ID_SYMBOL_CS ::\r\n   *     Corresponds to Microsoft symbol encoding. See\r\n   *     @FT_ENCODING_MS_SYMBOL.\r\n   *\r\n   *   TT_MS_ID_UNICODE_CS ::\r\n   *     Corresponds to a Microsoft WGL4 charmap, matching Unicode.  See\r\n   *     @FT_ENCODING_UNICODE.\r\n   *\r\n   *   TT_MS_ID_SJIS ::\r\n   *     Corresponds to SJIS Japanese encoding.  See @FT_ENCODING_SJIS.\r\n   *\r\n   *   TT_MS_ID_GB2312 ::\r\n   *     Corresponds to Simplified Chinese as used in Mainland China.  See\r\n   *     @FT_ENCODING_GB2312.\r\n   *\r\n   *   TT_MS_ID_BIG_5 ::\r\n   *     Corresponds to Traditional Chinese as used in Taiwan and Hong Kong.\r\n   *     See @FT_ENCODING_BIG5.\r\n   *\r\n   *   TT_MS_ID_WANSUNG ::\r\n   *     Corresponds to Korean Wansung encoding.  See @FT_ENCODING_WANSUNG.\r\n   *\r\n   *   TT_MS_ID_JOHAB ::\r\n   *     Corresponds to Johab encoding.  See @FT_ENCODING_JOHAB.\r\n   *\r\n   *   TT_MS_ID_UCS_4 ::\r\n   *     Corresponds to UCS-4 or UTF-32 charmaps.  This has been added to\r\n   *     the OpenType specification version 1.4 (mid-2001.)\r\n   */\r\n\r\n#define TT_MS_ID_SYMBOL_CS    0\r\n#define TT_MS_ID_UNICODE_CS   1\r\n#define TT_MS_ID_SJIS         2\r\n#define TT_MS_ID_GB2312       3\r\n#define TT_MS_ID_BIG_5        4\r\n#define TT_MS_ID_WANSUNG      5\r\n#define TT_MS_ID_JOHAB        6\r\n#define TT_MS_ID_UCS_4       10\r\n\r\n\r\n  /***********************************************************************\r\n   *\r\n   * @enum:\r\n   *   TT_ADOBE_ID_XXX\r\n   *\r\n   * @description:\r\n   *   A list of valid values for the `encoding_id' for\r\n   *   @TT_PLATFORM_ADOBE charmaps.  This is a FreeType-specific extension!\r\n   *\r\n   * @values:\r\n   *   TT_ADOBE_ID_STANDARD ::\r\n   *     Adobe standard encoding.\r\n   *   TT_ADOBE_ID_EXPERT ::\r\n   *     Adobe expert encoding.\r\n   *   TT_ADOBE_ID_CUSTOM ::\r\n   *     Adobe custom encoding.\r\n   *   TT_ADOBE_ID_LATIN_1 ::\r\n   *     Adobe Latin~1 encoding.\r\n   */\r\n\r\n#define TT_ADOBE_ID_STANDARD  0\r\n#define TT_ADOBE_ID_EXPERT    1\r\n#define TT_ADOBE_ID_CUSTOM    2\r\n#define TT_ADOBE_ID_LATIN_1   3\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Possible values of the language identifier field in the name records  */\r\n  /* of the TTF `name' table if the `platform' identifier code is          */\r\n  /* TT_PLATFORM_MACINTOSH.                                                */\r\n  /*                                                                       */\r\n  /* The canonical source for the Apple assigned Language ID's is at       */\r\n  /*                                                                       */\r\n  /*   http://fonts.apple.com/TTRefMan/RM06/Chap6name.html                 */\r\n  /*                                                                       */\r\n#define TT_MAC_LANGID_ENGLISH                       0\r\n#define TT_MAC_LANGID_FRENCH                        1\r\n#define TT_MAC_LANGID_GERMAN                        2\r\n#define TT_MAC_LANGID_ITALIAN                       3\r\n#define TT_MAC_LANGID_DUTCH                         4\r\n#define TT_MAC_LANGID_SWEDISH                       5\r\n#define TT_MAC_LANGID_SPANISH                       6\r\n#define TT_MAC_LANGID_DANISH                        7\r\n#define TT_MAC_LANGID_PORTUGUESE                    8\r\n#define TT_MAC_LANGID_NORWEGIAN                     9\r\n#define TT_MAC_LANGID_HEBREW                       10\r\n#define TT_MAC_LANGID_JAPANESE                     11\r\n#define TT_MAC_LANGID_ARABIC                       12\r\n#define TT_MAC_LANGID_FINNISH                      13\r\n#define TT_MAC_LANGID_GREEK                        14\r\n#define TT_MAC_LANGID_ICELANDIC                    15\r\n#define TT_MAC_LANGID_MALTESE                      16\r\n#define TT_MAC_LANGID_TURKISH                      17\r\n#define TT_MAC_LANGID_CROATIAN                     18\r\n#define TT_MAC_LANGID_CHINESE_TRADITIONAL          19\r\n#define TT_MAC_LANGID_URDU                         20\r\n#define TT_MAC_LANGID_HINDI                        21\r\n#define TT_MAC_LANGID_THAI                         22\r\n#define TT_MAC_LANGID_KOREAN                       23\r\n#define TT_MAC_LANGID_LITHUANIAN                   24\r\n#define TT_MAC_LANGID_POLISH                       25\r\n#define TT_MAC_LANGID_HUNGARIAN                    26\r\n#define TT_MAC_LANGID_ESTONIAN                     27\r\n#define TT_MAC_LANGID_LETTISH                      28\r\n#define TT_MAC_LANGID_SAAMISK                      29\r\n#define TT_MAC_LANGID_FAEROESE                     30\r\n#define TT_MAC_LANGID_FARSI                        31\r\n#define TT_MAC_LANGID_RUSSIAN                      32\r\n#define TT_MAC_LANGID_CHINESE_SIMPLIFIED           33\r\n#define TT_MAC_LANGID_FLEMISH                      34\r\n#define TT_MAC_LANGID_IRISH                        35\r\n#define TT_MAC_LANGID_ALBANIAN                     36\r\n#define TT_MAC_LANGID_ROMANIAN                     37\r\n#define TT_MAC_LANGID_CZECH                        38\r\n#define TT_MAC_LANGID_SLOVAK                       39\r\n#define TT_MAC_LANGID_SLOVENIAN                    40\r\n#define TT_MAC_LANGID_YIDDISH                      41\r\n#define TT_MAC_LANGID_SERBIAN                      42\r\n#define TT_MAC_LANGID_MACEDONIAN                   43\r\n#define TT_MAC_LANGID_BULGARIAN                    44\r\n#define TT_MAC_LANGID_UKRAINIAN                    45\r\n#define TT_MAC_LANGID_BYELORUSSIAN                 46\r\n#define TT_MAC_LANGID_UZBEK                        47\r\n#define TT_MAC_LANGID_KAZAKH                       48\r\n#define TT_MAC_LANGID_AZERBAIJANI                  49\r\n#define TT_MAC_LANGID_AZERBAIJANI_CYRILLIC_SCRIPT  49\r\n#define TT_MAC_LANGID_AZERBAIJANI_ARABIC_SCRIPT    50\r\n#define TT_MAC_LANGID_ARMENIAN                     51\r\n#define TT_MAC_LANGID_GEORGIAN                     52\r\n#define TT_MAC_LANGID_MOLDAVIAN                    53\r\n#define TT_MAC_LANGID_KIRGHIZ                      54\r\n#define TT_MAC_LANGID_TAJIKI                       55\r\n#define TT_MAC_LANGID_TURKMEN                      56\r\n#define TT_MAC_LANGID_MONGOLIAN                    57\r\n#define TT_MAC_LANGID_MONGOLIAN_MONGOLIAN_SCRIPT   57\r\n#define TT_MAC_LANGID_MONGOLIAN_CYRILLIC_SCRIPT    58\r\n#define TT_MAC_LANGID_PASHTO                       59\r\n#define TT_MAC_LANGID_KURDISH                      60\r\n#define TT_MAC_LANGID_KASHMIRI                     61\r\n#define TT_MAC_LANGID_SINDHI                       62\r\n#define TT_MAC_LANGID_TIBETAN                      63\r\n#define TT_MAC_LANGID_NEPALI                       64\r\n#define TT_MAC_LANGID_SANSKRIT                     65\r\n#define TT_MAC_LANGID_MARATHI                      66\r\n#define TT_MAC_LANGID_BENGALI                      67\r\n#define TT_MAC_LANGID_ASSAMESE                     68\r\n#define TT_MAC_LANGID_GUJARATI                     69\r\n#define TT_MAC_LANGID_PUNJABI                      70\r\n#define TT_MAC_LANGID_ORIYA                        71\r\n#define TT_MAC_LANGID_MALAYALAM                    72\r\n#define TT_MAC_LANGID_KANNADA                      73\r\n#define TT_MAC_LANGID_TAMIL                        74\r\n#define TT_MAC_LANGID_TELUGU                       75\r\n#define TT_MAC_LANGID_SINHALESE                    76\r\n#define TT_MAC_LANGID_BURMESE                      77\r\n#define TT_MAC_LANGID_KHMER                        78\r\n#define TT_MAC_LANGID_LAO                          79\r\n#define TT_MAC_LANGID_VIETNAMESE                   80\r\n#define TT_MAC_LANGID_INDONESIAN                   81\r\n#define TT_MAC_LANGID_TAGALOG                      82\r\n#define TT_MAC_LANGID_MALAY_ROMAN_SCRIPT           83\r\n#define TT_MAC_LANGID_MALAY_ARABIC_SCRIPT          84\r\n#define TT_MAC_LANGID_AMHARIC                      85\r\n#define TT_MAC_LANGID_TIGRINYA                     86\r\n#define TT_MAC_LANGID_GALLA                        87\r\n#define TT_MAC_LANGID_SOMALI                       88\r\n#define TT_MAC_LANGID_SWAHILI                      89\r\n#define TT_MAC_LANGID_RUANDA                       90\r\n#define TT_MAC_LANGID_RUNDI                        91\r\n#define TT_MAC_LANGID_CHEWA                        92\r\n#define TT_MAC_LANGID_MALAGASY                     93\r\n#define TT_MAC_LANGID_ESPERANTO                    94\r\n#define TT_MAC_LANGID_WELSH                       128\r\n#define TT_MAC_LANGID_BASQUE                      129\r\n#define TT_MAC_LANGID_CATALAN                     130\r\n#define TT_MAC_LANGID_LATIN                       131\r\n#define TT_MAC_LANGID_QUECHUA                     132\r\n#define TT_MAC_LANGID_GUARANI                     133\r\n#define TT_MAC_LANGID_AYMARA                      134\r\n#define TT_MAC_LANGID_TATAR                       135\r\n#define TT_MAC_LANGID_UIGHUR                      136\r\n#define TT_MAC_LANGID_DZONGKHA                    137\r\n#define TT_MAC_LANGID_JAVANESE                    138\r\n#define TT_MAC_LANGID_SUNDANESE                   139\r\n\r\n\r\n#if 0  /* these seem to be errors that have been dropped */\r\n\r\n#define TT_MAC_LANGID_SCOTTISH_GAELIC             140\r\n#define TT_MAC_LANGID_IRISH_GAELIC                141\r\n\r\n#endif\r\n\r\n\r\n  /* The following codes are new as of 2000-03-10 */\r\n#define TT_MAC_LANGID_GALICIAN                    140\r\n#define TT_MAC_LANGID_AFRIKAANS                   141\r\n#define TT_MAC_LANGID_BRETON                      142\r\n#define TT_MAC_LANGID_INUKTITUT                   143\r\n#define TT_MAC_LANGID_SCOTTISH_GAELIC             144\r\n#define TT_MAC_LANGID_MANX_GAELIC                 145\r\n#define TT_MAC_LANGID_IRISH_GAELIC                146\r\n#define TT_MAC_LANGID_TONGAN                      147\r\n#define TT_MAC_LANGID_GREEK_POLYTONIC             148\r\n#define TT_MAC_LANGID_GREELANDIC                  149\r\n#define TT_MAC_LANGID_AZERBAIJANI_ROMAN_SCRIPT    150\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Possible values of the language identifier field in the name records  */\r\n  /* of the TTF `name' table if the `platform' identifier code is          */\r\n  /* TT_PLATFORM_MICROSOFT.                                                */\r\n  /*                                                                       */\r\n  /* The canonical source for the MS assigned LCID's (seems to) be at      */\r\n  /*                                                                       */\r\n  /*   http://www.microsoft.com/globaldev/reference/lcid-all.mspx          */\r\n  /*                                                                       */\r\n  /* It used to be at various places, among them                           */\r\n  /*                                                                       */\r\n  /*   http://www.microsoft.com/typography/OTSPEC/lcid-cp.txt              */\r\n  /*   http://www.microsoft.com/globaldev/reference/loclanghome.asp        */\r\n  /*   http://support.microsoft.com/support/kb/articles/Q224/8/04.ASP      */\r\n  /*   http://msdn.microsoft.com/library/en-us/passport25/                 */\r\n  /*           NET_Passport_VBScript_Documentation/Single_Sign_In/         */\r\n  /*           Advanced_Single_Sign_In/Localization_and_LCIDs.asp          */\r\n  /*                                                                       */\r\n  /* Hopefully, it seems now that the Globaldev site prevails...           */\r\n  /*                                   (updated by Antoine, 2004-02-17)    */\r\n\r\n#define TT_MS_LANGID_ARABIC_GENERAL                    0x0001\r\n#define TT_MS_LANGID_ARABIC_SAUDI_ARABIA               0x0401\r\n#define TT_MS_LANGID_ARABIC_IRAQ                       0x0801\r\n#define TT_MS_LANGID_ARABIC_EGYPT                      0x0c01\r\n#define TT_MS_LANGID_ARABIC_LIBYA                      0x1001\r\n#define TT_MS_LANGID_ARABIC_ALGERIA                    0x1401\r\n#define TT_MS_LANGID_ARABIC_MOROCCO                    0x1801\r\n#define TT_MS_LANGID_ARABIC_TUNISIA                    0x1c01\r\n#define TT_MS_LANGID_ARABIC_OMAN                       0x2001\r\n#define TT_MS_LANGID_ARABIC_YEMEN                      0x2401\r\n#define TT_MS_LANGID_ARABIC_SYRIA                      0x2801\r\n#define TT_MS_LANGID_ARABIC_JORDAN                     0x2c01\r\n#define TT_MS_LANGID_ARABIC_LEBANON                    0x3001\r\n#define TT_MS_LANGID_ARABIC_KUWAIT                     0x3401\r\n#define TT_MS_LANGID_ARABIC_UAE                        0x3801\r\n#define TT_MS_LANGID_ARABIC_BAHRAIN                    0x3c01\r\n#define TT_MS_LANGID_ARABIC_QATAR                      0x4001\r\n#define TT_MS_LANGID_BULGARIAN_BULGARIA                0x0402\r\n#define TT_MS_LANGID_CATALAN_SPAIN                     0x0403\r\n#define TT_MS_LANGID_CHINESE_GENERAL                   0x0004\r\n#define TT_MS_LANGID_CHINESE_TAIWAN                    0x0404\r\n#define TT_MS_LANGID_CHINESE_PRC                       0x0804\r\n#define TT_MS_LANGID_CHINESE_HONG_KONG                 0x0c04\r\n#define TT_MS_LANGID_CHINESE_SINGAPORE                 0x1004\r\n\r\n#if 1  /* this looks like the correct value */\r\n#define TT_MS_LANGID_CHINESE_MACAU                     0x1404\r\n#else  /* but beware, Microsoft may change its mind...\r\n          the most recent Word reference has the following: */\r\n#define TT_MS_LANGID_CHINESE_MACAU  TT_MS_LANGID_CHINESE_HONG_KONG\r\n#endif\r\n\r\n#if 0  /* used only with .NET `cultures'; commented out */\r\n#define TT_MS_LANGID_CHINESE_TRADITIONAL               0x7C04\r\n#endif\r\n\r\n#define TT_MS_LANGID_CZECH_CZECH_REPUBLIC              0x0405\r\n#define TT_MS_LANGID_DANISH_DENMARK                    0x0406\r\n#define TT_MS_LANGID_GERMAN_GERMANY                    0x0407\r\n#define TT_MS_LANGID_GERMAN_SWITZERLAND                0x0807\r\n#define TT_MS_LANGID_GERMAN_AUSTRIA                    0x0c07\r\n#define TT_MS_LANGID_GERMAN_LUXEMBOURG                 0x1007\r\n#define TT_MS_LANGID_GERMAN_LIECHTENSTEI               0x1407\r\n#define TT_MS_LANGID_GREEK_GREECE                      0x0408\r\n\r\n  /* don't ask what this one means... It is commented out currently. */\r\n#if 0\r\n#define TT_MS_LANGID_GREEK_GREECE2                     0x2008\r\n#endif\r\n\r\n#define TT_MS_LANGID_ENGLISH_GENERAL                   0x0009\r\n#define TT_MS_LANGID_ENGLISH_UNITED_STATES             0x0409\r\n#define TT_MS_LANGID_ENGLISH_UNITED_KINGDOM            0x0809\r\n#define TT_MS_LANGID_ENGLISH_AUSTRALIA                 0x0c09\r\n#define TT_MS_LANGID_ENGLISH_CANADA                    0x1009\r\n#define TT_MS_LANGID_ENGLISH_NEW_ZEALAND               0x1409\r\n#define TT_MS_LANGID_ENGLISH_IRELAND                   0x1809\r\n#define TT_MS_LANGID_ENGLISH_SOUTH_AFRICA              0x1c09\r\n#define TT_MS_LANGID_ENGLISH_JAMAICA                   0x2009\r\n#define TT_MS_LANGID_ENGLISH_CARIBBEAN                 0x2409\r\n#define TT_MS_LANGID_ENGLISH_BELIZE                    0x2809\r\n#define TT_MS_LANGID_ENGLISH_TRINIDAD                  0x2c09\r\n#define TT_MS_LANGID_ENGLISH_ZIMBABWE                  0x3009\r\n#define TT_MS_LANGID_ENGLISH_PHILIPPINES               0x3409\r\n#define TT_MS_LANGID_ENGLISH_INDONESIA                 0x3809\r\n#define TT_MS_LANGID_ENGLISH_HONG_KONG                 0x3c09\r\n#define TT_MS_LANGID_ENGLISH_INDIA                     0x4009\r\n#define TT_MS_LANGID_ENGLISH_MALAYSIA                  0x4409\r\n#define TT_MS_LANGID_ENGLISH_SINGAPORE                 0x4809\r\n#define TT_MS_LANGID_SPANISH_SPAIN_TRADITIONAL_SORT    0x040a\r\n#define TT_MS_LANGID_SPANISH_MEXICO                    0x080a\r\n#define TT_MS_LANGID_SPANISH_SPAIN_INTERNATIONAL_SORT  0x0c0a\r\n#define TT_MS_LANGID_SPANISH_GUATEMALA                 0x100a\r\n#define TT_MS_LANGID_SPANISH_COSTA_RICA                0x140a\r\n#define TT_MS_LANGID_SPANISH_PANAMA                    0x180a\r\n#define TT_MS_LANGID_SPANISH_DOMINICAN_REPUBLIC        0x1c0a\r\n#define TT_MS_LANGID_SPANISH_VENEZUELA                 0x200a\r\n#define TT_MS_LANGID_SPANISH_COLOMBIA                  0x240a\r\n#define TT_MS_LANGID_SPANISH_PERU                      0x280a\r\n#define TT_MS_LANGID_SPANISH_ARGENTINA                 0x2c0a\r\n#define TT_MS_LANGID_SPANISH_ECUADOR                   0x300a\r\n#define TT_MS_LANGID_SPANISH_CHILE                     0x340a\r\n#define TT_MS_LANGID_SPANISH_URUGUAY                   0x380a\r\n#define TT_MS_LANGID_SPANISH_PARAGUAY                  0x3c0a\r\n#define TT_MS_LANGID_SPANISH_BOLIVIA                   0x400a\r\n#define TT_MS_LANGID_SPANISH_EL_SALVADOR               0x440a\r\n#define TT_MS_LANGID_SPANISH_HONDURAS                  0x480a\r\n#define TT_MS_LANGID_SPANISH_NICARAGUA                 0x4c0a\r\n#define TT_MS_LANGID_SPANISH_PUERTO_RICO               0x500a\r\n#define TT_MS_LANGID_SPANISH_UNITED_STATES             0x540a\r\n  /* The following ID blatantly violate MS specs by using a */\r\n  /* sublanguage > 0x1F.                                    */\r\n#define TT_MS_LANGID_SPANISH_LATIN_AMERICA             0xE40aU\r\n#define TT_MS_LANGID_FINNISH_FINLAND                   0x040b\r\n#define TT_MS_LANGID_FRENCH_FRANCE                     0x040c\r\n#define TT_MS_LANGID_FRENCH_BELGIUM                    0x080c\r\n#define TT_MS_LANGID_FRENCH_CANADA                     0x0c0c\r\n#define TT_MS_LANGID_FRENCH_SWITZERLAND                0x100c\r\n#define TT_MS_LANGID_FRENCH_LUXEMBOURG                 0x140c\r\n#define TT_MS_LANGID_FRENCH_MONACO                     0x180c\r\n#define TT_MS_LANGID_FRENCH_WEST_INDIES                0x1c0c\r\n#define TT_MS_LANGID_FRENCH_REUNION                    0x200c\r\n#define TT_MS_LANGID_FRENCH_CONGO                      0x240c\r\n  /* which was formerly: */\r\n#define TT_MS_LANGID_FRENCH_ZAIRE  TT_MS_LANGID_FRENCH_CONGO\r\n#define TT_MS_LANGID_FRENCH_SENEGAL                    0x280c\r\n#define TT_MS_LANGID_FRENCH_CAMEROON                   0x2c0c\r\n#define TT_MS_LANGID_FRENCH_COTE_D_IVOIRE              0x300c\r\n#define TT_MS_LANGID_FRENCH_MALI                       0x340c\r\n#define TT_MS_LANGID_FRENCH_MOROCCO                    0x380c\r\n#define TT_MS_LANGID_FRENCH_HAITI                      0x3c0c\r\n  /* and another violation of the spec (see 0xE40aU) */\r\n#define TT_MS_LANGID_FRENCH_NORTH_AFRICA               0xE40cU\r\n#define TT_MS_LANGID_HEBREW_ISRAEL                     0x040d\r\n#define TT_MS_LANGID_HUNGARIAN_HUNGARY                 0x040e\r\n#define TT_MS_LANGID_ICELANDIC_ICELAND                 0x040f\r\n#define TT_MS_LANGID_ITALIAN_ITALY                     0x0410\r\n#define TT_MS_LANGID_ITALIAN_SWITZERLAND               0x0810\r\n#define TT_MS_LANGID_JAPANESE_JAPAN                    0x0411\r\n#define TT_MS_LANGID_KOREAN_EXTENDED_WANSUNG_KOREA     0x0412\r\n#define TT_MS_LANGID_KOREAN_JOHAB_KOREA                0x0812\r\n#define TT_MS_LANGID_DUTCH_NETHERLANDS                 0x0413\r\n#define TT_MS_LANGID_DUTCH_BELGIUM                     0x0813\r\n#define TT_MS_LANGID_NORWEGIAN_NORWAY_BOKMAL           0x0414\r\n#define TT_MS_LANGID_NORWEGIAN_NORWAY_NYNORSK          0x0814\r\n#define TT_MS_LANGID_POLISH_POLAND                     0x0415\r\n#define TT_MS_LANGID_PORTUGUESE_BRAZIL                 0x0416\r\n#define TT_MS_LANGID_PORTUGUESE_PORTUGAL               0x0816\r\n#define TT_MS_LANGID_RHAETO_ROMANIC_SWITZERLAND        0x0417\r\n#define TT_MS_LANGID_ROMANIAN_ROMANIA                  0x0418\r\n#define TT_MS_LANGID_MOLDAVIAN_MOLDAVIA                0x0818\r\n#define TT_MS_LANGID_RUSSIAN_RUSSIA                    0x0419\r\n#define TT_MS_LANGID_RUSSIAN_MOLDAVIA                  0x0819\r\n#define TT_MS_LANGID_CROATIAN_CROATIA                  0x041a\r\n#define TT_MS_LANGID_SERBIAN_SERBIA_LATIN              0x081a\r\n#define TT_MS_LANGID_SERBIAN_SERBIA_CYRILLIC           0x0c1a\r\n\r\n#if 0  /* this used to be this value, but it looks like we were wrong */\r\n#define TT_MS_LANGID_BOSNIAN_BOSNIA_HERZEGOVINA        0x101a\r\n#else  /* current sources say */\r\n#define TT_MS_LANGID_CROATIAN_BOSNIA_HERZEGOVINA       0x101a\r\n#define TT_MS_LANGID_BOSNIAN_BOSNIA_HERZEGOVINA        0x141a\r\n       /* and XPsp2 Platform SDK added (2004-07-26) */\r\n       /* Names are shortened to be significant within 40 chars. */\r\n#define TT_MS_LANGID_SERBIAN_BOSNIA_HERZ_LATIN         0x181a\r\n#define TT_MS_LANGID_SERBIAN_BOSNIA_HERZ_CYRILLIC      0x181a\r\n#endif\r\n\r\n#define TT_MS_LANGID_SLOVAK_SLOVAKIA                   0x041b\r\n#define TT_MS_LANGID_ALBANIAN_ALBANIA                  0x041c\r\n#define TT_MS_LANGID_SWEDISH_SWEDEN                    0x041d\r\n#define TT_MS_LANGID_SWEDISH_FINLAND                   0x081d\r\n#define TT_MS_LANGID_THAI_THAILAND                     0x041e\r\n#define TT_MS_LANGID_TURKISH_TURKEY                    0x041f\r\n#define TT_MS_LANGID_URDU_PAKISTAN                     0x0420\r\n#define TT_MS_LANGID_URDU_INDIA                        0x0820\r\n#define TT_MS_LANGID_INDONESIAN_INDONESIA              0x0421\r\n#define TT_MS_LANGID_UKRAINIAN_UKRAINE                 0x0422\r\n#define TT_MS_LANGID_BELARUSIAN_BELARUS                0x0423\r\n#define TT_MS_LANGID_SLOVENE_SLOVENIA                  0x0424\r\n#define TT_MS_LANGID_ESTONIAN_ESTONIA                  0x0425\r\n#define TT_MS_LANGID_LATVIAN_LATVIA                    0x0426\r\n#define TT_MS_LANGID_LITHUANIAN_LITHUANIA              0x0427\r\n#define TT_MS_LANGID_CLASSIC_LITHUANIAN_LITHUANIA      0x0827\r\n#define TT_MS_LANGID_TAJIK_TAJIKISTAN                  0x0428\r\n#define TT_MS_LANGID_FARSI_IRAN                        0x0429\r\n#define TT_MS_LANGID_VIETNAMESE_VIET_NAM               0x042a\r\n#define TT_MS_LANGID_ARMENIAN_ARMENIA                  0x042b\r\n#define TT_MS_LANGID_AZERI_AZERBAIJAN_LATIN            0x042c\r\n#define TT_MS_LANGID_AZERI_AZERBAIJAN_CYRILLIC         0x082c\r\n#define TT_MS_LANGID_BASQUE_SPAIN                      0x042d\r\n#define TT_MS_LANGID_SORBIAN_GERMANY                   0x042e\r\n#define TT_MS_LANGID_MACEDONIAN_MACEDONIA              0x042f\r\n#define TT_MS_LANGID_SUTU_SOUTH_AFRICA                 0x0430\r\n#define TT_MS_LANGID_TSONGA_SOUTH_AFRICA               0x0431\r\n#define TT_MS_LANGID_TSWANA_SOUTH_AFRICA               0x0432\r\n#define TT_MS_LANGID_VENDA_SOUTH_AFRICA                0x0433\r\n#define TT_MS_LANGID_XHOSA_SOUTH_AFRICA                0x0434\r\n#define TT_MS_LANGID_ZULU_SOUTH_AFRICA                 0x0435\r\n#define TT_MS_LANGID_AFRIKAANS_SOUTH_AFRICA            0x0436\r\n#define TT_MS_LANGID_GEORGIAN_GEORGIA                  0x0437\r\n#define TT_MS_LANGID_FAEROESE_FAEROE_ISLANDS           0x0438\r\n#define TT_MS_LANGID_HINDI_INDIA                       0x0439\r\n#define TT_MS_LANGID_MALTESE_MALTA                     0x043a\r\n  /* Added by XPsp2 Platform SDK (2004-07-26) */\r\n#define TT_MS_LANGID_SAMI_NORTHERN_NORWAY              0x043b\r\n#define TT_MS_LANGID_SAMI_NORTHERN_SWEDEN              0x083b\r\n#define TT_MS_LANGID_SAMI_NORTHERN_FINLAND             0x0C3b\r\n#define TT_MS_LANGID_SAMI_LULE_NORWAY                  0x103b\r\n#define TT_MS_LANGID_SAMI_LULE_SWEDEN                  0x143b\r\n#define TT_MS_LANGID_SAMI_SOUTHERN_NORWAY              0x183b\r\n#define TT_MS_LANGID_SAMI_SOUTHERN_SWEDEN              0x1C3b\r\n#define TT_MS_LANGID_SAMI_SKOLT_FINLAND                0x203b\r\n#define TT_MS_LANGID_SAMI_INARI_FINLAND                0x243b\r\n  /* ... and we also keep our old identifier... */\r\n#define TT_MS_LANGID_SAAMI_LAPONIA                     0x043b\r\n\r\n#if 0 /* this seems to be a previous inversion */\r\n#define TT_MS_LANGID_IRISH_GAELIC_IRELAND              0x043c\r\n#define TT_MS_LANGID_SCOTTISH_GAELIC_UNITED_KINGDOM    0x083c\r\n#else\r\n#define TT_MS_LANGID_SCOTTISH_GAELIC_UNITED_KINGDOM    0x083c\r\n#define TT_MS_LANGID_IRISH_GAELIC_IRELAND              0x043c\r\n#endif\r\n\r\n#define TT_MS_LANGID_YIDDISH_GERMANY                   0x043d\r\n#define TT_MS_LANGID_MALAY_MALAYSIA                    0x043e\r\n#define TT_MS_LANGID_MALAY_BRUNEI_DARUSSALAM           0x083e\r\n#define TT_MS_LANGID_KAZAK_KAZAKSTAN                   0x043f\r\n#define TT_MS_LANGID_KIRGHIZ_KIRGHIZSTAN /* Cyrillic*/ 0x0440\r\n  /* alias declared in Windows 2000 */\r\n#define TT_MS_LANGID_KIRGHIZ_KIRGHIZ_REPUBLIC \\\r\n          TT_MS_LANGID_KIRGHIZ_KIRGHIZSTAN\r\n\r\n#define TT_MS_LANGID_SWAHILI_KENYA                     0x0441\r\n#define TT_MS_LANGID_TURKMEN_TURKMENISTAN              0x0442\r\n#define TT_MS_LANGID_UZBEK_UZBEKISTAN_LATIN            0x0443\r\n#define TT_MS_LANGID_UZBEK_UZBEKISTAN_CYRILLIC         0x0843\r\n#define TT_MS_LANGID_TATAR_TATARSTAN                   0x0444\r\n#define TT_MS_LANGID_BENGALI_INDIA                     0x0445\r\n#define TT_MS_LANGID_BENGALI_BANGLADESH                0x0845\r\n#define TT_MS_LANGID_PUNJABI_INDIA                     0x0446\r\n#define TT_MS_LANGID_PUNJABI_ARABIC_PAKISTAN           0x0846\r\n#define TT_MS_LANGID_GUJARATI_INDIA                    0x0447\r\n#define TT_MS_LANGID_ORIYA_INDIA                       0x0448\r\n#define TT_MS_LANGID_TAMIL_INDIA                       0x0449\r\n#define TT_MS_LANGID_TELUGU_INDIA                      0x044a\r\n#define TT_MS_LANGID_KANNADA_INDIA                     0x044b\r\n#define TT_MS_LANGID_MALAYALAM_INDIA                   0x044c\r\n#define TT_MS_LANGID_ASSAMESE_INDIA                    0x044d\r\n#define TT_MS_LANGID_MARATHI_INDIA                     0x044e\r\n#define TT_MS_LANGID_SANSKRIT_INDIA                    0x044f\r\n#define TT_MS_LANGID_MONGOLIAN_MONGOLIA /* Cyrillic */ 0x0450\r\n#define TT_MS_LANGID_MONGOLIAN_MONGOLIA_MONGOLIAN      0x0850\r\n#define TT_MS_LANGID_TIBETAN_CHINA                     0x0451\r\n  /* Don't use the next constant!  It has            */\r\n  /*   (1) the wrong spelling (Dzonghka)             */\r\n  /*   (2) Microsoft doesn't officially define it -- */\r\n  /*       at least it is not in the List of Local   */\r\n  /*       ID Values.                                */\r\n  /*   (3) Dzongkha is not the same language as      */\r\n  /*       Tibetan, so merging it is wrong anyway.   */\r\n  /*                                                 */\r\n  /* TT_MS_LANGID_TIBETAN_BHUTAN is correct, BTW.    */\r\n#define TT_MS_LANGID_DZONGHKA_BHUTAN                   0x0851\r\n\r\n#if 0\r\n  /* the following used to be defined */\r\n#define TT_MS_LANGID_TIBETAN_BHUTAN                    0x0451\r\n  /* ... but it was changed; */\r\n#else\r\n  /* So we will continue to #define it, but with the correct value */\r\n#define TT_MS_LANGID_TIBETAN_BHUTAN   TT_MS_LANGID_DZONGHKA_BHUTAN\r\n#endif\r\n\r\n#define TT_MS_LANGID_WELSH_WALES                       0x0452\r\n#define TT_MS_LANGID_KHMER_CAMBODIA                    0x0453\r\n#define TT_MS_LANGID_LAO_LAOS                          0x0454\r\n#define TT_MS_LANGID_BURMESE_MYANMAR                   0x0455\r\n#define TT_MS_LANGID_GALICIAN_SPAIN                    0x0456\r\n#define TT_MS_LANGID_KONKANI_INDIA                     0x0457\r\n#define TT_MS_LANGID_MANIPURI_INDIA  /* Bengali */     0x0458\r\n#define TT_MS_LANGID_SINDHI_INDIA /* Arabic */         0x0459\r\n#define TT_MS_LANGID_SINDHI_PAKISTAN                   0x0859\r\n  /* Missing a LCID for Sindhi in Devanagari script */\r\n#define TT_MS_LANGID_SYRIAC_SYRIA                      0x045a\r\n#define TT_MS_LANGID_SINHALESE_SRI_LANKA               0x045b\r\n#define TT_MS_LANGID_CHEROKEE_UNITED_STATES            0x045c\r\n#define TT_MS_LANGID_INUKTITUT_CANADA                  0x045d\r\n#define TT_MS_LANGID_AMHARIC_ETHIOPIA                  0x045e\r\n#define TT_MS_LANGID_TAMAZIGHT_MOROCCO /* Arabic */    0x045f\r\n#define TT_MS_LANGID_TAMAZIGHT_MOROCCO_LATIN           0x085f\r\n  /* Missing a LCID for Tifinagh script */\r\n#define TT_MS_LANGID_KASHMIRI_PAKISTAN /* Arabic */    0x0460\r\n  /* Spelled this way by XPsp2 Platform SDK (2004-07-26) */\r\n  /* script is yet unclear... might be Arabic, Nagari or Sharada */\r\n#define TT_MS_LANGID_KASHMIRI_SASIA                    0x0860\r\n  /* ... and aliased (by MS) for compatibility reasons. */\r\n#define TT_MS_LANGID_KASHMIRI_INDIA TT_MS_LANGID_KASHMIRI_SASIA\r\n#define TT_MS_LANGID_NEPALI_NEPAL                      0x0461\r\n#define TT_MS_LANGID_NEPALI_INDIA                      0x0861\r\n#define TT_MS_LANGID_FRISIAN_NETHERLANDS               0x0462\r\n#define TT_MS_LANGID_PASHTO_AFGHANISTAN                0x0463\r\n#define TT_MS_LANGID_FILIPINO_PHILIPPINES              0x0464\r\n#define TT_MS_LANGID_DHIVEHI_MALDIVES                  0x0465\r\n  /* alias declared in Windows 2000 */\r\n#define TT_MS_LANGID_DIVEHI_MALDIVES  TT_MS_LANGID_DHIVEHI_MALDIVES\r\n#define TT_MS_LANGID_EDO_NIGERIA                       0x0466\r\n#define TT_MS_LANGID_FULFULDE_NIGERIA                  0x0467\r\n#define TT_MS_LANGID_HAUSA_NIGERIA                     0x0468\r\n#define TT_MS_LANGID_IBIBIO_NIGERIA                    0x0469\r\n#define TT_MS_LANGID_YORUBA_NIGERIA                    0x046a\r\n#define TT_MS_LANGID_QUECHUA_BOLIVIA                   0x046b\r\n#define TT_MS_LANGID_QUECHUA_ECUADOR                   0x086b\r\n#define TT_MS_LANGID_QUECHUA_PERU                      0x0c6b\r\n#define TT_MS_LANGID_SEPEDI_SOUTH_AFRICA               0x046c\r\n  /* Also spelled by XPsp2 Platform SDK (2004-07-26) */\r\n#define TT_MS_LANGID_SOTHO_SOUTHERN_SOUTH_AFRICA \\\r\n          TT_MS_LANGID_SEPEDI_SOUTH_AFRICA\r\n  /* language codes 0x046d, 0x046e and 0x046f are (still) unknown. */\r\n#define TT_MS_LANGID_IGBO_NIGERIA                      0x0470\r\n#define TT_MS_LANGID_KANURI_NIGERIA                    0x0471\r\n#define TT_MS_LANGID_OROMO_ETHIOPIA                    0x0472\r\n#define TT_MS_LANGID_TIGRIGNA_ETHIOPIA                 0x0473\r\n#define TT_MS_LANGID_TIGRIGNA_ERYTHREA                 0x0873\r\n  /* also spelled in the `Passport SDK' list as: */\r\n#define TT_MS_LANGID_TIGRIGNA_ERYTREA  TT_MS_LANGID_TIGRIGNA_ERYTHREA\r\n#define TT_MS_LANGID_GUARANI_PARAGUAY                  0x0474\r\n#define TT_MS_LANGID_HAWAIIAN_UNITED_STATES            0x0475\r\n#define TT_MS_LANGID_LATIN                             0x0476\r\n#define TT_MS_LANGID_SOMALI_SOMALIA                    0x0477\r\n  /* Note: Yi does not have a (proper) ISO 639-2 code, since it is mostly */\r\n  /*       not written (but OTOH the peculiar writing system is worth     */\r\n  /*       studying).                                                     */\r\n#define TT_MS_LANGID_YI_CHINA                          0x0478\r\n#define TT_MS_LANGID_PAPIAMENTU_NETHERLANDS_ANTILLES   0x0479\r\n  /* language codes from 0x047a to 0x047f are (still) unknown. */\r\n#define TT_MS_LANGID_UIGHUR_CHINA                      0x0480\r\n#define TT_MS_LANGID_MAORI_NEW_ZEALAND                 0x0481\r\n\r\n#if 0  /* not deemed useful for fonts */\r\n#define TT_MS_LANGID_HUMAN_INTERFACE_DEVICE            0x04ff\r\n#endif\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Possible values of the `name' identifier field in the name records of */\r\n  /* the TTF `name' table.  These values are platform independent.         */\r\n  /*                                                                       */\r\n#define TT_NAME_ID_COPYRIGHT            0\r\n#define TT_NAME_ID_FONT_FAMILY          1\r\n#define TT_NAME_ID_FONT_SUBFAMILY       2\r\n#define TT_NAME_ID_UNIQUE_ID            3\r\n#define TT_NAME_ID_FULL_NAME            4\r\n#define TT_NAME_ID_VERSION_STRING       5\r\n#define TT_NAME_ID_PS_NAME              6\r\n#define TT_NAME_ID_TRADEMARK            7\r\n\r\n  /* the following values are from the OpenType spec */\r\n#define TT_NAME_ID_MANUFACTURER         8\r\n#define TT_NAME_ID_DESIGNER             9\r\n#define TT_NAME_ID_DESCRIPTION          10\r\n#define TT_NAME_ID_VENDOR_URL           11\r\n#define TT_NAME_ID_DESIGNER_URL         12\r\n#define TT_NAME_ID_LICENSE              13\r\n#define TT_NAME_ID_LICENSE_URL          14\r\n  /* number 15 is reserved */\r\n#define TT_NAME_ID_PREFERRED_FAMILY     16\r\n#define TT_NAME_ID_PREFERRED_SUBFAMILY  17\r\n#define TT_NAME_ID_MAC_FULL_NAME        18\r\n\r\n  /* The following code is new as of 2000-01-21 */\r\n#define TT_NAME_ID_SAMPLE_TEXT          19\r\n\r\n  /* This is new in OpenType 1.3 */\r\n#define TT_NAME_ID_CID_FINDFONT_NAME    20\r\n\r\n  /* This is new in OpenType 1.5 */\r\n#define TT_NAME_ID_WWS_FAMILY           21\r\n#define TT_NAME_ID_WWS_SUBFAMILY        22\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Bit mask values for the Unicode Ranges from the TTF `OS2 ' table.     */\r\n  /*                                                                       */\r\n  /* Updated 08-Nov-2008.                                                  */\r\n  /*                                                                       */\r\n\r\n  /* Bit  0   Basic Latin */\r\n#define TT_UCR_BASIC_LATIN                     (1L <<  0) /* U+0020-U+007E */\r\n  /* Bit  1   C1 Controls and Latin-1 Supplement */\r\n#define TT_UCR_LATIN1_SUPPLEMENT               (1L <<  1) /* U+0080-U+00FF */\r\n  /* Bit  2   Latin Extended-A */\r\n#define TT_UCR_LATIN_EXTENDED_A                (1L <<  2) /* U+0100-U+017F */\r\n  /* Bit  3   Latin Extended-B */\r\n#define TT_UCR_LATIN_EXTENDED_B                (1L <<  3) /* U+0180-U+024F */\r\n  /* Bit  4   IPA Extensions                 */\r\n  /*          Phonetic Extensions            */\r\n  /*          Phonetic Extensions Supplement */\r\n#define TT_UCR_IPA_EXTENSIONS                  (1L <<  4) /* U+0250-U+02AF */\r\n                                                          /* U+1D00-U+1D7F */\r\n                                                          /* U+1D80-U+1DBF */\r\n  /* Bit  5   Spacing Modifier Letters */\r\n  /*          Modifier Tone Letters    */\r\n#define TT_UCR_SPACING_MODIFIER                (1L <<  5) /* U+02B0-U+02FF */\r\n                                                          /* U+A700-U+A71F */\r\n  /* Bit  6   Combining Diacritical Marks            */\r\n  /*          Combining Diacritical Marks Supplement */\r\n#define TT_UCR_COMBINING_DIACRITICS            (1L <<  6) /* U+0300-U+036F */\r\n                                                          /* U+1DC0-U+1DFF */\r\n  /* Bit  7   Greek and Coptic */\r\n#define TT_UCR_GREEK                           (1L <<  7) /* U+0370-U+03FF */\r\n  /* Bit  8   Coptic */\r\n#define TT_UCR_COPTIC                          (1L <<  8) /* U+2C80-U+2CFF */\r\n  /* Bit  9   Cyrillic            */\r\n  /*          Cyrillic Supplement */\r\n  /*          Cyrillic Extended-A */\r\n  /*          Cyrillic Extended-B */\r\n#define TT_UCR_CYRILLIC                        (1L <<  9) /* U+0400-U+04FF */\r\n                                                          /* U+0500-U+052F */\r\n                                                          /* U+2DE0-U+2DFF */\r\n                                                          /* U+A640-U+A69F */\r\n  /* Bit 10   Armenian */\r\n#define TT_UCR_ARMENIAN                        (1L << 10) /* U+0530-U+058F */\r\n  /* Bit 11   Hebrew */\r\n#define TT_UCR_HEBREW                          (1L << 11) /* U+0590-U+05FF */\r\n  /* Bit 12   Vai */\r\n#define TT_UCR_VAI                             (1L << 12) /* U+A500-U+A63F */\r\n  /* Bit 13   Arabic            */\r\n  /*          Arabic Supplement */\r\n#define TT_UCR_ARABIC                          (1L << 13) /* U+0600-U+06FF */\r\n                                                          /* U+0750-U+077F */\r\n  /* Bit 14   NKo */\r\n#define TT_UCR_NKO                             (1L << 14) /* U+07C0-U+07FF */\r\n  /* Bit 15   Devanagari */\r\n#define TT_UCR_DEVANAGARI                      (1L << 15) /* U+0900-U+097F */\r\n  /* Bit 16   Bengali */\r\n#define TT_UCR_BENGALI                         (1L << 16) /* U+0980-U+09FF */\r\n  /* Bit 17   Gurmukhi */\r\n#define TT_UCR_GURMUKHI                        (1L << 17) /* U+0A00-U+0A7F */\r\n  /* Bit 18   Gujarati */\r\n#define TT_UCR_GUJARATI                        (1L << 18) /* U+0A80-U+0AFF */\r\n  /* Bit 19   Oriya */\r\n#define TT_UCR_ORIYA                           (1L << 19) /* U+0B00-U+0B7F */\r\n  /* Bit 20   Tamil */\r\n#define TT_UCR_TAMIL                           (1L << 20) /* U+0B80-U+0BFF */\r\n  /* Bit 21   Telugu */\r\n#define TT_UCR_TELUGU                          (1L << 21) /* U+0C00-U+0C7F */\r\n  /* Bit 22   Kannada */\r\n#define TT_UCR_KANNADA                         (1L << 22) /* U+0C80-U+0CFF */\r\n  /* Bit 23   Malayalam */\r\n#define TT_UCR_MALAYALAM                       (1L << 23) /* U+0D00-U+0D7F */\r\n  /* Bit 24   Thai */\r\n#define TT_UCR_THAI                            (1L << 24) /* U+0E00-U+0E7F */\r\n  /* Bit 25   Lao */\r\n#define TT_UCR_LAO                             (1L << 25) /* U+0E80-U+0EFF */\r\n  /* Bit 26   Georgian            */\r\n  /*          Georgian Supplement */\r\n#define TT_UCR_GEORGIAN                        (1L << 26) /* U+10A0-U+10FF */\r\n                                                          /* U+2D00-U+2D2F */\r\n  /* Bit 27   Balinese */\r\n#define TT_UCR_BALINESE                        (1L << 27) /* U+1B00-U+1B7F */\r\n  /* Bit 28   Hangul Jamo */\r\n#define TT_UCR_HANGUL_JAMO                     (1L << 28) /* U+1100-U+11FF */\r\n  /* Bit 29   Latin Extended Additional */\r\n  /*          Latin Extended-C          */\r\n  /*          Latin Extended-D          */\r\n#define TT_UCR_LATIN_EXTENDED_ADDITIONAL       (1L << 29) /* U+1E00-U+1EFF */\r\n                                                          /* U+2C60-U+2C7F */\r\n                                                          /* U+A720-U+A7FF */\r\n  /* Bit 30   Greek Extended */\r\n#define TT_UCR_GREEK_EXTENDED                  (1L << 30) /* U+1F00-U+1FFF */\r\n  /* Bit 31   General Punctuation      */\r\n  /*          Supplemental Punctuation */\r\n#define TT_UCR_GENERAL_PUNCTUATION             (1L << 31) /* U+2000-U+206F */\r\n                                                          /* U+2E00-U+2E7F */\r\n  /* Bit 32   Superscripts And Subscripts */\r\n#define TT_UCR_SUPERSCRIPTS_SUBSCRIPTS         (1L <<  0) /* U+2070-U+209F */\r\n  /* Bit 33   Currency Symbols */\r\n#define TT_UCR_CURRENCY_SYMBOLS                (1L <<  1) /* U+20A0-U+20CF */\r\n  /* Bit 34   Combining Diacritical Marks For Symbols */\r\n#define TT_UCR_COMBINING_DIACRITICS_SYMB       (1L <<  2) /* U+20D0-U+20FF */\r\n  /* Bit 35   Letterlike Symbols */\r\n#define TT_UCR_LETTERLIKE_SYMBOLS              (1L <<  3) /* U+2100-U+214F */\r\n  /* Bit 36   Number Forms */\r\n#define TT_UCR_NUMBER_FORMS                    (1L <<  4) /* U+2150-U+218F */\r\n  /* Bit 37   Arrows                           */\r\n  /*          Supplemental Arrows-A            */\r\n  /*          Supplemental Arrows-B            */\r\n  /*          Miscellaneous Symbols and Arrows */\r\n#define TT_UCR_ARROWS                          (1L <<  5) /* U+2190-U+21FF */\r\n                                                          /* U+27F0-U+27FF */\r\n                                                          /* U+2900-U+297F */\r\n                                                          /* U+2B00-U+2BFF */\r\n  /* Bit 38   Mathematical Operators               */\r\n  /*          Supplemental Mathematical Operators  */\r\n  /*          Miscellaneous Mathematical Symbols-A */\r\n  /*          Miscellaneous Mathematical Symbols-B */\r\n#define TT_UCR_MATHEMATICAL_OPERATORS          (1L <<  6) /* U+2200-U+22FF */\r\n                                                          /* U+2A00-U+2AFF */\r\n                                                          /* U+27C0-U+27EF */\r\n                                                          /* U+2980-U+29FF */\r\n  /* Bit 39 Miscellaneous Technical */\r\n#define TT_UCR_MISCELLANEOUS_TECHNICAL         (1L <<  7) /* U+2300-U+23FF */\r\n  /* Bit 40   Control Pictures */\r\n#define TT_UCR_CONTROL_PICTURES                (1L <<  8) /* U+2400-U+243F */\r\n  /* Bit 41   Optical Character Recognition */\r\n#define TT_UCR_OCR                             (1L <<  9) /* U+2440-U+245F */\r\n  /* Bit 42   Enclosed Alphanumerics */\r\n#define TT_UCR_ENCLOSED_ALPHANUMERICS          (1L << 10) /* U+2460-U+24FF */\r\n  /* Bit 43   Box Drawing */\r\n#define TT_UCR_BOX_DRAWING                     (1L << 11) /* U+2500-U+257F */\r\n  /* Bit 44   Block Elements */\r\n#define TT_UCR_BLOCK_ELEMENTS                  (1L << 12) /* U+2580-U+259F */\r\n  /* Bit 45   Geometric Shapes */\r\n#define TT_UCR_GEOMETRIC_SHAPES                (1L << 13) /* U+25A0-U+25FF */\r\n  /* Bit 46   Miscellaneous Symbols */\r\n#define TT_UCR_MISCELLANEOUS_SYMBOLS           (1L << 14) /* U+2600-U+26FF */\r\n  /* Bit 47   Dingbats */\r\n#define TT_UCR_DINGBATS                        (1L << 15) /* U+2700-U+27BF */\r\n  /* Bit 48   CJK Symbols and Punctuation */\r\n#define TT_UCR_CJK_SYMBOLS                     (1L << 16) /* U+3000-U+303F */\r\n  /* Bit 49   Hiragana */\r\n#define TT_UCR_HIRAGANA                        (1L << 17) /* U+3040-U+309F */\r\n  /* Bit 50   Katakana                     */\r\n  /*          Katakana Phonetic Extensions */\r\n#define TT_UCR_KATAKANA                        (1L << 18) /* U+30A0-U+30FF */\r\n                                                          /* U+31F0-U+31FF */\r\n  /* Bit 51   Bopomofo          */\r\n  /*          Bopomofo Extended */\r\n#define TT_UCR_BOPOMOFO                        (1L << 19) /* U+3100-U+312F */\r\n                                                          /* U+31A0-U+31BF */\r\n  /* Bit 52   Hangul Compatibility Jamo */\r\n#define TT_UCR_HANGUL_COMPATIBILITY_JAMO       (1L << 20) /* U+3130-U+318F */\r\n  /* Bit 53   Phags-Pa */\r\n#define TT_UCR_CJK_MISC                        (1L << 21) /* U+A840-U+A87F */\r\n#define TT_UCR_KANBUN  TT_UCR_CJK_MISC /* deprecated */\r\n#define TT_UCR_PHAGSPA\r\n  /* Bit 54   Enclosed CJK Letters and Months */\r\n#define TT_UCR_ENCLOSED_CJK_LETTERS_MONTHS     (1L << 22) /* U+3200-U+32FF */\r\n  /* Bit 55   CJK Compatibility */\r\n#define TT_UCR_CJK_COMPATIBILITY               (1L << 23) /* U+3300-U+33FF */\r\n  /* Bit 56   Hangul Syllables */\r\n#define TT_UCR_HANGUL                          (1L << 24) /* U+AC00-U+D7A3 */\r\n  /* Bit 57   High Surrogates              */\r\n  /*          High Private Use Surrogates  */\r\n  /*          Low Surrogates               */\r\n  /*                                       */\r\n  /* According to OpenType specs v.1.3+,   */\r\n  /* setting bit 57 implies that there is  */\r\n  /* at least one codepoint beyond the     */\r\n  /* Basic Multilingual Plane that is      */\r\n  /* supported by this font.  So it really */\r\n  /* means >= U+10000                      */\r\n#define TT_UCR_SURROGATES                      (1L << 25) /* U+D800-U+DB7F */\r\n                                                          /* U+DB80-U+DBFF */\r\n                                                          /* U+DC00-U+DFFF */\r\n#define TT_UCR_NON_PLANE_0  TT_UCR_SURROGATES\r\n  /* Bit 58  Phoenician */\r\n#define TT_UCR_PHOENICIAN                      (1L << 26) /*U+10900-U+1091F*/\r\n  /* Bit 59   CJK Unified Ideographs             */\r\n  /*          CJK Radicals Supplement            */\r\n  /*          Kangxi Radicals                    */\r\n  /*          Ideographic Description Characters */\r\n  /*          CJK Unified Ideographs Extension A */\r\n  /*          CJK Unified Ideographs Extension B */\r\n  /*          Kanbun                             */\r\n#define TT_UCR_CJK_UNIFIED_IDEOGRAPHS          (1L << 27) /* U+4E00-U+9FFF */\r\n                                                          /* U+2E80-U+2EFF */\r\n                                                          /* U+2F00-U+2FDF */\r\n                                                          /* U+2FF0-U+2FFF */\r\n                                                          /* U+3400-U+4DB5 */\r\n                                                          /*U+20000-U+2A6DF*/\r\n                                                          /* U+3190-U+319F */\r\n  /* Bit 60   Private Use */\r\n#define TT_UCR_PRIVATE_USE                     (1L << 28) /* U+E000-U+F8FF */\r\n  /* Bit 61   CJK Strokes                             */\r\n  /*          CJK Compatibility Ideographs            */\r\n  /*          CJK Compatibility Ideographs Supplement */\r\n#define TT_UCR_CJK_COMPATIBILITY_IDEOGRAPHS    (1L << 29) /* U+31C0-U+31EF */\r\n                                                          /* U+F900-U+FAFF */\r\n                                                          /*U+2F800-U+2FA1F*/\r\n  /* Bit 62   Alphabetic Presentation Forms */\r\n#define TT_UCR_ALPHABETIC_PRESENTATION_FORMS   (1L << 30) /* U+FB00-U+FB4F */\r\n  /* Bit 63   Arabic Presentation Forms-A */\r\n#define TT_UCR_ARABIC_PRESENTATIONS_A          (1L << 31) /* U+FB50-U+FDFF */\r\n  /* Bit 64   Combining Half Marks */\r\n#define TT_UCR_COMBINING_HALF_MARKS            (1L <<  0) /* U+FE20-U+FE2F */\r\n  /* Bit 65   Vertical forms          */\r\n  /*          CJK Compatibility Forms */\r\n#define TT_UCR_CJK_COMPATIBILITY_FORMS         (1L <<  1) /* U+FE10-U+FE1F */\r\n                                                          /* U+FE30-U+FE4F */\r\n  /* Bit 66   Small Form Variants */\r\n#define TT_UCR_SMALL_FORM_VARIANTS             (1L <<  2) /* U+FE50-U+FE6F */\r\n  /* Bit 67   Arabic Presentation Forms-B */\r\n#define TT_UCR_ARABIC_PRESENTATIONS_B          (1L <<  3) /* U+FE70-U+FEFE */\r\n  /* Bit 68   Halfwidth and Fullwidth Forms */\r\n#define TT_UCR_HALFWIDTH_FULLWIDTH_FORMS       (1L <<  4) /* U+FF00-U+FFEF */\r\n  /* Bit 69   Specials */\r\n#define TT_UCR_SPECIALS                        (1L <<  5) /* U+FFF0-U+FFFD */\r\n  /* Bit 70   Tibetan */\r\n#define TT_UCR_TIBETAN                         (1L <<  6) /* U+0F00-U+0FFF */\r\n  /* Bit 71   Syriac */\r\n#define TT_UCR_SYRIAC                          (1L <<  7) /* U+0700-U+074F */\r\n  /* Bit 72   Thaana */\r\n#define TT_UCR_THAANA                          (1L <<  8) /* U+0780-U+07BF */\r\n  /* Bit 73   Sinhala */\r\n#define TT_UCR_SINHALA                         (1L <<  9) /* U+0D80-U+0DFF */\r\n  /* Bit 74   Myanmar */\r\n#define TT_UCR_MYANMAR                         (1L << 10) /* U+1000-U+109F */\r\n  /* Bit 75   Ethiopic            */\r\n  /*          Ethiopic Supplement */\r\n  /*          Ethiopic Extended   */\r\n#define TT_UCR_ETHIOPIC                        (1L << 11) /* U+1200-U+137F */\r\n                                                          /* U+1380-U+139F */\r\n                                                          /* U+2D80-U+2DDF */\r\n  /* Bit 76   Cherokee */\r\n#define TT_UCR_CHEROKEE                        (1L << 12) /* U+13A0-U+13FF */\r\n  /* Bit 77   Unified Canadian Aboriginal Syllabics */\r\n#define TT_UCR_CANADIAN_ABORIGINAL_SYLLABICS   (1L << 13) /* U+1400-U+167F */\r\n  /* Bit 78   Ogham */\r\n#define TT_UCR_OGHAM                           (1L << 14) /* U+1680-U+169F */\r\n  /* Bit 79   Runic */\r\n#define TT_UCR_RUNIC                           (1L << 15) /* U+16A0-U+16FF */\r\n  /* Bit 80   Khmer         */\r\n  /*          Khmer Symbols */\r\n#define TT_UCR_KHMER                           (1L << 16) /* U+1780-U+17FF */\r\n                                                          /* U+19E0-U+19FF */\r\n  /* Bit 81   Mongolian */\r\n#define TT_UCR_MONGOLIAN                       (1L << 17) /* U+1800-U+18AF */\r\n  /* Bit 82   Braille Patterns */\r\n#define TT_UCR_BRAILLE                         (1L << 18) /* U+2800-U+28FF */\r\n  /* Bit 83   Yi Syllables */\r\n  /*          Yi Radicals  */\r\n#define TT_UCR_YI                              (1L << 19) /* U+A000-U+A48F */\r\n                                                          /* U+A490-U+A4CF */\r\n  /* Bit 84   Tagalog  */\r\n  /*          Hanunoo  */\r\n  /*          Buhid    */\r\n  /*          Tagbanwa */\r\n#define TT_UCR_PHILIPPINE                      (1L << 20) /* U+1700-U+171F */\r\n                                                          /* U+1720-U+173F */\r\n                                                          /* U+1740-U+175F */\r\n                                                          /* U+1760-U+177F */\r\n  /* Bit 85   Old Italic */\r\n#define TT_UCR_OLD_ITALIC                      (1L << 21) /*U+10300-U+1032F*/\r\n  /* Bit 86   Gothic */\r\n#define TT_UCR_GOTHIC                          (1L << 22) /*U+10330-U+1034F*/\r\n  /* Bit 87   Deseret */\r\n#define TT_UCR_DESERET                         (1L << 23) /*U+10400-U+1044F*/\r\n  /* Bit 88   Byzantine Musical Symbols      */\r\n  /*          Musical Symbols                */\r\n  /*          Ancient Greek Musical Notation */\r\n#define TT_UCR_MUSICAL_SYMBOLS                 (1L << 24) /*U+1D000-U+1D0FF*/\r\n                                                          /*U+1D100-U+1D1FF*/\r\n                                                          /*U+1D200-U+1D24F*/\r\n  /* Bit 89   Mathematical Alphanumeric Symbols */\r\n#define TT_UCR_MATH_ALPHANUMERIC_SYMBOLS       (1L << 25) /*U+1D400-U+1D7FF*/\r\n  /* Bit 90   Private Use (plane 15) */\r\n  /*          Private Use (plane 16) */\r\n#define TT_UCR_PRIVATE_USE_SUPPLEMENTARY       (1L << 26) /*U+F0000-U+FFFFD*/\r\n                                                        /*U+100000-U+10FFFD*/\r\n  /* Bit 91   Variation Selectors            */\r\n  /*          Variation Selectors Supplement */\r\n#define TT_UCR_VARIATION_SELECTORS             (1L << 27) /* U+FE00-U+FE0F */\r\n                                                          /*U+E0100-U+E01EF*/\r\n  /* Bit 92   Tags */\r\n#define TT_UCR_TAGS                            (1L << 28) /*U+E0000-U+E007F*/\r\n  /* Bit 93   Limbu */\r\n#define TT_UCR_LIMBU                           (1L << 29) /* U+1900-U+194F */\r\n  /* Bit 94   Tai Le */\r\n#define TT_UCR_TAI_LE                          (1L << 30) /* U+1950-U+197F */\r\n  /* Bit 95   New Tai Lue */\r\n#define TT_UCR_NEW_TAI_LUE                     (1L << 31) /* U+1980-U+19DF */\r\n  /* Bit 96   Buginese */\r\n#define TT_UCR_BUGINESE                        (1L <<  0) /* U+1A00-U+1A1F */\r\n  /* Bit 97   Glagolitic */\r\n#define TT_UCR_GLAGOLITIC                      (1L <<  1) /* U+2C00-U+2C5F */\r\n  /* Bit 98   Tifinagh */\r\n#define TT_UCR_TIFINAGH                        (1L <<  2) /* U+2D30-U+2D7F */\r\n  /* Bit 99   Yijing Hexagram Symbols */\r\n#define TT_UCR_YIJING                          (1L <<  3) /* U+4DC0-U+4DFF */\r\n  /* Bit 100  Syloti Nagri */\r\n#define TT_UCR_SYLOTI_NAGRI                    (1L <<  4) /* U+A800-U+A82F */\r\n  /* Bit 101  Linear B Syllabary */\r\n  /*          Linear B Ideograms */\r\n  /*          Aegean Numbers     */\r\n#define TT_UCR_LINEAR_B                        (1L <<  5) /*U+10000-U+1007F*/\r\n                                                          /*U+10080-U+100FF*/\r\n                                                          /*U+10100-U+1013F*/\r\n  /* Bit 102  Ancient Greek Numbers */\r\n#define TT_UCR_ANCIENT_GREEK_NUMBERS           (1L <<  6) /*U+10140-U+1018F*/\r\n  /* Bit 103  Ugaritic */\r\n#define TT_UCR_UGARITIC                        (1L <<  7) /*U+10380-U+1039F*/\r\n  /* Bit 104  Old Persian */\r\n#define TT_UCR_OLD_PERSIAN                     (1L <<  8) /*U+103A0-U+103DF*/\r\n  /* Bit 105  Shavian */\r\n#define TT_UCR_SHAVIAN                         (1L <<  9) /*U+10450-U+1047F*/\r\n  /* Bit 106  Osmanya */\r\n#define TT_UCR_OSMANYA                         (1L << 10) /*U+10480-U+104AF*/\r\n  /* Bit 107  Cypriot Syllabary */\r\n#define TT_UCR_CYPRIOT_SYLLABARY               (1L << 11) /*U+10800-U+1083F*/\r\n  /* Bit 108  Kharoshthi */\r\n#define TT_UCR_KHAROSHTHI                      (1L << 12) /*U+10A00-U+10A5F*/\r\n  /* Bit 109  Tai Xuan Jing Symbols */\r\n#define TT_UCR_TAI_XUAN_JING                   (1L << 13) /*U+1D300-U+1D35F*/\r\n  /* Bit 110  Cuneiform                         */\r\n  /*          Cuneiform Numbers and Punctuation */\r\n#define TT_UCR_CUNEIFORM                       (1L << 14) /*U+12000-U+123FF*/\r\n                                                          /*U+12400-U+1247F*/\r\n  /* Bit 111  Counting Rod Numerals */\r\n#define TT_UCR_COUNTING_ROD_NUMERALS           (1L << 15) /*U+1D360-U+1D37F*/\r\n  /* Bit 112  Sundanese */\r\n#define TT_UCR_SUNDANESE                       (1L << 16) /* U+1B80-U+1BBF */\r\n  /* Bit 113  Lepcha */\r\n#define TT_UCR_LEPCHA                          (1L << 17) /* U+1C00-U+1C4F */\r\n  /* Bit 114  Ol Chiki */\r\n#define TT_UCR_OL_CHIKI                        (1L << 18) /* U+1C50-U+1C7F */\r\n  /* Bit 115  Saurashtra */\r\n#define TT_UCR_SAURASHTRA                      (1L << 19) /* U+A880-U+A8DF */\r\n  /* Bit 116  Kayah Li */\r\n#define TT_UCR_KAYAH_LI                        (1L << 20) /* U+A900-U+A92F */\r\n  /* Bit 117  Rejang */\r\n#define TT_UCR_REJANG                          (1L << 21) /* U+A930-U+A95F */\r\n  /* Bit 118  Cham */\r\n#define TT_UCR_CHAM                            (1L << 22) /* U+AA00-U+AA5F */\r\n  /* Bit 119  Ancient Symbols */\r\n#define TT_UCR_ANCIENT_SYMBOLS                 (1L << 23) /*U+10190-U+101CF*/\r\n  /* Bit 120  Phaistos Disc */\r\n#define TT_UCR_PHAISTOS_DISC                   (1L << 24) /*U+101D0-U+101FF*/\r\n  /* Bit 121  Carian */\r\n  /*          Lycian */\r\n  /*          Lydian */\r\n#define TT_UCR_OLD_ANATOLIAN                   (1L << 25) /*U+102A0-U+102DF*/\r\n                                                          /*U+10280-U+1029F*/\r\n                                                          /*U+10920-U+1093F*/\r\n  /* Bit 122  Domino Tiles  */\r\n  /*          Mahjong Tiles */\r\n#define TT_UCR_GAME_TILES                      (1L << 26) /*U+1F030-U+1F09F*/\r\n                                                          /*U+1F000-U+1F02F*/\r\n  /* Bit 123-127 Reserved for process-internal usage */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Some compilers have a very limited length of identifiers.             */\r\n  /*                                                                       */\r\n#if defined( __TURBOC__ ) && __TURBOC__ < 0x0410 || defined( __PACIFIC__ )\r\n#define HAVE_LIMIT_ON_IDENTS\r\n#endif\r\n\r\n\r\n#ifndef HAVE_LIMIT_ON_IDENTS\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* Here some alias #defines in order to be clearer.                      */\r\n  /*                                                                       */\r\n  /* These are not always #defined to stay within the 31~character limit   */\r\n  /* which some compilers have.                                            */\r\n  /*                                                                       */\r\n  /* Credits go to Dave Hoo <dhoo@flash.net> for pointing out that modern  */\r\n  /* Borland compilers (read: from BC++ 3.1 on) can increase this limit.   */\r\n  /* If you get a warning with such a compiler, use the -i40 switch.       */\r\n  /*                                                                       */\r\n#define TT_UCR_ARABIC_PRESENTATION_FORMS_A      \\\r\n         TT_UCR_ARABIC_PRESENTATIONS_A\r\n#define TT_UCR_ARABIC_PRESENTATION_FORMS_B      \\\r\n         TT_UCR_ARABIC_PRESENTATIONS_B\r\n\r\n#define TT_UCR_COMBINING_DIACRITICAL_MARKS      \\\r\n         TT_UCR_COMBINING_DIACRITICS\r\n#define TT_UCR_COMBINING_DIACRITICAL_MARKS_SYMB \\\r\n         TT_UCR_COMBINING_DIACRITICS_SYMB\r\n\r\n\r\n#endif /* !HAVE_LIMIT_ON_IDENTS */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __TTNAMEID_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/tttables.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  tttables.h                                                             */\r\n/*                                                                         */\r\n/*    Basic SFNT/TrueType tables definitions and interface                 */\r\n/*    (specification only).                                                */\r\n/*                                                                         */\r\n/*  Copyright 1996-2005, 2008-2011 by                                      */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __TTTABLES_H__\r\n#define __TTTABLES_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Section>                                                             */\r\n  /*    truetype_tables                                                    */\r\n  /*                                                                       */\r\n  /* <Title>                                                               */\r\n  /*    TrueType Tables                                                    */\r\n  /*                                                                       */\r\n  /* <Abstract>                                                            */\r\n  /*    TrueType specific table types and functions.                       */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    This section contains the definition of TrueType-specific tables   */\r\n  /*    as well as some routines used to access and process them.          */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_Header                                                          */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to model a TrueType font header table.  All       */\r\n  /*    fields follow the TrueType specification.                          */\r\n  /*                                                                       */\r\n  typedef struct  TT_Header_\r\n  {\r\n    FT_Fixed   Table_Version;\r\n    FT_Fixed   Font_Revision;\r\n\r\n    FT_Long    CheckSum_Adjust;\r\n    FT_Long    Magic_Number;\r\n\r\n    FT_UShort  Flags;\r\n    FT_UShort  Units_Per_EM;\r\n\r\n    FT_Long    Created [2];\r\n    FT_Long    Modified[2];\r\n\r\n    FT_Short   xMin;\r\n    FT_Short   yMin;\r\n    FT_Short   xMax;\r\n    FT_Short   yMax;\r\n\r\n    FT_UShort  Mac_Style;\r\n    FT_UShort  Lowest_Rec_PPEM;\r\n\r\n    FT_Short   Font_Direction;\r\n    FT_Short   Index_To_Loc_Format;\r\n    FT_Short   Glyph_Data_Format;\r\n\r\n  } TT_Header;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_HoriHeader                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to model a TrueType horizontal header, the `hhea' */\r\n  /*    table, as well as the corresponding horizontal metrics table,      */\r\n  /*    i.e., the `hmtx' table.                                            */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    Version                :: The table version.                       */\r\n  /*                                                                       */\r\n  /*    Ascender               :: The font's ascender, i.e., the distance  */\r\n  /*                              from the baseline to the top-most of all */\r\n  /*                              glyph points found in the font.          */\r\n  /*                                                                       */\r\n  /*                              This value is invalid in many fonts, as  */\r\n  /*                              it is usually set by the font designer,  */\r\n  /*                              and often reflects only a portion of the */\r\n  /*                              glyphs found in the font (maybe ASCII).  */\r\n  /*                                                                       */\r\n  /*                              You should use the `sTypoAscender' field */\r\n  /*                              of the OS/2 table instead if you want    */\r\n  /*                              the correct one.                         */\r\n  /*                                                                       */\r\n  /*    Descender              :: The font's descender, i.e., the distance */\r\n  /*                              from the baseline to the bottom-most of  */\r\n  /*                              all glyph points found in the font.  It  */\r\n  /*                              is negative.                             */\r\n  /*                                                                       */\r\n  /*                              This value is invalid in many fonts, as  */\r\n  /*                              it is usually set by the font designer,  */\r\n  /*                              and often reflects only a portion of the */\r\n  /*                              glyphs found in the font (maybe ASCII).  */\r\n  /*                                                                       */\r\n  /*                              You should use the `sTypoDescender'      */\r\n  /*                              field of the OS/2 table instead if you   */\r\n  /*                              want the correct one.                    */\r\n  /*                                                                       */\r\n  /*    Line_Gap               :: The font's line gap, i.e., the distance  */\r\n  /*                              to add to the ascender and descender to  */\r\n  /*                              get the BTB, i.e., the                   */\r\n  /*                              baseline-to-baseline distance for the    */\r\n  /*                              font.                                    */\r\n  /*                                                                       */\r\n  /*    advance_Width_Max      :: This field is the maximum of all advance */\r\n  /*                              widths found in the font.  It can be     */\r\n  /*                              used to compute the maximum width of an  */\r\n  /*                              arbitrary string of text.                */\r\n  /*                                                                       */\r\n  /*    min_Left_Side_Bearing  :: The minimum left side bearing of all     */\r\n  /*                              glyphs within the font.                  */\r\n  /*                                                                       */\r\n  /*    min_Right_Side_Bearing :: The minimum right side bearing of all    */\r\n  /*                              glyphs within the font.                  */\r\n  /*                                                                       */\r\n  /*    xMax_Extent            :: The maximum horizontal extent (i.e., the */\r\n  /*                              `width' of a glyph's bounding box) for   */\r\n  /*                              all glyphs in the font.                  */\r\n  /*                                                                       */\r\n  /*    caret_Slope_Rise       :: The rise coefficient of the cursor's     */\r\n  /*                              slope of the cursor (slope=rise/run).    */\r\n  /*                                                                       */\r\n  /*    caret_Slope_Run        :: The run coefficient of the cursor's      */\r\n  /*                              slope.                                   */\r\n  /*                                                                       */\r\n  /*    Reserved               :: 8~reserved bytes.                        */\r\n  /*                                                                       */\r\n  /*    metric_Data_Format     :: Always~0.                                */\r\n  /*                                                                       */\r\n  /*    number_Of_HMetrics     :: Number of HMetrics entries in the `hmtx' */\r\n  /*                              table -- this value can be smaller than  */\r\n  /*                              the total number of glyphs in the font.  */\r\n  /*                                                                       */\r\n  /*    long_metrics           :: A pointer into the `hmtx' table.         */\r\n  /*                                                                       */\r\n  /*    short_metrics          :: A pointer into the `hmtx' table.         */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    IMPORTANT: The TT_HoriHeader and TT_VertHeader structures should   */\r\n  /*               be identical except for the names of their fields which */\r\n  /*               are different.                                          */\r\n  /*                                                                       */\r\n  /*               This ensures that a single function in the `ttload'     */\r\n  /*               module is able to read both the horizontal and vertical */\r\n  /*               headers.                                                */\r\n  /*                                                                       */\r\n  typedef struct  TT_HoriHeader_\r\n  {\r\n    FT_Fixed   Version;\r\n    FT_Short   Ascender;\r\n    FT_Short   Descender;\r\n    FT_Short   Line_Gap;\r\n\r\n    FT_UShort  advance_Width_Max;      /* advance width maximum */\r\n\r\n    FT_Short   min_Left_Side_Bearing;  /* minimum left-sb       */\r\n    FT_Short   min_Right_Side_Bearing; /* minimum right-sb      */\r\n    FT_Short   xMax_Extent;            /* xmax extents          */\r\n    FT_Short   caret_Slope_Rise;\r\n    FT_Short   caret_Slope_Run;\r\n    FT_Short   caret_Offset;\r\n\r\n    FT_Short   Reserved[4];\r\n\r\n    FT_Short   metric_Data_Format;\r\n    FT_UShort  number_Of_HMetrics;\r\n\r\n    /* The following fields are not defined by the TrueType specification */\r\n    /* but they are used to connect the metrics header to the relevant    */\r\n    /* `HMTX' table.                                                      */\r\n\r\n    void*      long_metrics;\r\n    void*      short_metrics;\r\n\r\n  } TT_HoriHeader;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_VertHeader                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to model a TrueType vertical header, the `vhea'   */\r\n  /*    table, as well as the corresponding vertical metrics table, i.e.,  */\r\n  /*    the `vmtx' table.                                                  */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    Version                 :: The table version.                      */\r\n  /*                                                                       */\r\n  /*    Ascender                :: The font's ascender, i.e., the distance */\r\n  /*                               from the baseline to the top-most of    */\r\n  /*                               all glyph points found in the font.     */\r\n  /*                                                                       */\r\n  /*                               This value is invalid in many fonts, as */\r\n  /*                               it is usually set by the font designer, */\r\n  /*                               and often reflects only a portion of    */\r\n  /*                               the glyphs found in the font (maybe     */\r\n  /*                               ASCII).                                 */\r\n  /*                                                                       */\r\n  /*                               You should use the `sTypoAscender'      */\r\n  /*                               field of the OS/2 table instead if you  */\r\n  /*                               want the correct one.                   */\r\n  /*                                                                       */\r\n  /*    Descender               :: The font's descender, i.e., the         */\r\n  /*                               distance from the baseline to the       */\r\n  /*                               bottom-most of all glyph points found   */\r\n  /*                               in the font.  It is negative.           */\r\n  /*                                                                       */\r\n  /*                               This value is invalid in many fonts, as */\r\n  /*                               it is usually set by the font designer, */\r\n  /*                               and often reflects only a portion of    */\r\n  /*                               the glyphs found in the font (maybe     */\r\n  /*                               ASCII).                                 */\r\n  /*                                                                       */\r\n  /*                               You should use the `sTypoDescender'     */\r\n  /*                               field of the OS/2 table instead if you  */\r\n  /*                               want the correct one.                   */\r\n  /*                                                                       */\r\n  /*    Line_Gap                :: The font's line gap, i.e., the distance */\r\n  /*                               to add to the ascender and descender to */\r\n  /*                               get the BTB, i.e., the                  */\r\n  /*                               baseline-to-baseline distance for the   */\r\n  /*                               font.                                   */\r\n  /*                                                                       */\r\n  /*    advance_Height_Max      :: This field is the maximum of all        */\r\n  /*                               advance heights found in the font.  It  */\r\n  /*                               can be used to compute the maximum      */\r\n  /*                               height of an arbitrary string of text.  */\r\n  /*                                                                       */\r\n  /*    min_Top_Side_Bearing    :: The minimum top side bearing of all     */\r\n  /*                               glyphs within the font.                 */\r\n  /*                                                                       */\r\n  /*    min_Bottom_Side_Bearing :: The minimum bottom side bearing of all  */\r\n  /*                               glyphs within the font.                 */\r\n  /*                                                                       */\r\n  /*    yMax_Extent             :: The maximum vertical extent (i.e., the  */\r\n  /*                               `height' of a glyph's bounding box) for */\r\n  /*                               all glyphs in the font.                 */\r\n  /*                                                                       */\r\n  /*    caret_Slope_Rise        :: The rise coefficient of the cursor's    */\r\n  /*                               slope of the cursor (slope=rise/run).   */\r\n  /*                                                                       */\r\n  /*    caret_Slope_Run         :: The run coefficient of the cursor's     */\r\n  /*                               slope.                                  */\r\n  /*                                                                       */\r\n  /*    caret_Offset            :: The cursor's offset for slanted fonts.  */\r\n  /*                               This value is `reserved' in vmtx        */\r\n  /*                               version 1.0.                            */\r\n  /*                                                                       */\r\n  /*    Reserved                :: 8~reserved bytes.                       */\r\n  /*                                                                       */\r\n  /*    metric_Data_Format      :: Always~0.                               */\r\n  /*                                                                       */\r\n  /*    number_Of_HMetrics      :: Number of VMetrics entries in the       */\r\n  /*                               `vmtx' table -- this value can be       */\r\n  /*                               smaller than the total number of glyphs */\r\n  /*                               in the font.                            */\r\n  /*                                                                       */\r\n  /*    long_metrics           :: A pointer into the `vmtx' table.         */\r\n  /*                                                                       */\r\n  /*    short_metrics          :: A pointer into the `vmtx' table.         */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    IMPORTANT: The TT_HoriHeader and TT_VertHeader structures should   */\r\n  /*               be identical except for the names of their fields which */\r\n  /*               are different.                                          */\r\n  /*                                                                       */\r\n  /*               This ensures that a single function in the `ttload'     */\r\n  /*               module is able to read both the horizontal and vertical */\r\n  /*               headers.                                                */\r\n  /*                                                                       */\r\n  typedef struct  TT_VertHeader_\r\n  {\r\n    FT_Fixed   Version;\r\n    FT_Short   Ascender;\r\n    FT_Short   Descender;\r\n    FT_Short   Line_Gap;\r\n\r\n    FT_UShort  advance_Height_Max;      /* advance height maximum */\r\n\r\n    FT_Short   min_Top_Side_Bearing;    /* minimum left-sb or top-sb       */\r\n    FT_Short   min_Bottom_Side_Bearing; /* minimum right-sb or bottom-sb   */\r\n    FT_Short   yMax_Extent;             /* xmax or ymax extents            */\r\n    FT_Short   caret_Slope_Rise;\r\n    FT_Short   caret_Slope_Run;\r\n    FT_Short   caret_Offset;\r\n\r\n    FT_Short   Reserved[4];\r\n\r\n    FT_Short   metric_Data_Format;\r\n    FT_UShort  number_Of_VMetrics;\r\n\r\n    /* The following fields are not defined by the TrueType specification */\r\n    /* but they're used to connect the metrics header to the relevant     */\r\n    /* `HMTX' or `VMTX' table.                                            */\r\n\r\n    void*      long_metrics;\r\n    void*      short_metrics;\r\n\r\n  } TT_VertHeader;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_OS2                                                             */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to model a TrueType OS/2 table. This is the long  */\r\n  /*    table version.  All fields comply to the TrueType specification.   */\r\n  /*                                                                       */\r\n  /*    Note that we now support old Mac fonts which do not include an     */\r\n  /*    OS/2 table.  In this case, the `version' field is always set to    */\r\n  /*    0xFFFF.                                                            */\r\n  /*                                                                       */\r\n  typedef struct  TT_OS2_\r\n  {\r\n    FT_UShort  version;                /* 0x0001 - more or 0xFFFF */\r\n    FT_Short   xAvgCharWidth;\r\n    FT_UShort  usWeightClass;\r\n    FT_UShort  usWidthClass;\r\n    FT_Short   fsType;\r\n    FT_Short   ySubscriptXSize;\r\n    FT_Short   ySubscriptYSize;\r\n    FT_Short   ySubscriptXOffset;\r\n    FT_Short   ySubscriptYOffset;\r\n    FT_Short   ySuperscriptXSize;\r\n    FT_Short   ySuperscriptYSize;\r\n    FT_Short   ySuperscriptXOffset;\r\n    FT_Short   ySuperscriptYOffset;\r\n    FT_Short   yStrikeoutSize;\r\n    FT_Short   yStrikeoutPosition;\r\n    FT_Short   sFamilyClass;\r\n\r\n    FT_Byte    panose[10];\r\n\r\n    FT_ULong   ulUnicodeRange1;        /* Bits 0-31   */\r\n    FT_ULong   ulUnicodeRange2;        /* Bits 32-63  */\r\n    FT_ULong   ulUnicodeRange3;        /* Bits 64-95  */\r\n    FT_ULong   ulUnicodeRange4;        /* Bits 96-127 */\r\n\r\n    FT_Char    achVendID[4];\r\n\r\n    FT_UShort  fsSelection;\r\n    FT_UShort  usFirstCharIndex;\r\n    FT_UShort  usLastCharIndex;\r\n    FT_Short   sTypoAscender;\r\n    FT_Short   sTypoDescender;\r\n    FT_Short   sTypoLineGap;\r\n    FT_UShort  usWinAscent;\r\n    FT_UShort  usWinDescent;\r\n\r\n    /* only version 1 tables: */\r\n\r\n    FT_ULong   ulCodePageRange1;       /* Bits 0-31   */\r\n    FT_ULong   ulCodePageRange2;       /* Bits 32-63  */\r\n\r\n    /* only version 2 tables: */\r\n\r\n    FT_Short   sxHeight;\r\n    FT_Short   sCapHeight;\r\n    FT_UShort  usDefaultChar;\r\n    FT_UShort  usBreakChar;\r\n    FT_UShort  usMaxContext;\r\n\r\n  } TT_OS2;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_Postscript                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to model a TrueType PostScript table.  All fields */\r\n  /*    comply to the TrueType specification.  This structure does not     */\r\n  /*    reference the PostScript glyph names, which can be nevertheless    */\r\n  /*    accessed with the `ttpost' module.                                 */\r\n  /*                                                                       */\r\n  typedef struct  TT_Postscript_\r\n  {\r\n    FT_Fixed  FormatType;\r\n    FT_Fixed  italicAngle;\r\n    FT_Short  underlinePosition;\r\n    FT_Short  underlineThickness;\r\n    FT_ULong  isFixedPitch;\r\n    FT_ULong  minMemType42;\r\n    FT_ULong  maxMemType42;\r\n    FT_ULong  minMemType1;\r\n    FT_ULong  maxMemType1;\r\n\r\n    /* Glyph names follow in the file, but we don't   */\r\n    /* load them by default.  See the ttpost.c file.  */\r\n\r\n  } TT_Postscript;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_PCLT                                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    A structure used to model a TrueType PCLT table.  All fields       */\r\n  /*    comply to the TrueType specification.                              */\r\n  /*                                                                       */\r\n  typedef struct  TT_PCLT_\r\n  {\r\n    FT_Fixed   Version;\r\n    FT_ULong   FontNumber;\r\n    FT_UShort  Pitch;\r\n    FT_UShort  xHeight;\r\n    FT_UShort  Style;\r\n    FT_UShort  TypeFamily;\r\n    FT_UShort  CapHeight;\r\n    FT_UShort  SymbolSet;\r\n    FT_Char    TypeFace[16];\r\n    FT_Char    CharacterComplement[8];\r\n    FT_Char    FileName[6];\r\n    FT_Char    StrokeWeight;\r\n    FT_Char    WidthType;\r\n    FT_Byte    SerifStyle;\r\n    FT_Byte    Reserved;\r\n\r\n  } TT_PCLT;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Struct>                                                              */\r\n  /*    TT_MaxProfile                                                      */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    The maximum profile is a table containing many max values which    */\r\n  /*    can be used to pre-allocate arrays.  This ensures that no memory   */\r\n  /*    allocation occurs during a glyph load.                             */\r\n  /*                                                                       */\r\n  /* <Fields>                                                              */\r\n  /*    version               :: The version number.                       */\r\n  /*                                                                       */\r\n  /*    numGlyphs             :: The number of glyphs in this TrueType     */\r\n  /*                             font.                                     */\r\n  /*                                                                       */\r\n  /*    maxPoints             :: The maximum number of points in a         */\r\n  /*                             non-composite TrueType glyph.  See also   */\r\n  /*                             the structure element                     */\r\n  /*                             `maxCompositePoints'.                     */\r\n  /*                                                                       */\r\n  /*    maxContours           :: The maximum number of contours in a       */\r\n  /*                             non-composite TrueType glyph.  See also   */\r\n  /*                             the structure element                     */\r\n  /*                             `maxCompositeContours'.                   */\r\n  /*                                                                       */\r\n  /*    maxCompositePoints    :: The maximum number of points in a         */\r\n  /*                             composite TrueType glyph.  See also the   */\r\n  /*                             structure element `maxPoints'.            */\r\n  /*                                                                       */\r\n  /*    maxCompositeContours  :: The maximum number of contours in a       */\r\n  /*                             composite TrueType glyph.  See also the   */\r\n  /*                             structure element `maxContours'.          */\r\n  /*                                                                       */\r\n  /*    maxZones              :: The maximum number of zones used for      */\r\n  /*                             glyph hinting.                            */\r\n  /*                                                                       */\r\n  /*    maxTwilightPoints     :: The maximum number of points in the       */\r\n  /*                             twilight zone used for glyph hinting.     */\r\n  /*                                                                       */\r\n  /*    maxStorage            :: The maximum number of elements in the     */\r\n  /*                             storage area used for glyph hinting.      */\r\n  /*                                                                       */\r\n  /*    maxFunctionDefs       :: The maximum number of function            */\r\n  /*                             definitions in the TrueType bytecode for  */\r\n  /*                             this font.                                */\r\n  /*                                                                       */\r\n  /*    maxInstructionDefs    :: The maximum number of instruction         */\r\n  /*                             definitions in the TrueType bytecode for  */\r\n  /*                             this font.                                */\r\n  /*                                                                       */\r\n  /*    maxStackElements      :: The maximum number of stack elements used */\r\n  /*                             during bytecode interpretation.           */\r\n  /*                                                                       */\r\n  /*    maxSizeOfInstructions :: The maximum number of TrueType opcodes    */\r\n  /*                             used for glyph hinting.                   */\r\n  /*                                                                       */\r\n  /*    maxComponentElements  :: The maximum number of simple (i.e., non-  */\r\n  /*                             composite) glyphs in a composite glyph.   */\r\n  /*                                                                       */\r\n  /*    maxComponentDepth     :: The maximum nesting depth of composite    */\r\n  /*                             glyphs.                                   */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    This structure is only used during font loading.                   */\r\n  /*                                                                       */\r\n  typedef struct  TT_MaxProfile_\r\n  {\r\n    FT_Fixed   version;\r\n    FT_UShort  numGlyphs;\r\n    FT_UShort  maxPoints;\r\n    FT_UShort  maxContours;\r\n    FT_UShort  maxCompositePoints;\r\n    FT_UShort  maxCompositeContours;\r\n    FT_UShort  maxZones;\r\n    FT_UShort  maxTwilightPoints;\r\n    FT_UShort  maxStorage;\r\n    FT_UShort  maxFunctionDefs;\r\n    FT_UShort  maxInstructionDefs;\r\n    FT_UShort  maxStackElements;\r\n    FT_UShort  maxSizeOfInstructions;\r\n    FT_UShort  maxComponentElements;\r\n    FT_UShort  maxComponentDepth;\r\n\r\n  } TT_MaxProfile;\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Enum>                                                                */\r\n  /*    FT_Sfnt_Tag                                                        */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    An enumeration used to specify the index of an SFNT table.         */\r\n  /*    Used in the @FT_Get_Sfnt_Table API function.                       */\r\n  /*                                                                       */\r\n  typedef enum  FT_Sfnt_Tag_\r\n  {\r\n    ft_sfnt_head = 0,    /* TT_Header     */\r\n    ft_sfnt_maxp = 1,    /* TT_MaxProfile */\r\n    ft_sfnt_os2  = 2,    /* TT_OS2        */\r\n    ft_sfnt_hhea = 3,    /* TT_HoriHeader */\r\n    ft_sfnt_vhea = 4,    /* TT_VertHeader */\r\n    ft_sfnt_post = 5,    /* TT_Postscript */\r\n    ft_sfnt_pclt = 6,    /* TT_PCLT       */\r\n\r\n    sfnt_max   /* internal end mark */\r\n\r\n  } FT_Sfnt_Tag;\r\n\r\n  /* */\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Get_Sfnt_Table                                                  */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Return a pointer to a given SFNT table within a face.              */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    face :: A handle to the source.                                    */\r\n  /*                                                                       */\r\n  /*    tag  :: The index of the SFNT table.                               */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    A type-less pointer to the table.  This will be~0 in case of       */\r\n  /*    error, or if the corresponding table was not found *OR* loaded     */\r\n  /*    from the file.                                                     */\r\n  /*                                                                       */\r\n  /*    Use a typecast according to `tag' to access the structure          */\r\n  /*    elements.                                                          */\r\n  /*                                                                       */\r\n  /* <Note>                                                                */\r\n  /*    The table is owned by the face object and disappears with it.      */\r\n  /*                                                                       */\r\n  /*    This function is only useful to access SFNT tables that are loaded */\r\n  /*    by the sfnt, truetype, and opentype drivers.  See @FT_Sfnt_Tag for */\r\n  /*    a list.                                                            */\r\n  /*                                                                       */\r\n  FT_EXPORT( void* )\r\n  FT_Get_Sfnt_Table( FT_Face      face,\r\n                     FT_Sfnt_Tag  tag );\r\n\r\n\r\n /**************************************************************************\r\n  *\r\n  * @function:\r\n  *   FT_Load_Sfnt_Table\r\n  *\r\n  * @description:\r\n  *   Load any font table into client memory.\r\n  *\r\n  * @input:\r\n  *   face ::\r\n  *     A handle to the source face.\r\n  *\r\n  *   tag ::\r\n  *     The four-byte tag of the table to load.  Use the value~0 if you want\r\n  *     to access the whole font file.  Otherwise, you can use one of the\r\n  *     definitions found in the @FT_TRUETYPE_TAGS_H file, or forge a new\r\n  *     one with @FT_MAKE_TAG.\r\n  *\r\n  *   offset ::\r\n  *     The starting offset in the table (or file if tag == 0).\r\n  *\r\n  * @output:\r\n  *   buffer ::\r\n  *     The target buffer address.  The client must ensure that the memory\r\n  *     array is big enough to hold the data.\r\n  *\r\n  * @inout:\r\n  *   length ::\r\n  *     If the `length' parameter is NULL, then try to load the whole table.\r\n  *     Return an error code if it fails.\r\n  *\r\n  *     Else, if `*length' is~0, exit immediately while returning the\r\n  *     table's (or file) full size in it.\r\n  *\r\n  *     Else the number of bytes to read from the table or file, from the\r\n  *     starting offset.\r\n  *\r\n  * @return:\r\n  *   FreeType error code.  0~means success.\r\n  *\r\n  * @note:\r\n  *   If you need to determine the table's length you should first call this\r\n  *   function with `*length' set to~0, as in the following example:\r\n  *\r\n  *     {\r\n  *       FT_ULong  length = 0;\r\n  *\r\n  *\r\n  *       error = FT_Load_Sfnt_Table( face, tag, 0, NULL, &length );\r\n  *       if ( error ) { ... table does not exist ... }\r\n  *\r\n  *       buffer = malloc( length );\r\n  *       if ( buffer == NULL ) { ... not enough memory ... }\r\n  *\r\n  *       error = FT_Load_Sfnt_Table( face, tag, 0, buffer, &length );\r\n  *       if ( error ) { ... could not load table ... }\r\n  *     }\r\n  */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Load_Sfnt_Table( FT_Face    face,\r\n                      FT_ULong   tag,\r\n                      FT_Long    offset,\r\n                      FT_Byte*   buffer,\r\n                      FT_ULong*  length );\r\n\r\n\r\n /**************************************************************************\r\n  *\r\n  * @function:\r\n  *   FT_Sfnt_Table_Info\r\n  *\r\n  * @description:\r\n  *   Return information on an SFNT table.\r\n  *\r\n  * @input:\r\n  *   face ::\r\n  *     A handle to the source face.\r\n  *\r\n  *   table_index ::\r\n  *     The index of an SFNT table.  The function returns\r\n  *     FT_Err_Table_Missing for an invalid value.\r\n  *\r\n  * @inout:\r\n  *   tag ::\r\n  *     The name tag of the SFNT table.  If the value is NULL, `table_index'\r\n  *     is ignored, and `length' returns the number of SFNT tables in the\r\n  *     font.\r\n  *\r\n  * @output:\r\n  *   length ::\r\n  *     The length of the SFNT table (or the number of SFNT tables, depending\r\n  *     on `tag').\r\n  *\r\n  * @return:\r\n  *   FreeType error code.  0~means success.\r\n  *\r\n  * @note:\r\n  *   SFNT tables with length zero are treated as missing.\r\n  *\r\n  */\r\n  FT_EXPORT( FT_Error )\r\n  FT_Sfnt_Table_Info( FT_Face    face,\r\n                      FT_UInt    table_index,\r\n                      FT_ULong  *tag,\r\n                      FT_ULong  *length );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Get_CMap_Language_ID                                            */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Return TrueType/sfnt specific cmap language ID.  Definitions of    */\r\n  /*    language ID values are in `freetype/ttnameid.h'.                   */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    charmap ::                                                         */\r\n  /*      The target charmap.                                              */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    The language ID of `charmap'.  If `charmap' doesn't belong to a    */\r\n  /*    TrueType/sfnt face, just return~0 as the default value.            */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_ULong )\r\n  FT_Get_CMap_Language_ID( FT_CharMap  charmap );\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* <Function>                                                            */\r\n  /*    FT_Get_CMap_Format                                                 */\r\n  /*                                                                       */\r\n  /* <Description>                                                         */\r\n  /*    Return TrueType/sfnt specific cmap format.                         */\r\n  /*                                                                       */\r\n  /* <Input>                                                               */\r\n  /*    charmap ::                                                         */\r\n  /*      The target charmap.                                              */\r\n  /*                                                                       */\r\n  /* <Return>                                                              */\r\n  /*    The format of `charmap'.  If `charmap' doesn't belong to a         */\r\n  /*    TrueType/sfnt face, return -1.                                     */\r\n  /*                                                                       */\r\n  FT_EXPORT( FT_Long )\r\n  FT_Get_CMap_Format( FT_CharMap  charmap );\r\n\r\n  /* */\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __TTTABLES_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/tttags.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  tttags.h                                                               */\r\n/*                                                                         */\r\n/*    Tags for TrueType and OpenType tables (specification only).          */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2004, 2005, 2007, 2008 by                         */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __TTAGS_H__\r\n#define __TTAGS_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n#define TTAG_avar  FT_MAKE_TAG( 'a', 'v', 'a', 'r' )\r\n#define TTAG_BASE  FT_MAKE_TAG( 'B', 'A', 'S', 'E' )\r\n#define TTAG_bdat  FT_MAKE_TAG( 'b', 'd', 'a', 't' )\r\n#define TTAG_BDF   FT_MAKE_TAG( 'B', 'D', 'F', ' ' )\r\n#define TTAG_bhed  FT_MAKE_TAG( 'b', 'h', 'e', 'd' )\r\n#define TTAG_bloc  FT_MAKE_TAG( 'b', 'l', 'o', 'c' )\r\n#define TTAG_bsln  FT_MAKE_TAG( 'b', 's', 'l', 'n' )\r\n#define TTAG_CFF   FT_MAKE_TAG( 'C', 'F', 'F', ' ' )\r\n#define TTAG_CID   FT_MAKE_TAG( 'C', 'I', 'D', ' ' )\r\n#define TTAG_cmap  FT_MAKE_TAG( 'c', 'm', 'a', 'p' )\r\n#define TTAG_cvar  FT_MAKE_TAG( 'c', 'v', 'a', 'r' )\r\n#define TTAG_cvt   FT_MAKE_TAG( 'c', 'v', 't', ' ' )\r\n#define TTAG_DSIG  FT_MAKE_TAG( 'D', 'S', 'I', 'G' )\r\n#define TTAG_EBDT  FT_MAKE_TAG( 'E', 'B', 'D', 'T' )\r\n#define TTAG_EBLC  FT_MAKE_TAG( 'E', 'B', 'L', 'C' )\r\n#define TTAG_EBSC  FT_MAKE_TAG( 'E', 'B', 'S', 'C' )\r\n#define TTAG_feat  FT_MAKE_TAG( 'f', 'e', 'a', 't' )\r\n#define TTAG_FOND  FT_MAKE_TAG( 'F', 'O', 'N', 'D' )\r\n#define TTAG_fpgm  FT_MAKE_TAG( 'f', 'p', 'g', 'm' )\r\n#define TTAG_fvar  FT_MAKE_TAG( 'f', 'v', 'a', 'r' )\r\n#define TTAG_gasp  FT_MAKE_TAG( 'g', 'a', 's', 'p' )\r\n#define TTAG_GDEF  FT_MAKE_TAG( 'G', 'D', 'E', 'F' )\r\n#define TTAG_glyf  FT_MAKE_TAG( 'g', 'l', 'y', 'f' )\r\n#define TTAG_GPOS  FT_MAKE_TAG( 'G', 'P', 'O', 'S' )\r\n#define TTAG_GSUB  FT_MAKE_TAG( 'G', 'S', 'U', 'B' )\r\n#define TTAG_gvar  FT_MAKE_TAG( 'g', 'v', 'a', 'r' )\r\n#define TTAG_hdmx  FT_MAKE_TAG( 'h', 'd', 'm', 'x' )\r\n#define TTAG_head  FT_MAKE_TAG( 'h', 'e', 'a', 'd' )\r\n#define TTAG_hhea  FT_MAKE_TAG( 'h', 'h', 'e', 'a' )\r\n#define TTAG_hmtx  FT_MAKE_TAG( 'h', 'm', 't', 'x' )\r\n#define TTAG_JSTF  FT_MAKE_TAG( 'J', 'S', 'T', 'F' )\r\n#define TTAG_just  FT_MAKE_TAG( 'j', 'u', 's', 't' )\r\n#define TTAG_kern  FT_MAKE_TAG( 'k', 'e', 'r', 'n' )\r\n#define TTAG_lcar  FT_MAKE_TAG( 'l', 'c', 'a', 'r' )\r\n#define TTAG_loca  FT_MAKE_TAG( 'l', 'o', 'c', 'a' )\r\n#define TTAG_LTSH  FT_MAKE_TAG( 'L', 'T', 'S', 'H' )\r\n#define TTAG_LWFN  FT_MAKE_TAG( 'L', 'W', 'F', 'N' )\r\n#define TTAG_MATH  FT_MAKE_TAG( 'M', 'A', 'T', 'H' )\r\n#define TTAG_maxp  FT_MAKE_TAG( 'm', 'a', 'x', 'p' )\r\n#define TTAG_META  FT_MAKE_TAG( 'M', 'E', 'T', 'A' )\r\n#define TTAG_MMFX  FT_MAKE_TAG( 'M', 'M', 'F', 'X' )\r\n#define TTAG_MMSD  FT_MAKE_TAG( 'M', 'M', 'S', 'D' )\r\n#define TTAG_mort  FT_MAKE_TAG( 'm', 'o', 'r', 't' )\r\n#define TTAG_morx  FT_MAKE_TAG( 'm', 'o', 'r', 'x' )\r\n#define TTAG_name  FT_MAKE_TAG( 'n', 'a', 'm', 'e' )\r\n#define TTAG_opbd  FT_MAKE_TAG( 'o', 'p', 'b', 'd' )\r\n#define TTAG_OS2   FT_MAKE_TAG( 'O', 'S', '/', '2' )\r\n#define TTAG_OTTO  FT_MAKE_TAG( 'O', 'T', 'T', 'O' )\r\n#define TTAG_PCLT  FT_MAKE_TAG( 'P', 'C', 'L', 'T' )\r\n#define TTAG_POST  FT_MAKE_TAG( 'P', 'O', 'S', 'T' )\r\n#define TTAG_post  FT_MAKE_TAG( 'p', 'o', 's', 't' )\r\n#define TTAG_prep  FT_MAKE_TAG( 'p', 'r', 'e', 'p' )\r\n#define TTAG_prop  FT_MAKE_TAG( 'p', 'r', 'o', 'p' )\r\n#define TTAG_sfnt  FT_MAKE_TAG( 's', 'f', 'n', 't' )\r\n#define TTAG_SING  FT_MAKE_TAG( 'S', 'I', 'N', 'G' )\r\n#define TTAG_trak  FT_MAKE_TAG( 't', 'r', 'a', 'k' )\r\n#define TTAG_true  FT_MAKE_TAG( 't', 'r', 'u', 'e' )\r\n#define TTAG_ttc   FT_MAKE_TAG( 't', 't', 'c', ' ' )\r\n#define TTAG_ttcf  FT_MAKE_TAG( 't', 't', 'c', 'f' )\r\n#define TTAG_TYP1  FT_MAKE_TAG( 'T', 'Y', 'P', '1' )\r\n#define TTAG_typ1  FT_MAKE_TAG( 't', 'y', 'p', '1' )\r\n#define TTAG_VDMX  FT_MAKE_TAG( 'V', 'D', 'M', 'X' )\r\n#define TTAG_vhea  FT_MAKE_TAG( 'v', 'h', 'e', 'a' )\r\n#define TTAG_vmtx  FT_MAKE_TAG( 'v', 'm', 't', 'x' )\r\n\r\n\r\nFT_END_HEADER\r\n\r\n#endif /* __TTAGS_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/freetype/ttunpat.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ttunpat.h                                                              */\r\n/*                                                                         */\r\n/*    Definitions for the unpatented TrueType hinting system               */\r\n/*                                                                         */\r\n/*  Copyright 2003, 2006 by                                                */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  Written by Graham Asher <graham.asher@btinternet.com>                  */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n#ifndef __TTUNPAT_H__\r\n#define __TTUNPAT_H__\r\n\r\n\r\n#include <ft2build.h>\r\n#include FT_FREETYPE_H\r\n\r\n#ifdef FREETYPE_H\r\n#error \"freetype.h of FreeType 1 has been loaded!\"\r\n#error \"Please fix the directory search order for header files\"\r\n#error \"so that freetype.h of FreeType 2 is found first.\"\r\n#endif\r\n\r\n\r\nFT_BEGIN_HEADER\r\n\r\n\r\n /***************************************************************************\r\n  *\r\n  * @constant:\r\n  *   FT_PARAM_TAG_UNPATENTED_HINTING\r\n  *\r\n  * @description:\r\n  *   A constant used as the tag of an @FT_Parameter structure to indicate\r\n  *   that unpatented methods only should be used by the TrueType bytecode\r\n  *   interpreter for a typeface opened by @FT_Open_Face.\r\n  *\r\n  */\r\n#define FT_PARAM_TAG_UNPATENTED_HINTING  FT_MAKE_TAG( 'u', 'n', 'p', 'a' )\r\n\r\n /* */\r\n\r\nFT_END_HEADER\r\n\r\n\r\n#endif /* __TTUNPAT_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/freetype/include/ft2build.h",
    "content": "/***************************************************************************/\r\n/*                                                                         */\r\n/*  ft2build.h                                                             */\r\n/*                                                                         */\r\n/*    FreeType 2 build and setup macros.                                   */\r\n/*    (Generic version)                                                    */\r\n/*                                                                         */\r\n/*  Copyright 1996-2001, 2006 by                                           */\r\n/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */\r\n/*                                                                         */\r\n/*  This file is part of the FreeType project, and may only be used,       */\r\n/*  modified, and distributed under the terms of the FreeType project      */\r\n/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */\r\n/*  this file you indicate that you have read the license and              */\r\n/*  understand and accept it fully.                                        */\r\n/*                                                                         */\r\n/***************************************************************************/\r\n\r\n\r\n  /*************************************************************************/\r\n  /*                                                                       */\r\n  /* This file corresponds to the default `ft2build.h' file for            */\r\n  /* FreeType 2.  It uses the `freetype' include root.                     */\r\n  /*                                                                       */\r\n  /* Note that specific platforms might use a different configuration.     */\r\n  /* See builds/unix/ft2unix.h for an example.                             */\r\n  /*                                                                       */\r\n  /*************************************************************************/\r\n\r\n\r\n#ifndef __FT2_BUILD_GENERIC_H__\r\n#define __FT2_BUILD_GENERIC_H__\r\n\r\n#include <freetype/config/ftheader.h>\r\n\r\n#endif /* __FT2_BUILD_GENERIC_H__ */\r\n\r\n\r\n/* END */\r\n"
  },
  {
    "path": "other/icons/teeworlds_cl.rc",
    "content": "50h ICON \"teeworlds.ico\"\n"
  },
  {
    "path": "other/icons/teeworlds_gcc.rc",
    "content": "ID ICON \"teeworlds.ico\"\n"
  },
  {
    "path": "other/icons/teeworlds_srv_cl.rc",
    "content": "50h ICON \"Teeworlds_srv.ico\"\n"
  },
  {
    "path": "other/icons/teeworlds_srv_gcc.rc",
    "content": "ID ICON \"Teeworlds_srv.ico\"\n"
  },
  {
    "path": "other/sdl/include/SDL.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/** @file SDL.h\n *  Main include header for the SDL library\n */\n\n#ifndef _SDL_H\n#define _SDL_H\n\n#include \"SDL_main.h\"\n#include \"SDL_stdinc.h\"\n#include \"SDL_audio.h\"\n#include \"SDL_cdrom.h\"\n#include \"SDL_cpuinfo.h\"\n#include \"SDL_endian.h\"\n#include \"SDL_error.h\"\n#include \"SDL_events.h\"\n#include \"SDL_loadso.h\"\n#include \"SDL_mutex.h\"\n#include \"SDL_rwops.h\"\n#include \"SDL_thread.h\"\n#include \"SDL_timer.h\"\n#include \"SDL_video.h\"\n#include \"SDL_version.h\"\n\n#include \"begin_code.h\"\n/* Set up for C function definitions, even when using C++ */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/** @file SDL.h\n *  @note As of version 0.5, SDL is loaded dynamically into the application\n */\n\n/** @name SDL_INIT Flags\n *  These are the flags which may be passed to SDL_Init() -- you should\n *  specify the subsystems which you will be using in your application.\n */\n/*@{*/\n#define\tSDL_INIT_TIMER\t\t0x00000001\n#define SDL_INIT_AUDIO\t\t0x00000010\n#define SDL_INIT_VIDEO\t\t0x00000020\n#define SDL_INIT_CDROM\t\t0x00000100\n#define SDL_INIT_JOYSTICK\t0x00000200\n#define SDL_INIT_NOPARACHUTE\t0x00100000\t/**< Don't catch fatal signals */\n#define SDL_INIT_EVENTTHREAD\t0x01000000\t/**< Not supported on all OS's */\n#define SDL_INIT_EVERYTHING\t0x0000FFFF\n/*@}*/\n\n/** This function loads the SDL dynamically linked library and initializes \n *  the subsystems specified by 'flags' (and those satisfying dependencies)\n *  Unless the SDL_INIT_NOPARACHUTE flag is set, it will install cleanup\n *  signal handlers for some commonly ignored fatal signals (like SIGSEGV)\n */\nextern DECLSPEC int SDLCALL SDL_Init(Uint32 flags);\n\n/** This function initializes specific SDL subsystems */\nextern DECLSPEC int SDLCALL SDL_InitSubSystem(Uint32 flags);\n\n/** This function cleans up specific SDL subsystems */\nextern DECLSPEC void SDLCALL SDL_QuitSubSystem(Uint32 flags);\n\n/** This function returns mask of the specified subsystems which have\n *  been initialized.\n *  If 'flags' is 0, it returns a mask of all initialized subsystems.\n */\nextern DECLSPEC Uint32 SDLCALL SDL_WasInit(Uint32 flags);\n\n/** This function cleans up all initialized subsystems and unloads the\n *  dynamically linked library.  You should call it upon all exit conditions.\n */\nextern DECLSPEC void SDLCALL SDL_Quit(void);\n\n/* Ends C function definitions when using C++ */\n#ifdef __cplusplus\n}\n#endif\n#include \"close_code.h\"\n\n#endif /* _SDL_H */\n"
  },
  {
    "path": "other/sdl/include/SDL_active.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/**\n *  @file SDL_active.h\n *  Include file for SDL application focus event handling \n */\n\n#ifndef _SDL_active_h\n#define _SDL_active_h\n\n#include \"SDL_stdinc.h\"\n#include \"SDL_error.h\"\n\n#include \"begin_code.h\"\n/* Set up for C function definitions, even when using C++ */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/** @name The available application states */\n/*@{*/\n#define SDL_APPMOUSEFOCUS\t0x01\t\t/**< The app has mouse coverage */\n#define SDL_APPINPUTFOCUS\t0x02\t\t/**< The app has input focus */\n#define SDL_APPACTIVE\t\t0x04\t\t/**< The application is active */\n/*@}*/\n\n/* Function prototypes */\n/** \n * This function returns the current state of the application, which is a\n * bitwise combination of SDL_APPMOUSEFOCUS, SDL_APPINPUTFOCUS, and\n * SDL_APPACTIVE.  If SDL_APPACTIVE is set, then the user is able to\n * see your application, otherwise it has been iconified or disabled.\n */\nextern DECLSPEC Uint8 SDLCALL SDL_GetAppState(void);\n\n\n/* Ends C function definitions when using C++ */\n#ifdef __cplusplus\n}\n#endif\n#include \"close_code.h\"\n\n#endif /* _SDL_active_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_audio.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/**\n *  @file SDL_audio.h\n *  Access to the raw audio mixing buffer for the SDL library\n */\n\n#ifndef _SDL_audio_h\n#define _SDL_audio_h\n\n#include \"SDL_stdinc.h\"\n#include \"SDL_error.h\"\n#include \"SDL_endian.h\"\n#include \"SDL_mutex.h\"\n#include \"SDL_thread.h\"\n#include \"SDL_rwops.h\"\n\n#include \"begin_code.h\"\n/* Set up for C function definitions, even when using C++ */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * When filling in the desired audio spec structure,\n * - 'desired->freq' should be the desired audio frequency in samples-per-second.\n * - 'desired->format' should be the desired audio format.\n * - 'desired->samples' is the desired size of the audio buffer, in samples.\n *     This number should be a power of two, and may be adjusted by the audio\n *     driver to a value more suitable for the hardware.  Good values seem to\n *     range between 512 and 8096 inclusive, depending on the application and\n *     CPU speed.  Smaller values yield faster response time, but can lead\n *     to underflow if the application is doing heavy processing and cannot\n *     fill the audio buffer in time.  A stereo sample consists of both right\n *     and left channels in LR ordering.\n *     Note that the number of samples is directly related to time by the\n *     following formula:  ms = (samples*1000)/freq\n * - 'desired->size' is the size in bytes of the audio buffer, and is\n *     calculated by SDL_OpenAudio().\n * - 'desired->silence' is the value used to set the buffer to silence,\n *     and is calculated by SDL_OpenAudio().\n * - 'desired->callback' should be set to a function that will be called\n *     when the audio device is ready for more data.  It is passed a pointer\n *     to the audio buffer, and the length in bytes of the audio buffer.\n *     This function usually runs in a separate thread, and so you should\n *     protect data structures that it accesses by calling SDL_LockAudio()\n *     and SDL_UnlockAudio() in your code.\n * - 'desired->userdata' is passed as the first parameter to your callback\n *     function.\n *\n * @note The calculated values in this structure are calculated by SDL_OpenAudio()\n *\n */\ntypedef struct SDL_AudioSpec {\n\tint freq;\t\t/**< DSP frequency -- samples per second */\n\tUint16 format;\t\t/**< Audio data format */\n\tUint8  channels;\t/**< Number of channels: 1 mono, 2 stereo */\n\tUint8  silence;\t\t/**< Audio buffer silence value (calculated) */\n\tUint16 samples;\t\t/**< Audio buffer size in samples (power of 2) */\n\tUint16 padding;\t\t/**< Necessary for some compile environments */\n\tUint32 size;\t\t/**< Audio buffer size in bytes (calculated) */\n\t/**\n\t *  This function is called when the audio device needs more data.\n\t *\n\t *  @param[out] stream\tA pointer to the audio data buffer\n\t *  @param[in]  len\tThe length of the audio buffer in bytes.\n\t *\n\t *  Once the callback returns, the buffer will no longer be valid.\n\t *  Stereo samples are stored in a LRLRLR ordering.\n\t */\n\tvoid (SDLCALL *callback)(void *userdata, Uint8 *stream, int len);\n\tvoid  *userdata;\n} SDL_AudioSpec;\n\n/**\n *  @name Audio format flags\n *  defaults to LSB byte order\n */\n/*@{*/\n#define AUDIO_U8\t0x0008\t/**< Unsigned 8-bit samples */\n#define AUDIO_S8\t0x8008\t/**< Signed 8-bit samples */\n#define AUDIO_U16LSB\t0x0010\t/**< Unsigned 16-bit samples */\n#define AUDIO_S16LSB\t0x8010\t/**< Signed 16-bit samples */\n#define AUDIO_U16MSB\t0x1010\t/**< As above, but big-endian byte order */\n#define AUDIO_S16MSB\t0x9010\t/**< As above, but big-endian byte order */\n#define AUDIO_U16\tAUDIO_U16LSB\n#define AUDIO_S16\tAUDIO_S16LSB\n\n/**\n *  @name Native audio byte ordering\n */\n/*@{*/\n#if SDL_BYTEORDER == SDL_LIL_ENDIAN\n#define AUDIO_U16SYS\tAUDIO_U16LSB\n#define AUDIO_S16SYS\tAUDIO_S16LSB\n#else\n#define AUDIO_U16SYS\tAUDIO_U16MSB\n#define AUDIO_S16SYS\tAUDIO_S16MSB\n#endif\n/*@}*/\n\n/*@}*/\n\n\n/** A structure to hold a set of audio conversion filters and buffers */\ntypedef struct SDL_AudioCVT {\n\tint needed;\t\t\t/**< Set to 1 if conversion possible */\n\tUint16 src_format;\t\t/**< Source audio format */\n\tUint16 dst_format;\t\t/**< Target audio format */\n\tdouble rate_incr;\t\t/**< Rate conversion increment */\n\tUint8 *buf;\t\t\t/**< Buffer to hold entire audio data */\n\tint    len;\t\t\t/**< Length of original audio buffer */\n\tint    len_cvt;\t\t\t/**< Length of converted audio buffer */\n\tint    len_mult;\t\t/**< buffer must be len*len_mult big */\n\tdouble len_ratio; \t/**< Given len, final size is len*len_ratio */\n\tvoid (SDLCALL *filters[10])(struct SDL_AudioCVT *cvt, Uint16 format);\n\tint filter_index;\t\t/**< Current audio conversion function */\n} SDL_AudioCVT;\n\n\n/* Function prototypes */\n\n/**\n * @name Audio Init and Quit\n * These functions are used internally, and should not be used unless you\n * have a specific need to specify the audio driver you want to use.\n * You should normally use SDL_Init() or SDL_InitSubSystem().\n */\n/*@{*/\nextern DECLSPEC int SDLCALL SDL_AudioInit(const char *driver_name);\nextern DECLSPEC void SDLCALL SDL_AudioQuit(void);\n/*@}*/\n\n/**\n * This function fills the given character buffer with the name of the\n * current audio driver, and returns a pointer to it if the audio driver has\n * been initialized.  It returns NULL if no driver has been initialized.\n */\nextern DECLSPEC char * SDLCALL SDL_AudioDriverName(char *namebuf, int maxlen);\n\n/**\n * This function opens the audio device with the desired parameters, and\n * returns 0 if successful, placing the actual hardware parameters in the\n * structure pointed to by 'obtained'.  If 'obtained' is NULL, the audio\n * data passed to the callback function will be guaranteed to be in the\n * requested format, and will be automatically converted to the hardware\n * audio format if necessary.  This function returns -1 if it failed \n * to open the audio device, or couldn't set up the audio thread.\n *\n * The audio device starts out playing silence when it's opened, and should\n * be enabled for playing by calling SDL_PauseAudio(0) when you are ready\n * for your audio callback function to be called.  Since the audio driver\n * may modify the requested size of the audio buffer, you should allocate\n * any local mixing buffers after you open the audio device.\n *\n * @sa SDL_AudioSpec\n */\nextern DECLSPEC int SDLCALL SDL_OpenAudio(SDL_AudioSpec *desired, SDL_AudioSpec *obtained);\n\ntypedef enum {\n\tSDL_AUDIO_STOPPED = 0,\n\tSDL_AUDIO_PLAYING,\n\tSDL_AUDIO_PAUSED\n} SDL_audiostatus;\n\n/** Get the current audio state */\nextern DECLSPEC SDL_audiostatus SDLCALL SDL_GetAudioStatus(void);\n\n/**\n * This function pauses and unpauses the audio callback processing.\n * It should be called with a parameter of 0 after opening the audio\n * device to start playing sound.  This is so you can safely initialize\n * data for your callback function after opening the audio device.\n * Silence will be written to the audio device during the pause.\n */\nextern DECLSPEC void SDLCALL SDL_PauseAudio(int pause_on);\n\n/**\n * This function loads a WAVE from the data source, automatically freeing\n * that source if 'freesrc' is non-zero.  For example, to load a WAVE file,\n * you could do:\n *\t@code SDL_LoadWAV_RW(SDL_RWFromFile(\"sample.wav\", \"rb\"), 1, ...); @endcode\n *\n * If this function succeeds, it returns the given SDL_AudioSpec,\n * filled with the audio data format of the wave data, and sets\n * 'audio_buf' to a malloc()'d buffer containing the audio data,\n * and sets 'audio_len' to the length of that audio buffer, in bytes.\n * You need to free the audio buffer with SDL_FreeWAV() when you are \n * done with it.\n *\n * This function returns NULL and sets the SDL error message if the \n * wave file cannot be opened, uses an unknown data format, or is \n * corrupt.  Currently raw and MS-ADPCM WAVE files are supported.\n */\nextern DECLSPEC SDL_AudioSpec * SDLCALL SDL_LoadWAV_RW(SDL_RWops *src, int freesrc, SDL_AudioSpec *spec, Uint8 **audio_buf, Uint32 *audio_len);\n\n/** Compatibility convenience function -- loads a WAV from a file */\n#define SDL_LoadWAV(file, spec, audio_buf, audio_len) \\\n\tSDL_LoadWAV_RW(SDL_RWFromFile(file, \"rb\"),1, spec,audio_buf,audio_len)\n\n/**\n * This function frees data previously allocated with SDL_LoadWAV_RW()\n */\nextern DECLSPEC void SDLCALL SDL_FreeWAV(Uint8 *audio_buf);\n\n/**\n * This function takes a source format and rate and a destination format\n * and rate, and initializes the 'cvt' structure with information needed\n * by SDL_ConvertAudio() to convert a buffer of audio data from one format\n * to the other.\n *\n * @return This function returns 0, or -1 if there was an error.\n */\nextern DECLSPEC int SDLCALL SDL_BuildAudioCVT(SDL_AudioCVT *cvt,\n\t\tUint16 src_format, Uint8 src_channels, int src_rate,\n\t\tUint16 dst_format, Uint8 dst_channels, int dst_rate);\n\n/**\n * Once you have initialized the 'cvt' structure using SDL_BuildAudioCVT(),\n * created an audio buffer cvt->buf, and filled it with cvt->len bytes of\n * audio data in the source format, this function will convert it in-place\n * to the desired format.\n * The data conversion may expand the size of the audio data, so the buffer\n * cvt->buf should be allocated after the cvt structure is initialized by\n * SDL_BuildAudioCVT(), and should be cvt->len*cvt->len_mult bytes long.\n */\nextern DECLSPEC int SDLCALL SDL_ConvertAudio(SDL_AudioCVT *cvt);\n\n\n#define SDL_MIX_MAXVOLUME 128\n/**\n * This takes two audio buffers of the playing audio format and mixes\n * them, performing addition, volume adjustment, and overflow clipping.\n * The volume ranges from 0 - 128, and should be set to SDL_MIX_MAXVOLUME\n * for full audio volume.  Note this does not change hardware volume.\n * This is provided for convenience -- you can mix your own audio data.\n */\nextern DECLSPEC void SDLCALL SDL_MixAudio(Uint8 *dst, const Uint8 *src, Uint32 len, int volume);\n\n/**\n * @name Audio Locks\n * The lock manipulated by these functions protects the callback function.\n * During a LockAudio/UnlockAudio pair, you can be guaranteed that the\n * callback function is not running.  Do not call these from the callback\n * function or you will cause deadlock.\n */\n/*@{*/\nextern DECLSPEC void SDLCALL SDL_LockAudio(void);\nextern DECLSPEC void SDLCALL SDL_UnlockAudio(void);\n/*@}*/\n\n/**\n * This function shuts down audio processing and closes the audio device.\n */\nextern DECLSPEC void SDLCALL SDL_CloseAudio(void);\n\n\n/* Ends C function definitions when using C++ */\n#ifdef __cplusplus\n}\n#endif\n#include \"close_code.h\"\n\n#endif /* _SDL_audio_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_byteorder.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/**\n *  @file SDL_byteorder.h\n *  @deprecated Use SDL_endian.h instead\n */\n\n/* DEPRECATED */\n#include \"SDL_endian.h\"\n"
  },
  {
    "path": "other/sdl/include/SDL_cdrom.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/**\n *  @file SDL_cdrom.h\n *  This is the CD-audio control API for Simple DirectMedia Layer\n */\n\n#ifndef _SDL_cdrom_h\n#define _SDL_cdrom_h\n\n#include \"SDL_stdinc.h\"\n#include \"SDL_error.h\"\n\n#include \"begin_code.h\"\n/* Set up for C function definitions, even when using C++ */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n *  @file SDL_cdrom.h\n *  In order to use these functions, SDL_Init() must have been called\n *  with the SDL_INIT_CDROM flag.  This causes SDL to scan the system\n *  for CD-ROM drives, and load appropriate drivers.\n */\n\n/** The maximum number of CD-ROM tracks on a disk */\n#define SDL_MAX_TRACKS\t99\n\n/** @name Track Types\n *  The types of CD-ROM track possible\n */\n/*@{*/\n#define SDL_AUDIO_TRACK\t0x00\n#define SDL_DATA_TRACK\t0x04\n/*@}*/\n\n/** The possible states which a CD-ROM drive can be in. */\ntypedef enum {\n\tCD_TRAYEMPTY,\n\tCD_STOPPED,\n\tCD_PLAYING,\n\tCD_PAUSED,\n\tCD_ERROR = -1\n} CDstatus;\n\n/** Given a status, returns true if there's a disk in the drive */\n#define CD_INDRIVE(status)\t((int)(status) > 0)\n\ntypedef struct SDL_CDtrack {\n\tUint8 id;\t\t/**< Track number */\n\tUint8 type;\t\t/**< Data or audio track */\n\tUint16 unused;\n\tUint32 length;\t\t/**< Length, in frames, of this track */\n\tUint32 offset;\t\t/**< Offset, in frames, from start of disk */\n} SDL_CDtrack;\n\n/** This structure is only current as of the last call to SDL_CDStatus() */\ntypedef struct SDL_CD {\n\tint id;\t\t\t/**< Private drive identifier */\n\tCDstatus status;\t/**< Current drive status */\n\n\t/** The rest of this structure is only valid if there's a CD in drive */\n        /*@{*/\n\tint numtracks;\t\t/**< Number of tracks on disk */\n\tint cur_track;\t\t/**< Current track position */\n\tint cur_frame;\t\t/**< Current frame offset within current track */\n\tSDL_CDtrack track[SDL_MAX_TRACKS+1];\n        /*@}*/\n} SDL_CD;\n\n/** @name Frames / MSF Conversion Functions\n *  Conversion functions from frames to Minute/Second/Frames and vice versa\n */\n/*@{*/\n#define CD_FPS\t75\n#define FRAMES_TO_MSF(f, M,S,F)\t{\t\t\t\t\t\\\n\tint value = f;\t\t\t\t\t\t\t\\\n\t*(F) = value%CD_FPS;\t\t\t\t\t\t\\\n\tvalue /= CD_FPS;\t\t\t\t\t\t\\\n\t*(S) = value%60;\t\t\t\t\t\t\\\n\tvalue /= 60;\t\t\t\t\t\t\t\\\n\t*(M) = value;\t\t\t\t\t\t\t\\\n}\n#define MSF_TO_FRAMES(M, S, F)\t((M)*60*CD_FPS+(S)*CD_FPS+(F))\n/*@}*/\n\n/* CD-audio API functions: */\n\n/**\n *  Returns the number of CD-ROM drives on the system, or -1 if\n *  SDL_Init() has not been called with the SDL_INIT_CDROM flag.\n */\nextern DECLSPEC int SDLCALL SDL_CDNumDrives(void);\n\n/**\n *  Returns a human-readable, system-dependent identifier for the CD-ROM.\n *  Example:\n *   - \"/dev/cdrom\"\n *   - \"E:\"\n *   - \"/dev/disk/ide/1/master\"\n */\nextern DECLSPEC const char * SDLCALL SDL_CDName(int drive);\n\n/**\n *  Opens a CD-ROM drive for access.  It returns a drive handle on success,\n *  or NULL if the drive was invalid or busy.  This newly opened CD-ROM\n *  becomes the default CD used when other CD functions are passed a NULL\n *  CD-ROM handle.\n *  Drives are numbered starting with 0.  Drive 0 is the system default CD-ROM.\n */\nextern DECLSPEC SDL_CD * SDLCALL SDL_CDOpen(int drive);\n\n/**\n *  This function returns the current status of the given drive.\n *  If the drive has a CD in it, the table of contents of the CD and current\n *  play position of the CD will be stored in the SDL_CD structure.\n */\nextern DECLSPEC CDstatus SDLCALL SDL_CDStatus(SDL_CD *cdrom);\n\n/**\n *  Play the given CD starting at 'start_track' and 'start_frame' for 'ntracks'\n *  tracks and 'nframes' frames.  If both 'ntrack' and 'nframe' are 0, play \n *  until the end of the CD.  This function will skip data tracks.\n *  This function should only be called after calling SDL_CDStatus() to \n *  get track information about the CD.\n *  For example:\n *      @code\n *\t// Play entire CD:\n *\tif ( CD_INDRIVE(SDL_CDStatus(cdrom)) )\n *\t\tSDL_CDPlayTracks(cdrom, 0, 0, 0, 0);\n *\t// Play last track:\n *\tif ( CD_INDRIVE(SDL_CDStatus(cdrom)) ) {\n *\t\tSDL_CDPlayTracks(cdrom, cdrom->numtracks-1, 0, 0, 0);\n *\t}\n *\t// Play first and second track and 10 seconds of third track:\n *\tif ( CD_INDRIVE(SDL_CDStatus(cdrom)) )\n *\t\tSDL_CDPlayTracks(cdrom, 0, 0, 2, 10);\n *      @endcode\n *\n *  @return This function returns 0, or -1 if there was an error.\n */\nextern DECLSPEC int SDLCALL SDL_CDPlayTracks(SDL_CD *cdrom,\n\t\tint start_track, int start_frame, int ntracks, int nframes);\n\n/**\n *  Play the given CD starting at 'start' frame for 'length' frames.\n *  @return It returns 0, or -1 if there was an error.\n */\nextern DECLSPEC int SDLCALL SDL_CDPlay(SDL_CD *cdrom, int start, int length);\n\n/** Pause play\n *  @return returns 0, or -1 on error\n */\nextern DECLSPEC int SDLCALL SDL_CDPause(SDL_CD *cdrom);\n\n/** Resume play\n *  @return returns 0, or -1 on error\n */\nextern DECLSPEC int SDLCALL SDL_CDResume(SDL_CD *cdrom);\n\n/** Stop play\n *  @return returns 0, or -1 on error\n */\nextern DECLSPEC int SDLCALL SDL_CDStop(SDL_CD *cdrom);\n\n/** Eject CD-ROM\n *  @return returns 0, or -1 on error\n */\nextern DECLSPEC int SDLCALL SDL_CDEject(SDL_CD *cdrom);\n\n/** Closes the handle for the CD-ROM drive */\nextern DECLSPEC void SDLCALL SDL_CDClose(SDL_CD *cdrom);\n\n\n/* Ends C function definitions when using C++ */\n#ifdef __cplusplus\n}\n#endif\n#include \"close_code.h\"\n\n#endif /* _SDL_video_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_config.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n#ifndef _SDL_config_h\n#define _SDL_config_h\n\n#include \"SDL_platform.h\"\n\n/* Add any platform that doesn't build using the configure system */\n#if defined(__DREAMCAST__)\n#include \"SDL_config_dreamcast.h\"\n#elif defined(__MACOS__)\n#include \"SDL_config_macos.h\"\n#elif defined(__MACOSX__)\n#include \"SDL_config_macosx.h\"\n#elif defined(__SYMBIAN32__)\n#include \"SDL_config_symbian.h\"  /* must be before win32! */\n#elif defined(__WIN32__)\n#include \"SDL_config_win32.h\"\n#elif defined(__OS2__)\n#include \"SDL_config_os2.h\"\n#else\n#include \"SDL_config_minimal.h\"\n#endif /* platform config */\n\n#endif /* _SDL_config_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_config.h.default",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2006 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n#ifndef _SDL_config_h\n#define _SDL_config_h\n\n#include \"SDL_platform.h\"\n\n/* Add any platform that doesn't build using the configure system */\n#if defined(__DREAMCAST__)\n#include \"SDL_config_dreamcast.h\"\n#elif defined(__MACOS__)\n#include \"SDL_config_macos.h\"\n#elif defined(__MACOSX__)\n#include \"SDL_config_macosx.h\"\n#elif defined(__SYMBIAN32__)\n#include \"SDL_config_symbian.h\"  /* must be before win32! */\n#elif defined(__WIN32__)\n#include \"SDL_config_win32.h\"\n#elif defined(__OS2__)\n#include \"SDL_config_os2.h\"\n#else\n#include \"SDL_config_minimal.h\"\n#endif /* platform config */\n\n#endif /* _SDL_config_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_config.h.in",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2006 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n#ifndef _SDL_config_h\n#define _SDL_config_h\n\n/* This is a set of defines to configure the SDL features */\n\n/* General platform specific identifiers */\n#include \"SDL_platform.h\"\n\n/* Make sure that this isn't included by Visual C++ */\n#ifdef _MSC_VER\n#error You should copy include/SDL_config.h.default to include/SDL_config.h\n#endif\n\n/* C language features */\n#undef const\n#undef inline\n#undef volatile\n\n/* C datatypes */\n#undef size_t\n#undef int8_t\n#undef uint8_t\n#undef int16_t\n#undef uint16_t\n#undef int32_t\n#undef uint32_t\n#undef int64_t\n#undef uint64_t\n#undef uintptr_t\n#undef SDL_HAS_64BIT_TYPE\n\n/* Endianness */\n#undef SDL_BYTEORDER\n\n/* Comment this if you want to build without any C library requirements */\n#undef HAVE_LIBC\n#if HAVE_LIBC\n\n/* Useful headers */\n#undef HAVE_ALLOCA_H\n#undef HAVE_SYS_TYPES_H\n#undef HAVE_STDIO_H\n#undef STDC_HEADERS\n#undef HAVE_STDLIB_H\n#undef HAVE_STDARG_H\n#undef HAVE_MALLOC_H\n#undef HAVE_MEMORY_H\n#undef HAVE_STRING_H\n#undef HAVE_STRINGS_H\n#undef HAVE_INTTYPES_H\n#undef HAVE_STDINT_H\n#undef HAVE_CTYPE_H\n#undef HAVE_MATH_H\n#undef HAVE_ICONV_H\n#undef HAVE_SIGNAL_H\n#undef HAVE_ALTIVEC_H\n\n/* C library functions */\n#undef HAVE_MALLOC\n#undef HAVE_CALLOC\n#undef HAVE_REALLOC\n#undef HAVE_FREE\n#undef HAVE_ALLOCA\n#ifndef _WIN32 /* Don't use C runtime versions of these on Windows */\n#undef HAVE_GETENV\n#undef HAVE_PUTENV\n#undef HAVE_UNSETENV\n#endif\n#undef HAVE_QSORT\n#undef HAVE_ABS\n#undef HAVE_BCOPY\n#undef HAVE_MEMSET\n#undef HAVE_MEMCPY\n#undef HAVE_MEMMOVE\n#undef HAVE_MEMCMP\n#undef HAVE_STRLEN\n#undef HAVE_STRLCPY\n#undef HAVE_STRLCAT\n#undef HAVE_STRDUP\n#undef HAVE__STRREV\n#undef HAVE__STRUPR\n#undef HAVE__STRLWR\n#undef HAVE_INDEX\n#undef HAVE_RINDEX\n#undef HAVE_STRCHR\n#undef HAVE_STRRCHR\n#undef HAVE_STRSTR\n#undef HAVE_ITOA\n#undef HAVE__LTOA\n#undef HAVE__UITOA\n#undef HAVE__ULTOA\n#undef HAVE_STRTOL\n#undef HAVE_STRTOUL\n#undef HAVE__I64TOA\n#undef HAVE__UI64TOA\n#undef HAVE_STRTOLL\n#undef HAVE_STRTOULL\n#undef HAVE_STRTOD\n#undef HAVE_ATOI\n#undef HAVE_ATOF\n#undef HAVE_STRCMP\n#undef HAVE_STRNCMP\n#undef HAVE__STRICMP\n#undef HAVE_STRCASECMP\n#undef HAVE__STRNICMP\n#undef HAVE_STRNCASECMP\n#undef HAVE_SSCANF\n#undef HAVE_SNPRINTF\n#undef HAVE_VSNPRINTF\n#undef HAVE_ICONV\n#undef HAVE_SIGACTION\n#undef HAVE_SETJMP\n#undef HAVE_NANOSLEEP\n#undef HAVE_CLOCK_GETTIME\n#undef HAVE_DLVSYM\n#undef HAVE_GETPAGESIZE\n\n#else\n/* We may need some replacement for stdarg.h here */\n#include <stdarg.h>\n#endif /* HAVE_LIBC */\n\n/* Allow disabling of core subsystems */\n#undef SDL_AUDIO_DISABLED\n#undef SDL_CDROM_DISABLED\n#undef SDL_CPUINFO_DISABLED\n#undef SDL_EVENTS_DISABLED\n#undef SDL_FILE_DISABLED\n#undef SDL_JOYSTICK_DISABLED\n#undef SDL_LOADSO_DISABLED\n#undef SDL_THREADS_DISABLED\n#undef SDL_TIMERS_DISABLED\n#undef SDL_VIDEO_DISABLED\n\n/* Enable various audio drivers */\n#undef SDL_AUDIO_DRIVER_ALSA\n#undef SDL_AUDIO_DRIVER_ALSA_DYNAMIC\n#undef SDL_AUDIO_DRIVER_ARTS\n#undef SDL_AUDIO_DRIVER_ARTS_DYNAMIC\n#undef SDL_AUDIO_DRIVER_BAUDIO\n#undef SDL_AUDIO_DRIVER_BSD\n#undef SDL_AUDIO_DRIVER_COREAUDIO\n#undef SDL_AUDIO_DRIVER_DART\n#undef SDL_AUDIO_DRIVER_DC\n#undef SDL_AUDIO_DRIVER_DISK\n#undef SDL_AUDIO_DRIVER_DUMMY\n#undef SDL_AUDIO_DRIVER_DMEDIA\n#undef SDL_AUDIO_DRIVER_DSOUND\n#undef SDL_AUDIO_DRIVER_PULSE\n#undef SDL_AUDIO_DRIVER_PULSE_DYNAMIC\n#undef SDL_AUDIO_DRIVER_ESD\n#undef SDL_AUDIO_DRIVER_ESD_DYNAMIC\n#undef SDL_AUDIO_DRIVER_MINT\n#undef SDL_AUDIO_DRIVER_MMEAUDIO\n#undef SDL_AUDIO_DRIVER_NAS\n#undef SDL_AUDIO_DRIVER_OSS\n#undef SDL_AUDIO_DRIVER_OSS_SOUNDCARD_H\n#undef SDL_AUDIO_DRIVER_PAUD\n#undef SDL_AUDIO_DRIVER_QNXNTO\n#undef SDL_AUDIO_DRIVER_SNDMGR\n#undef SDL_AUDIO_DRIVER_SUNAUDIO\n#undef SDL_AUDIO_DRIVER_WAVEOUT\n\n/* Enable various cdrom drivers */\n#undef SDL_CDROM_AIX\n#undef SDL_CDROM_BEOS\n#undef SDL_CDROM_BSDI\n#undef SDL_CDROM_DC\n#undef SDL_CDROM_DUMMY\n#undef SDL_CDROM_FREEBSD\n#undef SDL_CDROM_LINUX\n#undef SDL_CDROM_MACOS\n#undef SDL_CDROM_MACOSX\n#undef SDL_CDROM_MINT\n#undef SDL_CDROM_OPENBSD\n#undef SDL_CDROM_OS2\n#undef SDL_CDROM_OSF\n#undef SDL_CDROM_QNX\n#undef SDL_CDROM_WIN32\n\n/* Enable various input drivers */\n#undef SDL_INPUT_TSLIB\n#undef SDL_JOYSTICK_BEOS\n#undef SDL_JOYSTICK_DC\n#undef SDL_JOYSTICK_DUMMY\n#undef SDL_JOYSTICK_IOKIT\n#undef SDL_JOYSTICK_LINUX\n#undef SDL_JOYSTICK_LINUXEV\n#undef SDL_JOYSTICK_MACOS\n#undef SDL_JOYSTICK_MINT\n#undef SDL_JOYSTICK_OS2\n#undef SDL_JOYSTICK_RISCOS\n#undef SDL_JOYSTICK_WINMM\n#undef SDL_JOYSTICK_USBHID\n#undef SDL_JOYSTICK_USBHID_MACHINE_JOYSTICK_H\n\n/* Enable various shared object loading systems */\n#undef SDL_LOADSO_BEOS\n#undef SDL_LOADSO_DLCOMPAT\n#undef SDL_LOADSO_DLOPEN\n#undef SDL_LOADSO_DUMMY\n#undef SDL_LOADSO_LDG\n#undef SDL_LOADSO_MACOS\n#undef SDL_LOADSO_OS2\n#undef SDL_LOADSO_WIN32\n\n/* Enable various threading systems */\n#undef SDL_THREAD_BEOS\n#undef SDL_THREAD_DC\n#undef SDL_THREAD_OS2\n#undef SDL_THREAD_PTH\n#undef SDL_THREAD_PTHREAD\n#undef SDL_THREAD_PTHREAD_RECURSIVE_MUTEX\n#undef SDL_THREAD_PTHREAD_RECURSIVE_MUTEX_NP\n#undef SDL_THREAD_SPROC\n#undef SDL_THREAD_WIN32\n\n/* Enable various timer systems */\n#undef SDL_TIMER_BEOS\n#undef SDL_TIMER_DC\n#undef SDL_TIMER_DUMMY\n#undef SDL_TIMER_MACOS\n#undef SDL_TIMER_MINT\n#undef SDL_TIMER_OS2\n#undef SDL_TIMER_RISCOS\n#undef SDL_TIMER_UNIX\n#undef SDL_TIMER_WIN32\n#undef SDL_TIMER_WINCE\n\n/* Enable various video drivers */\n#undef SDL_VIDEO_DRIVER_AALIB\n#undef SDL_VIDEO_DRIVER_BWINDOW\n#undef SDL_VIDEO_DRIVER_DC\n#undef SDL_VIDEO_DRIVER_DDRAW\n#undef SDL_VIDEO_DRIVER_DGA\n#undef SDL_VIDEO_DRIVER_DIRECTFB\n#undef SDL_VIDEO_DRIVER_DRAWSPROCKET\n#undef SDL_VIDEO_DRIVER_DUMMY\n#undef SDL_VIDEO_DRIVER_FBCON\n#undef SDL_VIDEO_DRIVER_GAPI\n#undef SDL_VIDEO_DRIVER_GEM\n#undef SDL_VIDEO_DRIVER_GGI\n#undef SDL_VIDEO_DRIVER_IPOD\n#undef SDL_VIDEO_DRIVER_NANOX\n#undef SDL_VIDEO_DRIVER_OS2FS\n#undef SDL_VIDEO_DRIVER_PHOTON\n#undef SDL_VIDEO_DRIVER_PICOGUI\n#undef SDL_VIDEO_DRIVER_PS2GS\n#undef SDL_VIDEO_DRIVER_QTOPIA\n#undef SDL_VIDEO_DRIVER_QUARTZ\n#undef SDL_VIDEO_DRIVER_RISCOS\n#undef SDL_VIDEO_DRIVER_SVGALIB\n#undef SDL_VIDEO_DRIVER_TOOLBOX\n#undef SDL_VIDEO_DRIVER_VGL\n#undef SDL_VIDEO_DRIVER_WINDIB\n#undef SDL_VIDEO_DRIVER_WSCONS\n#undef SDL_VIDEO_DRIVER_X11\n#undef SDL_VIDEO_DRIVER_X11_DGAMOUSE\n#undef SDL_VIDEO_DRIVER_X11_DPMS\n#undef SDL_VIDEO_DRIVER_X11_DYNAMIC\n#undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT\n#undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR\n#undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XRENDER\n#undef SDL_VIDEO_DRIVER_X11_VIDMODE\n#undef SDL_VIDEO_DRIVER_X11_XINERAMA\n#undef SDL_VIDEO_DRIVER_X11_XME\n#undef SDL_VIDEO_DRIVER_X11_XRANDR\n#undef SDL_VIDEO_DRIVER_X11_XV\n#undef SDL_VIDEO_DRIVER_XBIOS\n\n/* Enable OpenGL support */\n#undef SDL_VIDEO_OPENGL\n#undef SDL_VIDEO_OPENGL_GLX\n#undef SDL_VIDEO_OPENGL_WGL\n#undef SDL_VIDEO_OPENGL_OSMESA\n#undef SDL_VIDEO_OPENGL_OSMESA_DYNAMIC\n\n/* Enable assembly routines */\n#undef SDL_ASSEMBLY_ROUTINES\n#undef SDL_HERMES_BLITTERS\n#undef SDL_ALTIVEC_BLITTERS\n\n#endif /* _SDL_config_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_config_amiga.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2006 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n#ifndef _SDL_config_amiga_h\n#define _SDL_config_amiga_h\n\n#include \"SDL_platform.h\"\n\n/* This is a set of defines to configure the SDL features */\n\n#define SDL_HAS_64BIT_TYPE\t1\n\n/* Useful headers */\n#define HAVE_SYS_TYPES_H\t1\n#define HAVE_STDIO_H\t1\n#define STDC_HEADERS\t1\n#define HAVE_STRING_H\t1\n#define HAVE_INTTYPES_H\t1\n#define HAVE_SIGNAL_H\t1\n\n/* C library functions */\n#define HAVE_MALLOC\t1\n#define HAVE_CALLOC\t1\n#define HAVE_REALLOC\t1\n#define HAVE_FREE\t1\n#define HAVE_ALLOCA\t1\n#define HAVE_GETENV\t1\n#define HAVE_PUTENV\t1\n#define HAVE_MEMSET\t1\n#define HAVE_MEMCPY\t1\n#define HAVE_MEMMOVE\t1\n#define HAVE_MEMCMP\t1\n\n/* Enable various audio drivers */\n#define SDL_AUDIO_DRIVER_AHI\t1\n#define SDL_AUDIO_DRIVER_DISK\t1\n#define SDL_AUDIO_DRIVER_DUMMY\t1\n\n/* Enable various cdrom drivers */\n#define SDL_CDROM_DUMMY\t1\n\n/* Enable various input drivers */\n#define SDL_JOYSTICK_AMIGA\t1\n\n/* Enable various shared object loading systems */\n#define SDL_LOADSO_DUMMY\t1\n\n/* Enable various threading systems */\n#define SDL_THREAD_AMIGA\t1\n\n/* Enable various timer systems */\n#define SDL_TIMER_AMIGA\t1\n\n/* Enable various video drivers */\n#define SDL_VIDEO_DRIVER_CYBERGRAPHICS\t1\n#define SDL_VIDEO_DRIVER_DUMMY\t1\n\n/* Enable OpenGL support */\n#define SDL_VIDEO_OPENGL\t1\n\n#endif /* _SDL_config_amiga_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_config_dreamcast.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n#ifndef _SDL_config_dreamcast_h\n#define _SDL_config_dreamcast_h\n\n#include \"SDL_platform.h\"\n\n/* This is a set of defines to configure the SDL features */\n\ntypedef signed char int8_t;\ntypedef unsigned char uint8_t;\ntypedef signed short int16_t;\ntypedef unsigned short uint16_t;\ntypedef signed int int32_t;\ntypedef unsigned int uint32_t;\ntypedef signed long long int64_t;\ntypedef unsigned long long uint64_t;\ntypedef unsigned long uintptr_t;\n#define SDL_HAS_64BIT_TYPE\t1\n\n/* Useful headers */\n#define HAVE_SYS_TYPES_H\t1\n#define HAVE_STDIO_H\t1\n#define STDC_HEADERS\t1\n#define HAVE_STRING_H\t1\n#define HAVE_CTYPE_H\t1\n\n/* C library functions */\n#define HAVE_MALLOC\t1\n#define HAVE_CALLOC\t1\n#define HAVE_REALLOC\t1\n#define HAVE_FREE\t1\n#define HAVE_ALLOCA\t1\n#define HAVE_GETENV\t1\n#define HAVE_PUTENV\t1\n#define HAVE_QSORT\t1\n#define HAVE_ABS\t1\n#define HAVE_BCOPY\t1\n#define HAVE_MEMSET\t1\n#define HAVE_MEMCPY\t1\n#define HAVE_MEMMOVE\t1\n#define HAVE_MEMCMP\t1\n#define HAVE_STRLEN\t1\n#define HAVE_STRDUP\t1\n#define HAVE_INDEX\t1\n#define HAVE_RINDEX\t1\n#define HAVE_STRCHR\t1\n#define HAVE_STRRCHR\t1\n#define HAVE_STRSTR\t1\n#define HAVE_STRTOL\t1\n#define HAVE_STRTOD\t1\n#define HAVE_ATOI\t1\n#define HAVE_ATOF\t1\n#define HAVE_STRCMP\t1\n#define HAVE_STRNCMP\t1\n#define HAVE_STRICMP\t1\n#define HAVE_STRCASECMP\t1\n#define HAVE_SSCANF\t1\n#define HAVE_SNPRINTF\t1\n#define HAVE_VSNPRINTF\t1\n\n/* Enable various audio drivers */\n#define SDL_AUDIO_DRIVER_DC\t1\n#define SDL_AUDIO_DRIVER_DISK\t1\n#define SDL_AUDIO_DRIVER_DUMMY\t1\n\n/* Enable various cdrom drivers */\n#define SDL_CDROM_DC\t1\n\n/* Enable various input drivers */\n#define SDL_JOYSTICK_DC\t1\n\n/* Enable various shared object loading systems */\n#define SDL_LOADSO_DUMMY\t1\n\n/* Enable various threading systems */\n#define SDL_THREAD_DC\t1\n\n/* Enable various timer systems */\n#define SDL_TIMER_DC\t1\n\n/* Enable various video drivers */\n#define SDL_VIDEO_DRIVER_DC\t1\n#define SDL_VIDEO_DRIVER_DUMMY\t1\n\n#endif /* _SDL_config_dreamcast_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_config_macos.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n#ifndef _SDL_config_macos_h\n#define _SDL_config_macos_h\n\n#include \"SDL_platform.h\"\n\n/* This is a set of defines to configure the SDL features */\n\n#include <MacTypes.h>\n\ntypedef SInt8\tint8_t;\ntypedef UInt8\tuint8_t;\ntypedef SInt16\tint16_t;\ntypedef UInt16\tuint16_t;\ntypedef SInt32\tint32_t;\ntypedef UInt32\tuint32_t;\ntypedef SInt64\tint64_t;\ntypedef UInt64\tuint64_t;\ntypedef unsigned long\tuintptr_t;\n\n#define SDL_HAS_64BIT_TYPE\t1\n\n/* Useful headers */\n#define HAVE_STDIO_H\t1\n#define STDC_HEADERS\t1\n#define HAVE_STRING_H\t1\n#define HAVE_CTYPE_H\t1\n#define HAVE_MATH_H\t1\n#define HAVE_SIGNAL_H\t1\n\n/* C library functions */\n#define HAVE_MALLOC\t1\n#define HAVE_CALLOC\t1\n#define HAVE_REALLOC\t1\n#define HAVE_FREE\t1\n#define HAVE_ALLOCA\t1\n#define HAVE_ABS\t1\n#define HAVE_MEMSET\t1\n#define HAVE_MEMCPY\t1\n#define HAVE_MEMMOVE\t1\n#define HAVE_MEMCMP\t1\n#define HAVE_STRLEN\t1\n#define HAVE_STRCHR\t1\n#define HAVE_STRRCHR\t1\n#define HAVE_STRSTR\t1\n#define HAVE_ITOA\t1\n#define HAVE_STRTOL\t1\n#define HAVE_STRTOD\t1\n#define HAVE_ATOI\t1\n#define HAVE_ATOF\t1\n#define HAVE_STRCMP\t1\n#define HAVE_STRNCMP\t1\n#define HAVE_SSCANF\t1\n\n/* Enable various audio drivers */\n#define SDL_AUDIO_DRIVER_SNDMGR\t1\n#define SDL_AUDIO_DRIVER_DISK\t1\n#define SDL_AUDIO_DRIVER_DUMMY\t1\n\n/* Enable various cdrom drivers */\n#if TARGET_API_MAC_CARBON\n#define SDL_CDROM_DUMMY\t\t1\n#else\n#define SDL_CDROM_MACOS\t\t1\n#endif\n\n/* Enable various input drivers */\n#if TARGET_API_MAC_CARBON\n#define SDL_JOYSTICK_DUMMY\t1\n#else\n#define SDL_JOYSTICK_MACOS\t1\n#endif\n\n/* Enable various shared object loading systems */\n#define SDL_LOADSO_MACOS\t1\n\n/* Enable various threading systems */\n#define SDL_THREADS_DISABLED\t1\n\n/* Enable various timer systems */\n#define SDL_TIMER_MACOS\t1\n\n/* Enable various video drivers */\n#define SDL_VIDEO_DRIVER_DUMMY\t1\n#define SDL_VIDEO_DRIVER_DRAWSPROCKET\t1\n#define SDL_VIDEO_DRIVER_TOOLBOX\t1\n\n/* Enable OpenGL support */\n#define SDL_VIDEO_OPENGL\t1\n\n#endif /* _SDL_config_macos_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_config_macosx.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n#ifndef _SDL_config_macosx_h\n#define _SDL_config_macosx_h\n\n#include \"SDL_platform.h\"\n\n/* This gets us MAC_OS_X_VERSION_MIN_REQUIRED... */\n#include <AvailabilityMacros.h>\n\n/* This is a set of defines to configure the SDL features */\n\n#define SDL_HAS_64BIT_TYPE\t1\n\n/* Useful headers */\n/* If we specified an SDK or have a post-PowerPC chip, then alloca.h exists. */\n#if ( (MAC_OS_X_VERSION_MIN_REQUIRED >= 1030) || (!defined(__POWERPC__)) )\n#define HAVE_ALLOCA_H\t\t1\n#endif\n#define HAVE_SYS_TYPES_H\t1\n#define HAVE_STDIO_H\t1\n#define STDC_HEADERS\t1\n#define HAVE_STRING_H\t1\n#define HAVE_INTTYPES_H\t1\n#define HAVE_STDINT_H\t1\n#define HAVE_CTYPE_H\t1\n#define HAVE_MATH_H\t1\n#define HAVE_SIGNAL_H\t1\n\n/* C library functions */\n#define HAVE_MALLOC\t1\n#define HAVE_CALLOC\t1\n#define HAVE_REALLOC\t1\n#define HAVE_FREE\t1\n#define HAVE_ALLOCA\t1\n#define HAVE_GETENV\t1\n#define HAVE_PUTENV\t1\n#define HAVE_UNSETENV\t1\n#define HAVE_QSORT\t1\n#define HAVE_ABS\t1\n#define HAVE_BCOPY\t1\n#define HAVE_MEMSET\t1\n#define HAVE_MEMCPY\t1\n#define HAVE_MEMMOVE\t1\n#define HAVE_MEMCMP\t1\n#define HAVE_STRLEN\t1\n#define HAVE_STRLCPY\t1\n#define HAVE_STRLCAT\t1\n#define HAVE_STRDUP\t1\n#define HAVE_STRCHR\t1\n#define HAVE_STRRCHR\t1\n#define HAVE_STRSTR\t1\n#define HAVE_STRTOL\t1\n#define HAVE_STRTOUL\t1\n#define HAVE_STRTOLL\t1\n#define HAVE_STRTOULL\t1\n#define HAVE_STRTOD\t1\n#define HAVE_ATOI\t1\n#define HAVE_ATOF\t1\n#define HAVE_STRCMP\t1\n#define HAVE_STRNCMP\t1\n#define HAVE_STRCASECMP\t1\n#define HAVE_STRNCASECMP 1\n#define HAVE_SSCANF\t1\n#define HAVE_SNPRINTF\t1\n#define HAVE_VSNPRINTF\t1\n#define HAVE_SIGACTION\t1\n#define HAVE_SETJMP\t1\n#define HAVE_NANOSLEEP\t1\n\n/* Enable various audio drivers */\n#define SDL_AUDIO_DRIVER_COREAUDIO\t1\n#define SDL_AUDIO_DRIVER_DISK\t1\n#define SDL_AUDIO_DRIVER_DUMMY\t1\n\n/* Enable various cdrom drivers */\n#define SDL_CDROM_MACOSX\t1\n\n/* Enable various input drivers */\n#define SDL_JOYSTICK_IOKIT\t1\n\n/* Enable various shared object loading systems */\n#ifdef __ppc__\n/* For Mac OS X 10.2 compatibility */\n#define SDL_LOADSO_DLCOMPAT\t1\n#else\n#define SDL_LOADSO_DLOPEN\t1\n#endif\n\n/* Enable various threading systems */\n#define SDL_THREAD_PTHREAD\t1\n#define SDL_THREAD_PTHREAD_RECURSIVE_MUTEX\t1\n\n/* Enable various timer systems */\n#define SDL_TIMER_UNIX\t1\n\n/* Enable various video drivers */\n#define SDL_VIDEO_DRIVER_DUMMY\t1\n#if ((defined TARGET_API_MAC_CARBON) && (TARGET_API_MAC_CARBON))\n#define SDL_VIDEO_DRIVER_TOOLBOX\t1\n#else\n#define SDL_VIDEO_DRIVER_QUARTZ\t1\n#endif\n#define SDL_VIDEO_DRIVER_DGA 1\n#define SDL_VIDEO_DRIVER_X11 1\n#define SDL_VIDEO_DRIVER_X11_DGAMOUSE 1\n#define SDL_VIDEO_DRIVER_X11_DYNAMIC \"/usr/X11R6/lib/libX11.6.dylib\"\n#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT \"/usr/X11R6/lib/libXext.6.dylib\"\n#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR \"/usr/X11R6/lib/libXrandr.2.dylib\"\n#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XRENDER \"/usr/X11R6/lib/libXrender.1.dylib\"\n#define SDL_VIDEO_DRIVER_X11_VIDMODE 1\n#define SDL_VIDEO_DRIVER_X11_XINERAMA 1\n#define SDL_VIDEO_DRIVER_X11_XME 1\n#define SDL_VIDEO_DRIVER_X11_XRANDR 1\n#define SDL_VIDEO_DRIVER_X11_XV 1\n\n/* Enable OpenGL support */\n#define SDL_VIDEO_OPENGL\t1\n#define SDL_VIDEO_OPENGL_GLX 1\n\n/* Disable screensaver */\n#define SDL_VIDEO_DISABLE_SCREENSAVER\t1\n\n/* Enable assembly routines */\n#define SDL_ASSEMBLY_ROUTINES\t1\n#ifdef __ppc__\n#define SDL_ALTIVEC_BLITTERS\t1\n#endif\n\n#endif /* _SDL_config_macosx_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_config_minimal.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n#ifndef _SDL_config_minimal_h\n#define _SDL_config_minimal_h\n\n#include \"SDL_platform.h\"\n\n/* This is the minimal configuration that can be used to build SDL */\n\n#include <stdarg.h>\n\ntypedef signed char int8_t;\ntypedef unsigned char uint8_t;\ntypedef signed short int16_t;\ntypedef unsigned short uint16_t;\ntypedef signed int int32_t;\ntypedef unsigned int uint32_t;\ntypedef unsigned int size_t;\ntypedef unsigned long uintptr_t;\n\n/* Enable the dummy audio driver (src/audio/dummy/\\*.c) */\n#define SDL_AUDIO_DRIVER_DUMMY\t1\n\n/* Enable the stub cdrom driver (src/cdrom/dummy/\\*.c) */\n#define SDL_CDROM_DISABLED\t1\n\n/* Enable the stub joystick driver (src/joystick/dummy/\\*.c) */\n#define SDL_JOYSTICK_DISABLED\t1\n\n/* Enable the stub shared object loader (src/loadso/dummy/\\*.c) */\n#define SDL_LOADSO_DISABLED\t1\n\n/* Enable the stub thread support (src/thread/generic/\\*.c) */\n#define SDL_THREADS_DISABLED\t1\n\n/* Enable the stub timer support (src/timer/dummy/\\*.c) */\n#define SDL_TIMERS_DISABLED\t1\n\n/* Enable the dummy video driver (src/video/dummy/\\*.c) */\n#define SDL_VIDEO_DRIVER_DUMMY\t1\n\n#endif /* _SDL_config_minimal_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_config_nds.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n#ifndef _SDL_config_nds_h\n#define _SDL_config_nds_h\n\n#include \"SDL_platform.h\"\n\n/* This is a set of defines to configure the SDL features */\n\n/* General platform specific identifiers */\n#include \"SDL_platform.h\"\n\n/* C datatypes */\n#define SDL_HAS_64BIT_TYPE 1\n\n/* Endianness */\n#define SDL_BYTEORDER 1234\n\n/* Useful headers */\n#define HAVE_ALLOCA_H 1\n#define HAVE_SYS_TYPES_H 1\n#define HAVE_STDIO_H 1\n#define STDC_HEADERS 1\n#define HAVE_STDLIB_H 1\n#define HAVE_STDARG_H 1\n#define HAVE_MALLOC_H 1\n#define HAVE_STRING_H 1\n#define HAVE_INTTYPES_H 1\n#define HAVE_STDINT_H 1\n#define HAVE_CTYPE_H 1\n#define HAVE_MATH_H 1\n#define HAVE_ICONV_H 1\n#define HAVE_SIGNAL_H 1\n\n/* C library functions */\n#define HAVE_MALLOC 1\n#define HAVE_CALLOC 1\n#define HAVE_REALLOC 1\n#define HAVE_FREE 1\n#define HAVE_ALLOCA 1\n#define HAVE_GETENV 1\n#define HAVE_PUTENV 1\n#define HAVE_UNSETENV 1\n#define HAVE_QSORT 1\n#define HAVE_ABS 1\n#define HAVE_BCOPY 1\n#define HAVE_MEMSET 1\n#define HAVE_MEMCPY 1\n#define HAVE_MEMMOVE 1\n#define HAVE_STRLEN 1\n#define HAVE_STRLCPY 1\n#define HAVE_STRLCAT 1\n#define HAVE_STRDUP 1\n#define HAVE_STRCHR 1\n#define HAVE_STRRCHR 1\n#define HAVE_STRSTR 1\n#define HAVE_STRTOL 1\n#define HAVE_STRTOUL 1\n#define HAVE_STRTOLL 1\n#define HAVE_STRTOULL 1\n#define HAVE_ATOI 1\n#define HAVE_ATOF 1\n#define HAVE_STRCMP 1\n#define HAVE_STRNCMP 1\n#define HAVE_STRCASECMP 1\n#define HAVE_STRNCASECMP 1\n#define HAVE_SSCANF 1\n#define HAVE_SNPRINTF 1\n#define HAVE_VSNPRINTF 1\n#define HAVE_SETJMP 1\n\n/* Enable various audio drivers */\n#define SDL_AUDIO_DRIVER_NDS\t1\n#define SDL_AUDIO_DRIVER_DUMMY\t1\n\n/* Enable the stub cdrom driver (src/cdrom/dummy/\\*.c) */\n#define SDL_CDROM_DISABLED\t1\n\n/* Enable various input drivers */\n#define SDL_JOYSTICK_NDS\t1\n\n/* Enable the stub shared object loader (src/loadso/dummy/\\*.c) */\n#define SDL_LOADSO_DISABLED\t1\n\n/* Enable the stub thread support (src/thread/generic/\\*.c) */\n#define SDL_THREADS_DISABLED\t1\n\n/* Enable various timer systems */\n#define SDL_TIMER_NDS\t1\n\n/* Enable various video drivers */\n#define SDL_VIDEO_DRIVER_NDS\t1\n#define SDL_VIDEO_DRIVER_DUMMY\t1\n\n#endif /* _SDL_config_nds_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_config_os2.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n#ifndef _SDL_config_os2_h\n#define _SDL_config_os2_h\n\n#include \"SDL_platform.h\"\n\n/* This is a set of defines to configure the SDL features */\n\ntypedef signed char         int8_t;\ntypedef unsigned char       uint8_t;\ntypedef signed short        int16_t;\ntypedef unsigned short      uint16_t;\ntypedef signed int          int32_t;\ntypedef unsigned int        uint32_t;\ntypedef unsigned int        size_t;\ntypedef unsigned long       uintptr_t;\ntypedef signed long long    int64_t;\ntypedef unsigned long long  uint64_t;\n\n#define SDL_HAS_64BIT_TYPE\t1\n\n/* Use Watcom's LIBC */\n#define HAVE_LIBC 1\n\n/* Useful headers */\n#define HAVE_SYS_TYPES_H 1\n#define HAVE_STDIO_H 1\n#define STDC_HEADERS 1\n#define HAVE_STDLIB_H 1\n#define HAVE_STDARG_H 1\n#define HAVE_MALLOC_H 1\n#define HAVE_MEMORY_H 1\n#define HAVE_STRING_H 1\n#define HAVE_STRINGS_H 1\n#define HAVE_INTTYPES_H 1\n#define HAVE_STDINT_H 1\n#define HAVE_CTYPE_H 1\n#define HAVE_MATH_H 1\n#define HAVE_SIGNAL_H 1\n\n/* C library functions */\n#define HAVE_MALLOC 1\n#define HAVE_CALLOC 1\n#define HAVE_REALLOC 1\n#define HAVE_FREE 1\n#define HAVE_ALLOCA 1\n#define HAVE_GETENV 1\n#define HAVE_PUTENV 1\n#define HAVE_UNSETENV 1\n#define HAVE_QSORT 1\n#define HAVE_ABS 1\n#define HAVE_BCOPY 1\n#define HAVE_MEMSET 1\n#define HAVE_MEMCPY 1\n#define HAVE_MEMMOVE 1\n#define HAVE_MEMCMP 1\n#define HAVE_STRLEN 1\n#define HAVE_STRLCPY 1\n#define HAVE_STRLCAT 1\n#define HAVE_STRDUP 1\n#define HAVE__STRREV 1\n#define HAVE__STRUPR 1\n#define HAVE__STRLWR 1\n#define HAVE_INDEX 1\n#define HAVE_RINDEX 1\n#define HAVE_STRCHR 1\n#define HAVE_STRRCHR 1\n#define HAVE_STRSTR 1\n#define HAVE_ITOA 1\n#define HAVE__LTOA 1\n#define HAVE__UITOA 1\n#define HAVE__ULTOA 1\n#define HAVE_STRTOL 1\n#define HAVE__I64TOA 1\n#define HAVE__UI64TOA 1\n#define HAVE_STRTOLL 1\n#define HAVE_STRTOD 1\n#define HAVE_ATOI 1\n#define HAVE_ATOF 1\n#define HAVE_STRCMP 1\n#define HAVE_STRNCMP 1\n#define HAVE_STRICMP 1\n#define HAVE_STRCASECMP 1\n#define HAVE_SSCANF 1\n#define HAVE_SNPRINTF 1\n#define HAVE_VSNPRINTF 1\n#define HAVE_SETJMP 1\n#define HAVE_CLOCK_GETTIME 1\n\n/* Enable various audio drivers */\n#define SDL_AUDIO_DRIVER_DART\t1\n#define SDL_AUDIO_DRIVER_DISK\t1\n#define SDL_AUDIO_DRIVER_DUMMY\t1\n\n/* Enable various cdrom drivers */\n#define SDL_CDROM_OS2\t1\n\n/* Enable various input drivers */\n#define SDL_JOYSTICK_OS2\t1\n\n/* Enable various shared object loading systems */\n#define SDL_LOADSO_OS2\t1\n\n/* Enable various threading systems */\n#define SDL_THREAD_OS2\t1\n\n/* Enable various timer systems */\n#define SDL_TIMER_OS2\t1\n\n/* Enable various video drivers */\n#define SDL_VIDEO_DRIVER_DUMMY\t1\n#define SDL_VIDEO_DRIVER_OS2FS\t1\n\n/* Enable OpenGL support */\n/* Nothing here yet for OS/2... :( */\n\n/* Enable assembly routines where available */\n#define SDL_ASSEMBLY_ROUTINES\t1\n\n#endif /* _SDL_config_os2_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_config_symbian.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/*\n\nSymbian version Markus Mertama\n\n*/\n\n\n#ifndef _SDL_CONFIG_SYMBIAN_H\n#define _SDL_CONFIG_SYMBIAN_H\n\n#include \"SDL_platform.h\"\n\n/* This is the minimal configuration that can be used to build SDL */\n\n\n#include <stdarg.h>\n#include <stddef.h>\n\n\n#ifdef __GCCE__\n#define SYMBIAN32_GCCE\n#endif\n\n#ifndef _SIZE_T_DEFINED\ntypedef unsigned int size_t;\n#endif\n\n#ifndef _INTPTR_T_DECLARED\ntypedef unsigned int uintptr_t;\n#endif \n\n#ifndef _INT8_T_DECLARED\ntypedef signed char int8_t;\n#endif \n\n#ifndef _UINT8_T_DECLARED\ntypedef unsigned char uint8_t;\n#endif\n\n#ifndef _INT16_T_DECLARED\ntypedef signed short int16_t;\n#endif\n\n#ifndef _UINT16_T_DECLARED\ntypedef unsigned short uint16_t;\n#endif\n\n#ifndef _INT32_T_DECLARED\ntypedef signed int int32_t;\n#endif\n\n#ifndef _UINT32_T_DECLARED\ntypedef unsigned int uint32_t;\n#endif\n\n#ifndef _INT64_T_DECLARED\ntypedef signed long long int64_t;\n#endif\n\n#ifndef _UINT64_T_DECLARED\ntypedef unsigned long long uint64_t;\n#endif\n\n#define SDL_AUDIO_DRIVER_EPOCAUDIO\t1\n\n\n/* Enable the stub cdrom driver (src/cdrom/dummy/\\*.c) */\n#define SDL_CDROM_DISABLED\t1\n\n/* Enable the stub joystick driver (src/joystick/dummy/\\*.c) */\n#define SDL_JOYSTICK_DISABLED\t1\n\n/* Enable the stub shared object loader (src/loadso/dummy/\\*.c) */\n#define SDL_LOADSO_DISABLED\t1\n\n#define SDL_THREAD_SYMBIAN 1\n\n#define SDL_VIDEO_DRIVER_EPOC    1\n\n#define SDL_VIDEO_OPENGL 0\n\n#define SDL_HAS_64BIT_TYPE\t1\n\n#define HAVE_LIBC\t1\n#define HAVE_STDIO_H 1\n#define STDC_HEADERS 1\n#define HAVE_STRING_H 1\n#define HAVE_CTYPE_H 1\n#define HAVE_MATH_H 1\n\n#define HAVE_MALLOC 1\n#define HAVE_CALLOC 1\n#define HAVE_REALLOC 1\n#define HAVE_FREE 1\n/*#define HAVE_ALLOCA 1*/\n#define HAVE_QSORT 1\n#define HAVE_ABS 1\n#define HAVE_MEMSET 1\n#define HAVE_MEMCPY 1\n#define HAVE_MEMMOVE 1\n#define HAVE_MEMCMP 1\n#define HAVE_STRLEN 1\n#define HAVE__STRUPR 1\n#define HAVE_STRCHR 1\n#define HAVE_STRRCHR 1\n#define HAVE_STRSTR 1\n#define HAVE_ITOA 1\n#define HAVE_STRTOL 1\n#define HAVE_STRTOUL 1\n#define HAVE_STRTOLL 1\n#define HAVE_STRTOD 1\n#define HAVE_ATOI 1\n#define HAVE_ATOF 1\n#define HAVE_STRCMP 1\n#define HAVE_STRNCMP 1\n/*#define HAVE__STRICMP 1*/\n#define HAVE__STRNICMP 1\n#define HAVE_SSCANF 1\n#define HAVE_STDARG_H\t1\n#define HAVE_STDDEF_H\t1\n\n\n\n#endif /* _SDL_CONFIG_SYMBIAN_H */\n"
  },
  {
    "path": "other/sdl/include/SDL_config_win32.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n#ifndef _SDL_config_win32_h\n#define _SDL_config_win32_h\n\n#include \"SDL_platform.h\"\n\n/* This is a set of defines to configure the SDL features */\n\n#if defined(__GNUC__) || defined(__DMC__)\n#define HAVE_STDINT_H\t1\n#elif defined(_MSC_VER)\ntypedef signed __int8\t\tint8_t;\ntypedef unsigned __int8\t\tuint8_t;\ntypedef signed __int16\t\tint16_t;\ntypedef unsigned __int16\tuint16_t;\ntypedef signed __int32\t\tint32_t;\ntypedef unsigned __int32\tuint32_t;\ntypedef signed __int64\t\tint64_t;\ntypedef unsigned __int64\tuint64_t;\n#ifndef _UINTPTR_T_DEFINED\n#ifdef  _WIN64\ntypedef unsigned __int64    uintptr_t;\n#else\ntypedef unsigned int   uintptr_t;\n#endif\n#define _UINTPTR_T_DEFINED\n#endif\n/* Older Visual C++ headers don't have the Win64-compatible typedefs... */\n#if ((_MSC_VER <= 1200) && (!defined(DWORD_PTR)))\n#define DWORD_PTR DWORD\n#endif\n#if ((_MSC_VER <= 1200) && (!defined(LONG_PTR)))\n#define LONG_PTR LONG\n#endif\n#else\t/* !__GNUC__ && !_MSC_VER */\ntypedef signed char int8_t;\ntypedef unsigned char uint8_t;\ntypedef signed short int16_t;\ntypedef unsigned short uint16_t;\ntypedef signed int int32_t;\ntypedef unsigned int uint32_t;\ntypedef signed long long int64_t;\ntypedef unsigned long long uint64_t;\n#ifndef _SIZE_T_DEFINED_\n#define _SIZE_T_DEFINED_\ntypedef unsigned int size_t;\n#endif\ntypedef unsigned int uintptr_t;\n#endif /* __GNUC__ || _MSC_VER */\n#define SDL_HAS_64BIT_TYPE\t1\n\n/* Enabled for SDL 1.2 (binary compatibility) */\n#define HAVE_LIBC\t1\n#ifdef HAVE_LIBC\n/* Useful headers */\n#define HAVE_STDIO_H 1\n#define STDC_HEADERS 1\n#define HAVE_STRING_H 1\n#define HAVE_CTYPE_H 1\n#define HAVE_MATH_H 1\n#ifndef _WIN32_WCE\n#define HAVE_SIGNAL_H 1\n#endif\n\n/* C library functions */\n#define HAVE_MALLOC 1\n#define HAVE_CALLOC 1\n#define HAVE_REALLOC 1\n#define HAVE_FREE 1\n#define HAVE_ALLOCA 1\n#define HAVE_QSORT 1\n#define HAVE_ABS 1\n#define HAVE_MEMSET 1\n#define HAVE_MEMCPY 1\n#define HAVE_MEMMOVE 1\n#define HAVE_MEMCMP 1\n#define HAVE_STRLEN 1\n#define HAVE__STRREV 1\n#define HAVE__STRUPR 1\n#define HAVE__STRLWR 1\n#define HAVE_STRCHR 1\n#define HAVE_STRRCHR 1\n#define HAVE_STRSTR 1\n#define HAVE_ITOA 1\n#define HAVE__LTOA 1\n#define HAVE__ULTOA 1\n#define HAVE_STRTOL 1\n#define HAVE_STRTOUL 1\n#define HAVE_STRTOLL 1\n#define HAVE_STRTOD 1\n#define HAVE_ATOI 1\n#define HAVE_ATOF 1\n#define HAVE_STRCMP 1\n#define HAVE_STRNCMP 1\n#define HAVE__STRICMP 1\n#define HAVE__STRNICMP 1\n#define HAVE_SSCANF 1\n#else\n#define HAVE_STDARG_H\t1\n#define HAVE_STDDEF_H\t1\n#endif\n\n/* Enable various audio drivers */\n#ifndef _WIN32_WCE\n#define SDL_AUDIO_DRIVER_DSOUND\t1\n#endif\n#define SDL_AUDIO_DRIVER_WAVEOUT\t1\n#define SDL_AUDIO_DRIVER_DISK\t1\n#define SDL_AUDIO_DRIVER_DUMMY\t1\n\n/* Enable various cdrom drivers */\n#ifdef _WIN32_WCE\n#define SDL_CDROM_DISABLED      1\n#else\n#define SDL_CDROM_WIN32\t\t1\n#endif\n\n/* Enable various input drivers */\n#ifdef _WIN32_WCE\n#define SDL_JOYSTICK_DISABLED   1\n#else\n#define SDL_JOYSTICK_WINMM\t1\n#endif\n\n/* Enable various shared object loading systems */\n#define SDL_LOADSO_WIN32\t1\n\n/* Enable various threading systems */\n#define SDL_THREAD_WIN32\t1\n\n/* Enable various timer systems */\n#ifdef _WIN32_WCE\n#define SDL_TIMER_WINCE\t1\n#else\n#define SDL_TIMER_WIN32\t1\n#endif\n\n/* Enable various video drivers */\n#ifdef _WIN32_WCE\n#define SDL_VIDEO_DRIVER_GAPI\t1\n#endif\n#ifndef _WIN32_WCE\n#define SDL_VIDEO_DRIVER_DDRAW\t1\n#endif\n#define SDL_VIDEO_DRIVER_DUMMY\t1\n#define SDL_VIDEO_DRIVER_WINDIB\t1\n\n/* Enable OpenGL support */\n#ifndef _WIN32_WCE\n#define SDL_VIDEO_OPENGL\t1\n#define SDL_VIDEO_OPENGL_WGL\t1\n#endif\n\n/* Disable screensaver */\n#define SDL_VIDEO_DISABLE_SCREENSAVER\t1\n\n/* Enable assembly routines (Win64 doesn't have inline asm) */\n#ifndef _WIN64\n#define SDL_ASSEMBLY_ROUTINES\t1\n#endif\n\n#endif /* _SDL_config_win32_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_copying.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n"
  },
  {
    "path": "other/sdl/include/SDL_cpuinfo.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/**\n *  @file SDL_cpuinfo.h\n *  CPU feature detection for SDL\n */\n\n#ifndef _SDL_cpuinfo_h\n#define _SDL_cpuinfo_h\n\n#include \"SDL_stdinc.h\"\n\n#include \"begin_code.h\"\n/* Set up for C function definitions, even when using C++ */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/** This function returns true if the CPU has the RDTSC instruction */\nextern DECLSPEC SDL_bool SDLCALL SDL_HasRDTSC(void);\n\n/** This function returns true if the CPU has MMX features */\nextern DECLSPEC SDL_bool SDLCALL SDL_HasMMX(void);\n\n/** This function returns true if the CPU has MMX Ext. features */\nextern DECLSPEC SDL_bool SDLCALL SDL_HasMMXExt(void);\n\n/** This function returns true if the CPU has 3DNow features */\nextern DECLSPEC SDL_bool SDLCALL SDL_Has3DNow(void);\n\n/** This function returns true if the CPU has 3DNow! Ext. features */\nextern DECLSPEC SDL_bool SDLCALL SDL_Has3DNowExt(void);\n\n/** This function returns true if the CPU has SSE features */\nextern DECLSPEC SDL_bool SDLCALL SDL_HasSSE(void);\n\n/** This function returns true if the CPU has SSE2 features */\nextern DECLSPEC SDL_bool SDLCALL SDL_HasSSE2(void);\n\n/** This function returns true if the CPU has AltiVec features */\nextern DECLSPEC SDL_bool SDLCALL SDL_HasAltiVec(void);\n\n/* Ends C function definitions when using C++ */\n#ifdef __cplusplus\n}\n#endif\n#include \"close_code.h\"\n\n#endif /* _SDL_cpuinfo_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_endian.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/**\n *  @file SDL_endian.h\n *  Functions for reading and writing endian-specific values\n */\n\n#ifndef _SDL_endian_h\n#define _SDL_endian_h\n\n#include \"SDL_stdinc.h\"\n\n/** @name SDL_ENDIANs\n *  The two types of endianness \n */\n/*@{*/\n#define SDL_LIL_ENDIAN\t1234\n#define SDL_BIG_ENDIAN\t4321\n/*@}*/\n\n#ifndef SDL_BYTEORDER\t/* Not defined in SDL_config.h? */\n#if defined(__hppa__) || \\\n    defined(__m68k__) || defined(mc68000) || defined(_M_M68K) || \\\n    (defined(__MIPS__) && defined(__MISPEB__)) || \\\n    defined(__ppc__) || defined(__POWERPC__) || defined(_M_PPC) || \\\n    defined(__sparc__)\n#define SDL_BYTEORDER\tSDL_BIG_ENDIAN\n#else\n#define SDL_BYTEORDER\tSDL_LIL_ENDIAN\n#endif\n#endif /* !SDL_BYTEORDER */\n\n\n#include \"begin_code.h\"\n/* Set up for C function definitions, even when using C++ */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n *  @name SDL_Swap Functions\n *  Use inline functions for compilers that support them, and static\n *  functions for those that do not.  Because these functions become\n *  static for compilers that do not support inline functions, this\n *  header should only be included in files that actually use them.\n */\n/*@{*/\n#if defined(__GNUC__) && defined(__i386__) && \\\n   !(__GNUC__ == 2 && __GNUC_MINOR__ <= 95 /* broken gcc version */)\nstatic __inline__ Uint16 SDL_Swap16(Uint16 x)\n{\n\t__asm__(\"xchgb %b0,%h0\" : \"=q\" (x) :  \"0\" (x));\n\treturn x;\n}\n#elif defined(__GNUC__) && defined(__x86_64__)\nstatic __inline__ Uint16 SDL_Swap16(Uint16 x)\n{\n\t__asm__(\"xchgb %b0,%h0\" : \"=Q\" (x) :  \"0\" (x));\n\treturn x;\n}\n#elif defined(__GNUC__) && (defined(__powerpc__) || defined(__ppc__))\nstatic __inline__ Uint16 SDL_Swap16(Uint16 x)\n{\n\tUint16 result;\n\n\t__asm__(\"rlwimi %0,%2,8,16,23\" : \"=&r\" (result) : \"0\" (x >> 8), \"r\" (x));\n\treturn result;\n}\n#elif defined(__GNUC__) && (defined(__M68000__) || defined(__M68020__))\nstatic __inline__ Uint16 SDL_Swap16(Uint16 x)\n{\n\t__asm__(\"rorw #8,%0\" : \"=d\" (x) :  \"0\" (x) : \"cc\");\n\treturn x;\n}\n#else\nstatic __inline__ Uint16 SDL_Swap16(Uint16 x) {\n\treturn((x<<8)|(x>>8));\n}\n#endif\n\n#if defined(__GNUC__) && defined(__i386__) && \\\n   !(__GNUC__ == 2 && __GNUC_MINOR__ <= 95 /* broken gcc version */)\nstatic __inline__ Uint32 SDL_Swap32(Uint32 x)\n{\n\t__asm__(\"bswap %0\" : \"=r\" (x) : \"0\" (x));\n\treturn x;\n}\n#elif defined(__GNUC__) && defined(__x86_64__)\nstatic __inline__ Uint32 SDL_Swap32(Uint32 x)\n{\n\t__asm__(\"bswapl %0\" : \"=r\" (x) : \"0\" (x));\n\treturn x;\n}\n#elif defined(__GNUC__) && (defined(__powerpc__) || defined(__ppc__))\nstatic __inline__ Uint32 SDL_Swap32(Uint32 x)\n{\n\tUint32 result;\n\n\t__asm__(\"rlwimi %0,%2,24,16,23\" : \"=&r\" (result) : \"0\" (x>>24), \"r\" (x));\n\t__asm__(\"rlwimi %0,%2,8,8,15\"   : \"=&r\" (result) : \"0\" (result),    \"r\" (x));\n\t__asm__(\"rlwimi %0,%2,24,0,7\"   : \"=&r\" (result) : \"0\" (result),    \"r\" (x));\n\treturn result;\n}\n#elif defined(__GNUC__) && (defined(__M68000__) || defined(__M68020__))\nstatic __inline__ Uint32 SDL_Swap32(Uint32 x)\n{\n\t__asm__(\"rorw #8,%0\\n\\tswap %0\\n\\trorw #8,%0\" : \"=d\" (x) :  \"0\" (x) : \"cc\");\n\treturn x;\n}\n#else\nstatic __inline__ Uint32 SDL_Swap32(Uint32 x) {\n\treturn((x<<24)|((x<<8)&0x00FF0000)|((x>>8)&0x0000FF00)|(x>>24));\n}\n#endif\n\n#ifdef SDL_HAS_64BIT_TYPE\n#if defined(__GNUC__) && defined(__i386__) && \\\n   !(__GNUC__ == 2 && __GNUC_MINOR__ <= 95 /* broken gcc version */)\nstatic __inline__ Uint64 SDL_Swap64(Uint64 x)\n{\n\tunion { \n\t\tstruct { Uint32 a,b; } s;\n\t\tUint64 u;\n\t} v;\n\tv.u = x;\n\t__asm__(\"bswapl %0 ; bswapl %1 ; xchgl %0,%1\" \n\t        : \"=r\" (v.s.a), \"=r\" (v.s.b) \n\t        : \"0\" (v.s.a), \"1\" (v.s.b)); \n\treturn v.u;\n}\n#elif defined(__GNUC__) && defined(__x86_64__)\nstatic __inline__ Uint64 SDL_Swap64(Uint64 x)\n{\n\t__asm__(\"bswapq %0\" : \"=r\" (x) : \"0\" (x));\n\treturn x;\n}\n#else\nstatic __inline__ Uint64 SDL_Swap64(Uint64 x)\n{\n\tUint32 hi, lo;\n\n\t/* Separate into high and low 32-bit values and swap them */\n\tlo = SDL_static_cast(Uint32, x & 0xFFFFFFFF);\n\tx >>= 32;\n\thi = SDL_static_cast(Uint32, x & 0xFFFFFFFF);\n\tx = SDL_Swap32(lo);\n\tx <<= 32;\n\tx |= SDL_Swap32(hi);\n\treturn(x);\n}\n#endif\n#else\n/* This is mainly to keep compilers from complaining in SDL code.\n * If there is no real 64-bit datatype, then compilers will complain about\n * the fake 64-bit datatype that SDL provides when it compiles user code.\n */\n#define SDL_Swap64(X)\t(X)\n#endif /* SDL_HAS_64BIT_TYPE */\n/*@}*/\n\n/**\n *  @name SDL_SwapLE and SDL_SwapBE Functions\n *  Byteswap item from the specified endianness to the native endianness\n */\n/*@{*/\n#if SDL_BYTEORDER == SDL_LIL_ENDIAN\n#define SDL_SwapLE16(X)\t(X)\n#define SDL_SwapLE32(X)\t(X)\n#define SDL_SwapLE64(X)\t(X)\n#define SDL_SwapBE16(X)\tSDL_Swap16(X)\n#define SDL_SwapBE32(X)\tSDL_Swap32(X)\n#define SDL_SwapBE64(X)\tSDL_Swap64(X)\n#else\n#define SDL_SwapLE16(X)\tSDL_Swap16(X)\n#define SDL_SwapLE32(X)\tSDL_Swap32(X)\n#define SDL_SwapLE64(X)\tSDL_Swap64(X)\n#define SDL_SwapBE16(X)\t(X)\n#define SDL_SwapBE32(X)\t(X)\n#define SDL_SwapBE64(X)\t(X)\n#endif\n/*@}*/\n\n/* Ends C function definitions when using C++ */\n#ifdef __cplusplus\n}\n#endif\n#include \"close_code.h\"\n\n#endif /* _SDL_endian_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_error.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/**\n *  @file SDL_error.h\n *  Simple error message routines for SDL\n */\n\n#ifndef _SDL_error_h\n#define _SDL_error_h\n\n#include \"SDL_stdinc.h\"\n\n#include \"begin_code.h\"\n/* Set up for C function definitions, even when using C++ */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/** \n *  @name Public functions\n */\n/*@{*/\nextern DECLSPEC void SDLCALL SDL_SetError(const char *fmt, ...);\nextern DECLSPEC char * SDLCALL SDL_GetError(void);\nextern DECLSPEC void SDLCALL SDL_ClearError(void);\n/*@}*/\n\n/**\n *  @name Private functions\n *  @internal Private error message function - used internally\n */\n/*@{*/\n#define SDL_OutOfMemory()\tSDL_Error(SDL_ENOMEM)\n#define SDL_Unsupported()\tSDL_Error(SDL_UNSUPPORTED)\ntypedef enum {\n\tSDL_ENOMEM,\n\tSDL_EFREAD,\n\tSDL_EFWRITE,\n\tSDL_EFSEEK,\n\tSDL_UNSUPPORTED,\n\tSDL_LASTERROR\n} SDL_errorcode;\nextern DECLSPEC void SDLCALL SDL_Error(SDL_errorcode code);\n/*@}*/\n\n/* Ends C function definitions when using C++ */\n#ifdef __cplusplus\n}\n#endif\n#include \"close_code.h\"\n\n#endif /* _SDL_error_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_events.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/**\n *  @file SDL_events.h\n *  Include file for SDL event handling\n */\n\n#ifndef _SDL_events_h\n#define _SDL_events_h\n\n#include \"SDL_stdinc.h\"\n#include \"SDL_error.h\"\n#include \"SDL_active.h\"\n#include \"SDL_keyboard.h\"\n#include \"SDL_mouse.h\"\n#include \"SDL_joystick.h\"\n#include \"SDL_quit.h\"\n\n#include \"begin_code.h\"\n/* Set up for C function definitions, even when using C++ */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/** @name General keyboard/mouse state definitions */\n/*@{*/\n#define SDL_RELEASED\t0\n#define SDL_PRESSED\t1\n/*@}*/\n\n/** Event enumerations */\ntypedef enum {\n       SDL_NOEVENT = 0,\t\t\t/**< Unused (do not remove) */\n       SDL_ACTIVEEVENT,\t\t\t/**< Application loses/gains visibility */\n       SDL_KEYDOWN,\t\t\t/**< Keys pressed */\n       SDL_KEYUP,\t\t\t/**< Keys released */\n       SDL_MOUSEMOTION,\t\t\t/**< Mouse moved */\n       SDL_MOUSEBUTTONDOWN,\t\t/**< Mouse button pressed */\n       SDL_MOUSEBUTTONUP,\t\t/**< Mouse button released */\n       SDL_JOYAXISMOTION,\t\t/**< Joystick axis motion */\n       SDL_JOYBALLMOTION,\t\t/**< Joystick trackball motion */\n       SDL_JOYHATMOTION,\t\t/**< Joystick hat position change */\n       SDL_JOYBUTTONDOWN,\t\t/**< Joystick button pressed */\n       SDL_JOYBUTTONUP,\t\t\t/**< Joystick button released */\n       SDL_QUIT,\t\t\t/**< User-requested quit */\n       SDL_SYSWMEVENT,\t\t\t/**< System specific event */\n       SDL_EVENT_RESERVEDA,\t\t/**< Reserved for future use.. */\n       SDL_EVENT_RESERVEDB,\t\t/**< Reserved for future use.. */\n       SDL_VIDEORESIZE,\t\t\t/**< User resized video mode */\n       SDL_VIDEOEXPOSE,\t\t\t/**< Screen needs to be redrawn */\n       SDL_EVENT_RESERVED2,\t\t/**< Reserved for future use.. */\n       SDL_EVENT_RESERVED3,\t\t/**< Reserved for future use.. */\n       SDL_EVENT_RESERVED4,\t\t/**< Reserved for future use.. */\n       SDL_EVENT_RESERVED5,\t\t/**< Reserved for future use.. */\n       SDL_EVENT_RESERVED6,\t\t/**< Reserved for future use.. */\n       SDL_EVENT_RESERVED7,\t\t/**< Reserved for future use.. */\n       /** Events SDL_USEREVENT through SDL_MAXEVENTS-1 are for your use */\n       SDL_USEREVENT = 24,\n       /** This last event is only for bounding internal arrays\n\t*  It is the number of bits in the event mask datatype -- Uint32\n        */\n       SDL_NUMEVENTS = 32\n} SDL_EventType;\n\n/** @name Predefined event masks */\n/*@{*/\n#define SDL_EVENTMASK(X)\t(1<<(X))\ntypedef enum {\n\tSDL_ACTIVEEVENTMASK\t= SDL_EVENTMASK(SDL_ACTIVEEVENT),\n\tSDL_KEYDOWNMASK\t\t= SDL_EVENTMASK(SDL_KEYDOWN),\n\tSDL_KEYUPMASK\t\t= SDL_EVENTMASK(SDL_KEYUP),\n\tSDL_KEYEVENTMASK\t= SDL_EVENTMASK(SDL_KEYDOWN)|\n\t                          SDL_EVENTMASK(SDL_KEYUP),\n\tSDL_MOUSEMOTIONMASK\t= SDL_EVENTMASK(SDL_MOUSEMOTION),\n\tSDL_MOUSEBUTTONDOWNMASK\t= SDL_EVENTMASK(SDL_MOUSEBUTTONDOWN),\n\tSDL_MOUSEBUTTONUPMASK\t= SDL_EVENTMASK(SDL_MOUSEBUTTONUP),\n\tSDL_MOUSEEVENTMASK\t= SDL_EVENTMASK(SDL_MOUSEMOTION)|\n\t                          SDL_EVENTMASK(SDL_MOUSEBUTTONDOWN)|\n\t                          SDL_EVENTMASK(SDL_MOUSEBUTTONUP),\n\tSDL_JOYAXISMOTIONMASK\t= SDL_EVENTMASK(SDL_JOYAXISMOTION),\n\tSDL_JOYBALLMOTIONMASK\t= SDL_EVENTMASK(SDL_JOYBALLMOTION),\n\tSDL_JOYHATMOTIONMASK\t= SDL_EVENTMASK(SDL_JOYHATMOTION),\n\tSDL_JOYBUTTONDOWNMASK\t= SDL_EVENTMASK(SDL_JOYBUTTONDOWN),\n\tSDL_JOYBUTTONUPMASK\t= SDL_EVENTMASK(SDL_JOYBUTTONUP),\n\tSDL_JOYEVENTMASK\t= SDL_EVENTMASK(SDL_JOYAXISMOTION)|\n\t                          SDL_EVENTMASK(SDL_JOYBALLMOTION)|\n\t                          SDL_EVENTMASK(SDL_JOYHATMOTION)|\n\t                          SDL_EVENTMASK(SDL_JOYBUTTONDOWN)|\n\t                          SDL_EVENTMASK(SDL_JOYBUTTONUP),\n\tSDL_VIDEORESIZEMASK\t= SDL_EVENTMASK(SDL_VIDEORESIZE),\n\tSDL_VIDEOEXPOSEMASK\t= SDL_EVENTMASK(SDL_VIDEOEXPOSE),\n\tSDL_QUITMASK\t\t= SDL_EVENTMASK(SDL_QUIT),\n\tSDL_SYSWMEVENTMASK\t= SDL_EVENTMASK(SDL_SYSWMEVENT)\n} SDL_EventMask ;\n#define SDL_ALLEVENTS\t\t0xFFFFFFFF\n/*@}*/\n\n/** Application visibility event structure */\ntypedef struct SDL_ActiveEvent {\n\tUint8 type;\t/**< SDL_ACTIVEEVENT */\n\tUint8 gain;\t/**< Whether given states were gained or lost (1/0) */\n\tUint8 state;\t/**< A mask of the focus states */\n} SDL_ActiveEvent;\n\n/** Keyboard event structure */\ntypedef struct SDL_KeyboardEvent {\n\tUint8 type;\t/**< SDL_KEYDOWN or SDL_KEYUP */\n\tUint8 which;\t/**< The keyboard device index */\n\tUint8 state;\t/**< SDL_PRESSED or SDL_RELEASED */\n\tSDL_keysym keysym;\n} SDL_KeyboardEvent;\n\n/** Mouse motion event structure */\ntypedef struct SDL_MouseMotionEvent {\n\tUint8 type;\t/**< SDL_MOUSEMOTION */\n\tUint8 which;\t/**< The mouse device index */\n\tUint8 state;\t/**< The current button state */\n\tUint16 x, y;\t/**< The X/Y coordinates of the mouse */\n\tSint16 xrel;\t/**< The relative motion in the X direction */\n\tSint16 yrel;\t/**< The relative motion in the Y direction */\n} SDL_MouseMotionEvent;\n\n/** Mouse button event structure */\ntypedef struct SDL_MouseButtonEvent {\n\tUint8 type;\t/**< SDL_MOUSEBUTTONDOWN or SDL_MOUSEBUTTONUP */\n\tUint8 which;\t/**< The mouse device index */\n\tUint8 button;\t/**< The mouse button index */\n\tUint8 state;\t/**< SDL_PRESSED or SDL_RELEASED */\n\tUint16 x, y;\t/**< The X/Y coordinates of the mouse at press time */\n} SDL_MouseButtonEvent;\n\n/** Joystick axis motion event structure */\ntypedef struct SDL_JoyAxisEvent {\n\tUint8 type;\t/**< SDL_JOYAXISMOTION */\n\tUint8 which;\t/**< The joystick device index */\n\tUint8 axis;\t/**< The joystick axis index */\n\tSint16 value;\t/**< The axis value (range: -32768 to 32767) */\n} SDL_JoyAxisEvent;\n\n/** Joystick trackball motion event structure */\ntypedef struct SDL_JoyBallEvent {\n\tUint8 type;\t/**< SDL_JOYBALLMOTION */\n\tUint8 which;\t/**< The joystick device index */\n\tUint8 ball;\t/**< The joystick trackball index */\n\tSint16 xrel;\t/**< The relative motion in the X direction */\n\tSint16 yrel;\t/**< The relative motion in the Y direction */\n} SDL_JoyBallEvent;\n\n/** Joystick hat position change event structure */\ntypedef struct SDL_JoyHatEvent {\n\tUint8 type;\t/**< SDL_JOYHATMOTION */\n\tUint8 which;\t/**< The joystick device index */\n\tUint8 hat;\t/**< The joystick hat index */\n\tUint8 value;\t/**< The hat position value:\n\t\t\t *   SDL_HAT_LEFTUP   SDL_HAT_UP       SDL_HAT_RIGHTUP\n\t\t\t *   SDL_HAT_LEFT     SDL_HAT_CENTERED SDL_HAT_RIGHT\n\t\t\t *   SDL_HAT_LEFTDOWN SDL_HAT_DOWN     SDL_HAT_RIGHTDOWN\n\t\t\t *  Note that zero means the POV is centered.\n\t\t\t */\n} SDL_JoyHatEvent;\n\n/** Joystick button event structure */\ntypedef struct SDL_JoyButtonEvent {\n\tUint8 type;\t/**< SDL_JOYBUTTONDOWN or SDL_JOYBUTTONUP */\n\tUint8 which;\t/**< The joystick device index */\n\tUint8 button;\t/**< The joystick button index */\n\tUint8 state;\t/**< SDL_PRESSED or SDL_RELEASED */\n} SDL_JoyButtonEvent;\n\n/** The \"window resized\" event\n *  When you get this event, you are responsible for setting a new video\n *  mode with the new width and height.\n */\ntypedef struct SDL_ResizeEvent {\n\tUint8 type;\t/**< SDL_VIDEORESIZE */\n\tint w;\t\t/**< New width */\n\tint h;\t\t/**< New height */\n} SDL_ResizeEvent;\n\n/** The \"screen redraw\" event */\ntypedef struct SDL_ExposeEvent {\n\tUint8 type;\t/**< SDL_VIDEOEXPOSE */\n} SDL_ExposeEvent;\n\n/** The \"quit requested\" event */\ntypedef struct SDL_QuitEvent {\n\tUint8 type;\t/**< SDL_QUIT */\n} SDL_QuitEvent;\n\n/** A user-defined event type */\ntypedef struct SDL_UserEvent {\n\tUint8 type;\t/**< SDL_USEREVENT through SDL_NUMEVENTS-1 */\n\tint code;\t/**< User defined event code */\n\tvoid *data1;\t/**< User defined data pointer */\n\tvoid *data2;\t/**< User defined data pointer */\n} SDL_UserEvent;\n\n/** If you want to use this event, you should include SDL_syswm.h */\nstruct SDL_SysWMmsg;\ntypedef struct SDL_SysWMmsg SDL_SysWMmsg;\ntypedef struct SDL_SysWMEvent {\n\tUint8 type;\n\tSDL_SysWMmsg *msg;\n} SDL_SysWMEvent;\n\n/** General event structure */\ntypedef union SDL_Event {\n\tUint8 type;\n\tSDL_ActiveEvent active;\n\tSDL_KeyboardEvent key;\n\tSDL_MouseMotionEvent motion;\n\tSDL_MouseButtonEvent button;\n\tSDL_JoyAxisEvent jaxis;\n\tSDL_JoyBallEvent jball;\n\tSDL_JoyHatEvent jhat;\n\tSDL_JoyButtonEvent jbutton;\n\tSDL_ResizeEvent resize;\n\tSDL_ExposeEvent expose;\n\tSDL_QuitEvent quit;\n\tSDL_UserEvent user;\n\tSDL_SysWMEvent syswm;\n} SDL_Event;\n\n\n/* Function prototypes */\n\n/** Pumps the event loop, gathering events from the input devices.\n *  This function updates the event queue and internal input device state.\n *  This should only be run in the thread that sets the video mode.\n */\nextern DECLSPEC void SDLCALL SDL_PumpEvents(void);\n\ntypedef enum {\n\tSDL_ADDEVENT,\n\tSDL_PEEKEVENT,\n\tSDL_GETEVENT\n} SDL_eventaction;\n\n/**\n *  Checks the event queue for messages and optionally returns them.\n *\n *  If 'action' is SDL_ADDEVENT, up to 'numevents' events will be added to\n *  the back of the event queue.\n *  If 'action' is SDL_PEEKEVENT, up to 'numevents' events at the front\n *  of the event queue, matching 'mask', will be returned and will not\n *  be removed from the queue.\n *  If 'action' is SDL_GETEVENT, up to 'numevents' events at the front \n *  of the event queue, matching 'mask', will be returned and will be\n *  removed from the queue.\n *\n *  @return\n *  This function returns the number of events actually stored, or -1\n *  if there was an error.\n *\n *  This function is thread-safe.\n */\nextern DECLSPEC int SDLCALL SDL_PeepEvents(SDL_Event *events, int numevents,\n\t\t\t\tSDL_eventaction action, Uint32 mask);\n\n/** Polls for currently pending events, and returns 1 if there are any pending\n *  events, or 0 if there are none available.  If 'event' is not NULL, the next\n *  event is removed from the queue and stored in that area.\n */\nextern DECLSPEC int SDLCALL SDL_PollEvent(SDL_Event *event);\n\n/** Waits indefinitely for the next available event, returning 1, or 0 if there\n *  was an error while waiting for events.  If 'event' is not NULL, the next\n *  event is removed from the queue and stored in that area.\n */\nextern DECLSPEC int SDLCALL SDL_WaitEvent(SDL_Event *event);\n\n/** Add an event to the event queue.\n *  This function returns 0 on success, or -1 if the event queue was full\n *  or there was some other error.\n */\nextern DECLSPEC int SDLCALL SDL_PushEvent(SDL_Event *event);\n\n/** @name Event Filtering */\n/*@{*/\ntypedef int (SDLCALL *SDL_EventFilter)(const SDL_Event *event);\n/**\n *  This function sets up a filter to process all events before they\n *  change internal state and are posted to the internal event queue.\n *\n *  The filter is protypted as:\n *      @code typedef int (SDLCALL *SDL_EventFilter)(const SDL_Event *event); @endcode\n *\n * If the filter returns 1, then the event will be added to the internal queue.\n * If it returns 0, then the event will be dropped from the queue, but the \n * internal state will still be updated.  This allows selective filtering of\n * dynamically arriving events.\n *\n * @warning  Be very careful of what you do in the event filter function, as \n *           it may run in a different thread!\n *\n * There is one caveat when dealing with the SDL_QUITEVENT event type.  The\n * event filter is only called when the window manager desires to close the\n * application window.  If the event filter returns 1, then the window will\n * be closed, otherwise the window will remain open if possible.\n * If the quit event is generated by an interrupt signal, it will bypass the\n * internal queue and be delivered to the application at the next event poll.\n */\nextern DECLSPEC void SDLCALL SDL_SetEventFilter(SDL_EventFilter filter);\n\n/**\n *  Return the current event filter - can be used to \"chain\" filters.\n *  If there is no event filter set, this function returns NULL.\n */\nextern DECLSPEC SDL_EventFilter SDLCALL SDL_GetEventFilter(void);\n/*@}*/\n\n/** @name Event State */\n/*@{*/\n#define SDL_QUERY\t-1\n#define SDL_IGNORE\t 0\n#define SDL_DISABLE\t 0\n#define SDL_ENABLE\t 1\n/*@}*/\n\n/**\n* This function allows you to set the state of processing certain events.\n* If 'state' is set to SDL_IGNORE, that event will be automatically dropped\n* from the event queue and will not event be filtered.\n* If 'state' is set to SDL_ENABLE, that event will be processed normally.\n* If 'state' is set to SDL_QUERY, SDL_EventState() will return the \n* current processing state of the specified event.\n*/\nextern DECLSPEC Uint8 SDLCALL SDL_EventState(Uint8 type, int state);\n\n/* Ends C function definitions when using C++ */\n#ifdef __cplusplus\n}\n#endif\n#include \"close_code.h\"\n\n#endif /* _SDL_events_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_getenv.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/** @file SDL_getenv.h\n *  @deprecated Use SDL_stdinc.h instead\n */\n\n/* DEPRECATED */\n#include \"SDL_stdinc.h\"\n"
  },
  {
    "path": "other/sdl/include/SDL_joystick.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/** @file SDL_joystick.h\n *  Include file for SDL joystick event handling\n */\n\n#ifndef _SDL_joystick_h\n#define _SDL_joystick_h\n\n#include \"SDL_stdinc.h\"\n#include \"SDL_error.h\"\n\n#include \"begin_code.h\"\n/* Set up for C function definitions, even when using C++ */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/** @file SDL_joystick.h\n *  @note In order to use these functions, SDL_Init() must have been called\n *        with the SDL_INIT_JOYSTICK flag.  This causes SDL to scan the system\n *        for joysticks, and load appropriate drivers.\n */\n\n/** The joystick structure used to identify an SDL joystick */\nstruct _SDL_Joystick;\ntypedef struct _SDL_Joystick SDL_Joystick;\n\n/* Function prototypes */\n/**\n * Count the number of joysticks attached to the system\n */\nextern DECLSPEC int SDLCALL SDL_NumJoysticks(void);\n\n/**\n * Get the implementation dependent name of a joystick.\n *\n * This can be called before any joysticks are opened.\n * If no name can be found, this function returns NULL.\n */\nextern DECLSPEC const char * SDLCALL SDL_JoystickName(int device_index);\n\n/**\n * Open a joystick for use.\n *\n * @param[in] device_index\n * The index passed as an argument refers to\n * the N'th joystick on the system.  This index is the value which will\n * identify this joystick in future joystick events.\n *\n * @return This function returns a joystick identifier, or NULL if an error occurred.\n */\nextern DECLSPEC SDL_Joystick * SDLCALL SDL_JoystickOpen(int device_index);\n\n/**\n * Returns 1 if the joystick has been opened, or 0 if it has not.\n */\nextern DECLSPEC int SDLCALL SDL_JoystickOpened(int device_index);\n\n/**\n * Get the device index of an opened joystick.\n */\nextern DECLSPEC int SDLCALL SDL_JoystickIndex(SDL_Joystick *joystick);\n\n/**\n * Get the number of general axis controls on a joystick\n */\nextern DECLSPEC int SDLCALL SDL_JoystickNumAxes(SDL_Joystick *joystick);\n\n/**\n * Get the number of trackballs on a joystick\n *\n * Joystick trackballs have only relative motion events associated\n * with them and their state cannot be polled.\n */\nextern DECLSPEC int SDLCALL SDL_JoystickNumBalls(SDL_Joystick *joystick);\n\n/**\n * Get the number of POV hats on a joystick\n */\nextern DECLSPEC int SDLCALL SDL_JoystickNumHats(SDL_Joystick *joystick);\n\n/**\n * Get the number of buttons on a joystick\n */\nextern DECLSPEC int SDLCALL SDL_JoystickNumButtons(SDL_Joystick *joystick);\n\n/**\n * Update the current state of the open joysticks.\n *\n * This is called automatically by the event loop if any joystick\n * events are enabled.\n */\nextern DECLSPEC void SDLCALL SDL_JoystickUpdate(void);\n\n/**\n * Enable/disable joystick event polling.\n *\n * If joystick events are disabled, you must call SDL_JoystickUpdate()\n * yourself and check the state of the joystick when you want joystick\n * information.\n *\n * @param[in] state The state can be one of SDL_QUERY, SDL_ENABLE or SDL_IGNORE.\n */\nextern DECLSPEC int SDLCALL SDL_JoystickEventState(int state);\n\n/**\n * Get the current state of an axis control on a joystick\n *\n * @param[in] axis The axis indices start at index 0.\n *\n * @return The state is a value ranging from -32768 to 32767.\n */\nextern DECLSPEC Sint16 SDLCALL SDL_JoystickGetAxis(SDL_Joystick *joystick, int axis);\n\n/**\n *  @name Hat Positions\n *  The return value of SDL_JoystickGetHat() is one of the following positions:\n */\n/*@{*/\n#define SDL_HAT_CENTERED\t0x00\n#define SDL_HAT_UP\t\t0x01\n#define SDL_HAT_RIGHT\t\t0x02\n#define SDL_HAT_DOWN\t\t0x04\n#define SDL_HAT_LEFT\t\t0x08\n#define SDL_HAT_RIGHTUP\t\t(SDL_HAT_RIGHT|SDL_HAT_UP)\n#define SDL_HAT_RIGHTDOWN\t(SDL_HAT_RIGHT|SDL_HAT_DOWN)\n#define SDL_HAT_LEFTUP\t\t(SDL_HAT_LEFT|SDL_HAT_UP)\n#define SDL_HAT_LEFTDOWN\t(SDL_HAT_LEFT|SDL_HAT_DOWN)\n/*@}*/\n\n/** \n *  Get the current state of a POV hat on a joystick\n *\n *  @param[in] hat The hat indices start at index 0.\n */\nextern DECLSPEC Uint8 SDLCALL SDL_JoystickGetHat(SDL_Joystick *joystick, int hat);\n\n/**\n * Get the ball axis change since the last poll\n *\n * @param[in] ball The ball indices start at index 0.\n *\n * @return This returns 0, or -1 if you passed it invalid parameters.\n */\nextern DECLSPEC int SDLCALL SDL_JoystickGetBall(SDL_Joystick *joystick, int ball, int *dx, int *dy);\n\n/**\n * Get the current state of a button on a joystick\n *\n * @param[in] button The button indices start at index 0.\n */\nextern DECLSPEC Uint8 SDLCALL SDL_JoystickGetButton(SDL_Joystick *joystick, int button);\n\n/**\n * Close a joystick previously opened with SDL_JoystickOpen()\n */\nextern DECLSPEC void SDLCALL SDL_JoystickClose(SDL_Joystick *joystick);\n\n\n/* Ends C function definitions when using C++ */\n#ifdef __cplusplus\n}\n#endif\n#include \"close_code.h\"\n\n#endif /* _SDL_joystick_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_keyboard.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/** @file SDL_keyboard.h\n *  Include file for SDL keyboard event handling\n */\n\n#ifndef _SDL_keyboard_h\n#define _SDL_keyboard_h\n\n#include \"SDL_stdinc.h\"\n#include \"SDL_error.h\"\n#include \"SDL_keysym.h\"\n\n#include \"begin_code.h\"\n/* Set up for C function definitions, even when using C++ */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/** Keysym structure\n *\n *  - The scancode is hardware dependent, and should not be used by general\n *    applications.  If no hardware scancode is available, it will be 0.\n *\n *  - The 'unicode' translated character is only available when character\n *    translation is enabled by the SDL_EnableUNICODE() API.  If non-zero,\n *    this is a UNICODE character corresponding to the keypress.  If the\n *    high 9 bits of the character are 0, then this maps to the equivalent\n *    ASCII character:\n *      @code\n *\tchar ch;\n *\tif ( (keysym.unicode & 0xFF80) == 0 ) {\n *\t\tch = keysym.unicode & 0x7F;\n *\t} else {\n *\t\tAn international character..\n *\t}\n *      @endcode\n */\ntypedef struct SDL_keysym {\n\tUint8 scancode;\t\t\t/**< hardware specific scancode */\n\tSDLKey sym;\t\t\t/**< SDL virtual keysym */\n\tSDLMod mod;\t\t\t/**< current key modifiers */\n\tUint16 unicode;\t\t\t/**< translated character */\n} SDL_keysym;\n\n/** This is the mask which refers to all hotkey bindings */\n#define SDL_ALL_HOTKEYS\t\t0xFFFFFFFF\n\n/* Function prototypes */\n/**\n * Enable/Disable UNICODE translation of keyboard input.\n *\n * This translation has some overhead, so translation defaults off.\n *\n * @param[in] enable\n * If 'enable' is 1, translation is enabled.\n * If 'enable' is 0, translation is disabled.\n * If 'enable' is -1, the translation state is not changed.\n *\n * @return It returns the previous state of keyboard translation.\n */\nextern DECLSPEC int SDLCALL SDL_EnableUNICODE(int enable);\n\n#define SDL_DEFAULT_REPEAT_DELAY\t500\n#define SDL_DEFAULT_REPEAT_INTERVAL\t30\n/**\n * Enable/Disable keyboard repeat.  Keyboard repeat defaults to off.\n *\n *  @param[in] delay\n *  'delay' is the initial delay in ms between the time when a key is\n *  pressed, and keyboard repeat begins.\n *\n *  @param[in] interval\n *  'interval' is the time in ms between keyboard repeat events.\n *\n *  If 'delay' is set to 0, keyboard repeat is disabled.\n */\nextern DECLSPEC int SDLCALL SDL_EnableKeyRepeat(int delay, int interval);\nextern DECLSPEC void SDLCALL SDL_GetKeyRepeat(int *delay, int *interval);\n\n/**\n * Get a snapshot of the current state of the keyboard.\n * Returns an array of keystates, indexed by the SDLK_* syms.\n * Usage:\n *\t@code\n * \tUint8 *keystate = SDL_GetKeyState(NULL);\n *\tif ( keystate[SDLK_RETURN] ) //... \\<RETURN> is pressed.\n *\t@endcode\n */\nextern DECLSPEC Uint8 * SDLCALL SDL_GetKeyState(int *numkeys);\n\n/**\n * Get the current key modifier state\n */\nextern DECLSPEC SDLMod SDLCALL SDL_GetModState(void);\n\n/**\n * Set the current key modifier state.\n * This does not change the keyboard state, only the key modifier flags.\n */\nextern DECLSPEC void SDLCALL SDL_SetModState(SDLMod modstate);\n\n/**\n * Get the name of an SDL virtual keysym\n */\nextern DECLSPEC char * SDLCALL SDL_GetKeyName(SDLKey key);\n\n\n/* Ends C function definitions when using C++ */\n#ifdef __cplusplus\n}\n#endif\n#include \"close_code.h\"\n\n#endif /* _SDL_keyboard_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_keysym.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n#ifndef _SDL_keysym_h\n#define _SDL_keysym_h\n\n/** What we really want is a mapping of every raw key on the keyboard.\n *  To support international keyboards, we use the range 0xA1 - 0xFF\n *  as international virtual keycodes.  We'll follow in the footsteps of X11...\n *  @brief The names of the keys\n */\ntypedef enum {\n        /** @name ASCII mapped keysyms\n         *  The keyboard syms have been cleverly chosen to map to ASCII\n         */\n        /*@{*/\n\tSDLK_UNKNOWN\t\t= 0,\n\tSDLK_FIRST\t\t= 0,\n\tSDLK_BACKSPACE\t\t= 8,\n\tSDLK_TAB\t\t= 9,\n\tSDLK_CLEAR\t\t= 12,\n\tSDLK_RETURN\t\t= 13,\n\tSDLK_PAUSE\t\t= 19,\n\tSDLK_ESCAPE\t\t= 27,\n\tSDLK_SPACE\t\t= 32,\n\tSDLK_EXCLAIM\t\t= 33,\n\tSDLK_QUOTEDBL\t\t= 34,\n\tSDLK_HASH\t\t= 35,\n\tSDLK_DOLLAR\t\t= 36,\n\tSDLK_AMPERSAND\t\t= 38,\n\tSDLK_QUOTE\t\t= 39,\n\tSDLK_LEFTPAREN\t\t= 40,\n\tSDLK_RIGHTPAREN\t\t= 41,\n\tSDLK_ASTERISK\t\t= 42,\n\tSDLK_PLUS\t\t= 43,\n\tSDLK_COMMA\t\t= 44,\n\tSDLK_MINUS\t\t= 45,\n\tSDLK_PERIOD\t\t= 46,\n\tSDLK_SLASH\t\t= 47,\n\tSDLK_0\t\t\t= 48,\n\tSDLK_1\t\t\t= 49,\n\tSDLK_2\t\t\t= 50,\n\tSDLK_3\t\t\t= 51,\n\tSDLK_4\t\t\t= 52,\n\tSDLK_5\t\t\t= 53,\n\tSDLK_6\t\t\t= 54,\n\tSDLK_7\t\t\t= 55,\n\tSDLK_8\t\t\t= 56,\n\tSDLK_9\t\t\t= 57,\n\tSDLK_COLON\t\t= 58,\n\tSDLK_SEMICOLON\t\t= 59,\n\tSDLK_LESS\t\t= 60,\n\tSDLK_EQUALS\t\t= 61,\n\tSDLK_GREATER\t\t= 62,\n\tSDLK_QUESTION\t\t= 63,\n\tSDLK_AT\t\t\t= 64,\n\t/* \n\t   Skip uppercase letters\n\t */\n\tSDLK_LEFTBRACKET\t= 91,\n\tSDLK_BACKSLASH\t\t= 92,\n\tSDLK_RIGHTBRACKET\t= 93,\n\tSDLK_CARET\t\t= 94,\n\tSDLK_UNDERSCORE\t\t= 95,\n\tSDLK_BACKQUOTE\t\t= 96,\n\tSDLK_a\t\t\t= 97,\n\tSDLK_b\t\t\t= 98,\n\tSDLK_c\t\t\t= 99,\n\tSDLK_d\t\t\t= 100,\n\tSDLK_e\t\t\t= 101,\n\tSDLK_f\t\t\t= 102,\n\tSDLK_g\t\t\t= 103,\n\tSDLK_h\t\t\t= 104,\n\tSDLK_i\t\t\t= 105,\n\tSDLK_j\t\t\t= 106,\n\tSDLK_k\t\t\t= 107,\n\tSDLK_l\t\t\t= 108,\n\tSDLK_m\t\t\t= 109,\n\tSDLK_n\t\t\t= 110,\n\tSDLK_o\t\t\t= 111,\n\tSDLK_p\t\t\t= 112,\n\tSDLK_q\t\t\t= 113,\n\tSDLK_r\t\t\t= 114,\n\tSDLK_s\t\t\t= 115,\n\tSDLK_t\t\t\t= 116,\n\tSDLK_u\t\t\t= 117,\n\tSDLK_v\t\t\t= 118,\n\tSDLK_w\t\t\t= 119,\n\tSDLK_x\t\t\t= 120,\n\tSDLK_y\t\t\t= 121,\n\tSDLK_z\t\t\t= 122,\n\tSDLK_DELETE\t\t= 127,\n\t/* End of ASCII mapped keysyms */\n        /*@}*/\n\n\t/** @name International keyboard syms */\n        /*@{*/\n\tSDLK_WORLD_0\t\t= 160,\t\t/* 0xA0 */\n\tSDLK_WORLD_1\t\t= 161,\n\tSDLK_WORLD_2\t\t= 162,\n\tSDLK_WORLD_3\t\t= 163,\n\tSDLK_WORLD_4\t\t= 164,\n\tSDLK_WORLD_5\t\t= 165,\n\tSDLK_WORLD_6\t\t= 166,\n\tSDLK_WORLD_7\t\t= 167,\n\tSDLK_WORLD_8\t\t= 168,\n\tSDLK_WORLD_9\t\t= 169,\n\tSDLK_WORLD_10\t\t= 170,\n\tSDLK_WORLD_11\t\t= 171,\n\tSDLK_WORLD_12\t\t= 172,\n\tSDLK_WORLD_13\t\t= 173,\n\tSDLK_WORLD_14\t\t= 174,\n\tSDLK_WORLD_15\t\t= 175,\n\tSDLK_WORLD_16\t\t= 176,\n\tSDLK_WORLD_17\t\t= 177,\n\tSDLK_WORLD_18\t\t= 178,\n\tSDLK_WORLD_19\t\t= 179,\n\tSDLK_WORLD_20\t\t= 180,\n\tSDLK_WORLD_21\t\t= 181,\n\tSDLK_WORLD_22\t\t= 182,\n\tSDLK_WORLD_23\t\t= 183,\n\tSDLK_WORLD_24\t\t= 184,\n\tSDLK_WORLD_25\t\t= 185,\n\tSDLK_WORLD_26\t\t= 186,\n\tSDLK_WORLD_27\t\t= 187,\n\tSDLK_WORLD_28\t\t= 188,\n\tSDLK_WORLD_29\t\t= 189,\n\tSDLK_WORLD_30\t\t= 190,\n\tSDLK_WORLD_31\t\t= 191,\n\tSDLK_WORLD_32\t\t= 192,\n\tSDLK_WORLD_33\t\t= 193,\n\tSDLK_WORLD_34\t\t= 194,\n\tSDLK_WORLD_35\t\t= 195,\n\tSDLK_WORLD_36\t\t= 196,\n\tSDLK_WORLD_37\t\t= 197,\n\tSDLK_WORLD_38\t\t= 198,\n\tSDLK_WORLD_39\t\t= 199,\n\tSDLK_WORLD_40\t\t= 200,\n\tSDLK_WORLD_41\t\t= 201,\n\tSDLK_WORLD_42\t\t= 202,\n\tSDLK_WORLD_43\t\t= 203,\n\tSDLK_WORLD_44\t\t= 204,\n\tSDLK_WORLD_45\t\t= 205,\n\tSDLK_WORLD_46\t\t= 206,\n\tSDLK_WORLD_47\t\t= 207,\n\tSDLK_WORLD_48\t\t= 208,\n\tSDLK_WORLD_49\t\t= 209,\n\tSDLK_WORLD_50\t\t= 210,\n\tSDLK_WORLD_51\t\t= 211,\n\tSDLK_WORLD_52\t\t= 212,\n\tSDLK_WORLD_53\t\t= 213,\n\tSDLK_WORLD_54\t\t= 214,\n\tSDLK_WORLD_55\t\t= 215,\n\tSDLK_WORLD_56\t\t= 216,\n\tSDLK_WORLD_57\t\t= 217,\n\tSDLK_WORLD_58\t\t= 218,\n\tSDLK_WORLD_59\t\t= 219,\n\tSDLK_WORLD_60\t\t= 220,\n\tSDLK_WORLD_61\t\t= 221,\n\tSDLK_WORLD_62\t\t= 222,\n\tSDLK_WORLD_63\t\t= 223,\n\tSDLK_WORLD_64\t\t= 224,\n\tSDLK_WORLD_65\t\t= 225,\n\tSDLK_WORLD_66\t\t= 226,\n\tSDLK_WORLD_67\t\t= 227,\n\tSDLK_WORLD_68\t\t= 228,\n\tSDLK_WORLD_69\t\t= 229,\n\tSDLK_WORLD_70\t\t= 230,\n\tSDLK_WORLD_71\t\t= 231,\n\tSDLK_WORLD_72\t\t= 232,\n\tSDLK_WORLD_73\t\t= 233,\n\tSDLK_WORLD_74\t\t= 234,\n\tSDLK_WORLD_75\t\t= 235,\n\tSDLK_WORLD_76\t\t= 236,\n\tSDLK_WORLD_77\t\t= 237,\n\tSDLK_WORLD_78\t\t= 238,\n\tSDLK_WORLD_79\t\t= 239,\n\tSDLK_WORLD_80\t\t= 240,\n\tSDLK_WORLD_81\t\t= 241,\n\tSDLK_WORLD_82\t\t= 242,\n\tSDLK_WORLD_83\t\t= 243,\n\tSDLK_WORLD_84\t\t= 244,\n\tSDLK_WORLD_85\t\t= 245,\n\tSDLK_WORLD_86\t\t= 246,\n\tSDLK_WORLD_87\t\t= 247,\n\tSDLK_WORLD_88\t\t= 248,\n\tSDLK_WORLD_89\t\t= 249,\n\tSDLK_WORLD_90\t\t= 250,\n\tSDLK_WORLD_91\t\t= 251,\n\tSDLK_WORLD_92\t\t= 252,\n\tSDLK_WORLD_93\t\t= 253,\n\tSDLK_WORLD_94\t\t= 254,\n\tSDLK_WORLD_95\t\t= 255,\t\t/* 0xFF */\n        /*@}*/\n\n\t/** @name Numeric keypad */\n        /*@{*/\n\tSDLK_KP0\t\t= 256,\n\tSDLK_KP1\t\t= 257,\n\tSDLK_KP2\t\t= 258,\n\tSDLK_KP3\t\t= 259,\n\tSDLK_KP4\t\t= 260,\n\tSDLK_KP5\t\t= 261,\n\tSDLK_KP6\t\t= 262,\n\tSDLK_KP7\t\t= 263,\n\tSDLK_KP8\t\t= 264,\n\tSDLK_KP9\t\t= 265,\n\tSDLK_KP_PERIOD\t\t= 266,\n\tSDLK_KP_DIVIDE\t\t= 267,\n\tSDLK_KP_MULTIPLY\t= 268,\n\tSDLK_KP_MINUS\t\t= 269,\n\tSDLK_KP_PLUS\t\t= 270,\n\tSDLK_KP_ENTER\t\t= 271,\n\tSDLK_KP_EQUALS\t\t= 272,\n        /*@}*/\n\n\t/** @name Arrows + Home/End pad */\n        /*@{*/\n\tSDLK_UP\t\t\t= 273,\n\tSDLK_DOWN\t\t= 274,\n\tSDLK_RIGHT\t\t= 275,\n\tSDLK_LEFT\t\t= 276,\n\tSDLK_INSERT\t\t= 277,\n\tSDLK_HOME\t\t= 278,\n\tSDLK_END\t\t= 279,\n\tSDLK_PAGEUP\t\t= 280,\n\tSDLK_PAGEDOWN\t\t= 281,\n        /*@}*/\n\n\t/** @name Function keys */\n        /*@{*/\n\tSDLK_F1\t\t\t= 282,\n\tSDLK_F2\t\t\t= 283,\n\tSDLK_F3\t\t\t= 284,\n\tSDLK_F4\t\t\t= 285,\n\tSDLK_F5\t\t\t= 286,\n\tSDLK_F6\t\t\t= 287,\n\tSDLK_F7\t\t\t= 288,\n\tSDLK_F8\t\t\t= 289,\n\tSDLK_F9\t\t\t= 290,\n\tSDLK_F10\t\t= 291,\n\tSDLK_F11\t\t= 292,\n\tSDLK_F12\t\t= 293,\n\tSDLK_F13\t\t= 294,\n\tSDLK_F14\t\t= 295,\n\tSDLK_F15\t\t= 296,\n        /*@}*/\n\n\t/** @name Key state modifier keys */\n        /*@{*/\n\tSDLK_NUMLOCK\t\t= 300,\n\tSDLK_CAPSLOCK\t\t= 301,\n\tSDLK_SCROLLOCK\t\t= 302,\n\tSDLK_RSHIFT\t\t= 303,\n\tSDLK_LSHIFT\t\t= 304,\n\tSDLK_RCTRL\t\t= 305,\n\tSDLK_LCTRL\t\t= 306,\n\tSDLK_RALT\t\t= 307,\n\tSDLK_LALT\t\t= 308,\n\tSDLK_RMETA\t\t= 309,\n\tSDLK_LMETA\t\t= 310,\n\tSDLK_LSUPER\t\t= 311,\t\t/**< Left \"Windows\" key */\n\tSDLK_RSUPER\t\t= 312,\t\t/**< Right \"Windows\" key */\n\tSDLK_MODE\t\t= 313,\t\t/**< \"Alt Gr\" key */\n\tSDLK_COMPOSE\t\t= 314,\t\t/**< Multi-key compose key */\n        /*@}*/\n\n\t/** @name Miscellaneous function keys */\n        /*@{*/\n\tSDLK_HELP\t\t= 315,\n\tSDLK_PRINT\t\t= 316,\n\tSDLK_SYSREQ\t\t= 317,\n\tSDLK_BREAK\t\t= 318,\n\tSDLK_MENU\t\t= 319,\n\tSDLK_POWER\t\t= 320,\t\t/**< Power Macintosh power key */\n\tSDLK_EURO\t\t= 321,\t\t/**< Some european keyboards */\n\tSDLK_UNDO\t\t= 322,\t\t/**< Atari keyboard has Undo */\n        /*@}*/\n\n\t/* Add any other keys here */\n\n\tSDLK_LAST\n} SDLKey;\n\n/** Enumeration of valid key mods (possibly OR'd together) */\ntypedef enum {\n\tKMOD_NONE  = 0x0000,\n\tKMOD_LSHIFT= 0x0001,\n\tKMOD_RSHIFT= 0x0002,\n\tKMOD_LCTRL = 0x0040,\n\tKMOD_RCTRL = 0x0080,\n\tKMOD_LALT  = 0x0100,\n\tKMOD_RALT  = 0x0200,\n\tKMOD_LMETA = 0x0400,\n\tKMOD_RMETA = 0x0800,\n\tKMOD_NUM   = 0x1000,\n\tKMOD_CAPS  = 0x2000,\n\tKMOD_MODE  = 0x4000,\n\tKMOD_RESERVED = 0x8000\n} SDLMod;\n\n#define KMOD_CTRL\t(KMOD_LCTRL|KMOD_RCTRL)\n#define KMOD_SHIFT\t(KMOD_LSHIFT|KMOD_RSHIFT)\n#define KMOD_ALT\t(KMOD_LALT|KMOD_RALT)\n#define KMOD_META\t(KMOD_LMETA|KMOD_RMETA)\n\n#endif /* _SDL_keysym_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_loadso.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/** @file SDL_loadso.h\n *  System dependent library loading routines\n */\n\n/** @file SDL_loadso.h\n *  Some things to keep in mind:                                        \n *  - These functions only work on C function names.  Other languages may\n *    have name mangling and intrinsic language support that varies from\n *    compiler to compiler.\n *  - Make sure you declare your function pointers with the same calling\n *    convention as the actual library function.  Your code will crash\n *    mysteriously if you do not do this.\n *  - Avoid namespace collisions.  If you load a symbol from the library,\n *    it is not defined whether or not it goes into the global symbol\n *    namespace for the application.  If it does and it conflicts with\n *    symbols in your code or other shared libraries, you will not get\n *    the results you expect. :)\n */\n\n\n#ifndef _SDL_loadso_h\n#define _SDL_loadso_h\n\n#include \"SDL_stdinc.h\"\n#include \"SDL_error.h\"\n\n#include \"begin_code.h\"\n/* Set up for C function definitions, even when using C++ */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * This function dynamically loads a shared object and returns a pointer\n * to the object handle (or NULL if there was an error).\n * The 'sofile' parameter is a system dependent name of the object file.\n */\nextern DECLSPEC void * SDLCALL SDL_LoadObject(const char *sofile);\n\n/**\n * Given an object handle, this function looks up the address of the\n * named function in the shared object and returns it.  This address\n * is no longer valid after calling SDL_UnloadObject().\n */\nextern DECLSPEC void * SDLCALL SDL_LoadFunction(void *handle, const char *name);\n\n/** Unload a shared object from memory */\nextern DECLSPEC void SDLCALL SDL_UnloadObject(void *handle);\n\n/* Ends C function definitions when using C++ */\n#ifdef __cplusplus\n}\n#endif\n#include \"close_code.h\"\n\n#endif /* _SDL_loadso_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_main.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n#ifndef _SDL_main_h\n#define _SDL_main_h\n\n#include \"SDL_stdinc.h\"\n\n/** @file SDL_main.h\n *  Redefine main() on Win32 and MacOS so that it is called by winmain.c\n */\n\n#if defined(__WIN32__) || \\\n    (defined(__MWERKS__) && !defined(__BEOS__)) || \\\n    defined(__MACOS__) || defined(__MACOSX__) || \\\n    defined(__SYMBIAN32__) || defined(QWS)\n\n#ifdef __cplusplus\n#define C_LINKAGE\t\"C\"\n#else\n#define C_LINKAGE\n#endif /* __cplusplus */\n\n/** The application's main() function must be called with C linkage,\n *  and should be declared like this:\n *      @code\n *      #ifdef __cplusplus\n *      extern \"C\"\n *      #endif\n *\tint main(int argc, char *argv[])\n *\t{\n *\t}\n *      @endcode\n */\n#define main\tSDL_main\n\n/** The prototype for the application's main() function */\nextern C_LINKAGE int SDL_main(int argc, char *argv[]);\n\n\n/** @name From the SDL library code -- needed for registering the app on Win32 */\n/*@{*/\n#ifdef __WIN32__\n\n#include \"begin_code.h\"\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/** This should be called from your WinMain() function, if any */\nextern DECLSPEC void SDLCALL SDL_SetModuleHandle(void *hInst);\n/** This can also be called, but is no longer necessary */\nextern DECLSPEC int SDLCALL SDL_RegisterApp(char *name, Uint32 style, void *hInst);\n/** This can also be called, but is no longer necessary (SDL_Quit calls it) */\nextern DECLSPEC void SDLCALL SDL_UnregisterApp(void);\n#ifdef __cplusplus\n}\n#endif\n#include \"close_code.h\"\n#endif\n/*@}*/\n\n/** @name From the SDL library code -- needed for registering QuickDraw on MacOS */\n/*@{*/\n#if defined(__MACOS__)\n\n#include \"begin_code.h\"\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/** Forward declaration so we don't need to include QuickDraw.h */\nstruct QDGlobals;\n\n/** This should be called from your main() function, if any */\nextern DECLSPEC void SDLCALL SDL_InitQuickDraw(struct QDGlobals *the_qd);\n\n#ifdef __cplusplus\n}\n#endif\n#include \"close_code.h\"\n#endif\n/*@}*/\n\n#endif /* Need to redefine main()? */\n\n#endif /* _SDL_main_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_mouse.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/** @file SDL_mouse.h\n *  Include file for SDL mouse event handling\n */\n\n#ifndef _SDL_mouse_h\n#define _SDL_mouse_h\n\n#include \"SDL_stdinc.h\"\n#include \"SDL_error.h\"\n#include \"SDL_video.h\"\n\n#include \"begin_code.h\"\n/* Set up for C function definitions, even when using C++ */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\ntypedef struct WMcursor WMcursor;\t/**< Implementation dependent */\ntypedef struct SDL_Cursor {\n\tSDL_Rect area;\t\t\t/**< The area of the mouse cursor */\n\tSint16 hot_x, hot_y;\t\t/**< The \"tip\" of the cursor */\n\tUint8 *data;\t\t\t/**< B/W cursor data */\n\tUint8 *mask;\t\t\t/**< B/W cursor mask */\n\tUint8 *save[2];\t\t\t/**< Place to save cursor area */\n\tWMcursor *wm_cursor;\t\t/**< Window-manager cursor */\n} SDL_Cursor;\n\n/* Function prototypes */\n/**\n * Retrieve the current state of the mouse.\n * The current button state is returned as a button bitmask, which can\n * be tested using the SDL_BUTTON(X) macros, and x and y are set to the\n * current mouse cursor position.  You can pass NULL for either x or y.\n */\nextern DECLSPEC Uint8 SDLCALL SDL_GetMouseState(int *x, int *y);\n\n/**\n * Retrieve the current state of the mouse.\n * The current button state is returned as a button bitmask, which can\n * be tested using the SDL_BUTTON(X) macros, and x and y are set to the\n * mouse deltas since the last call to SDL_GetRelativeMouseState().\n */\nextern DECLSPEC Uint8 SDLCALL SDL_GetRelativeMouseState(int *x, int *y);\n\n/**\n * Set the position of the mouse cursor (generates a mouse motion event)\n */\nextern DECLSPEC void SDLCALL SDL_WarpMouse(Uint16 x, Uint16 y);\n\n/**\n * Create a cursor using the specified data and mask (in MSB format).\n * The cursor width must be a multiple of 8 bits.\n *\n * The cursor is created in black and white according to the following:\n * data  mask    resulting pixel on screen\n *  0     1       White\n *  1     1       Black\n *  0     0       Transparent\n *  1     0       Inverted color if possible, black if not.\n *\n * Cursors created with this function must be freed with SDL_FreeCursor().\n */\nextern DECLSPEC SDL_Cursor * SDLCALL SDL_CreateCursor\n\t\t(Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y);\n\n/**\n * Set the currently active cursor to the specified one.\n * If the cursor is currently visible, the change will be immediately \n * represented on the display.\n */\nextern DECLSPEC void SDLCALL SDL_SetCursor(SDL_Cursor *cursor);\n\n/**\n * Returns the currently active cursor.\n */\nextern DECLSPEC SDL_Cursor * SDLCALL SDL_GetCursor(void);\n\n/**\n * Deallocates a cursor created with SDL_CreateCursor().\n */\nextern DECLSPEC void SDLCALL SDL_FreeCursor(SDL_Cursor *cursor);\n\n/**\n * Toggle whether or not the cursor is shown on the screen.\n * The cursor start off displayed, but can be turned off.\n * SDL_ShowCursor() returns 1 if the cursor was being displayed\n * before the call, or 0 if it was not.  You can query the current\n * state by passing a 'toggle' value of -1.\n */\nextern DECLSPEC int SDLCALL SDL_ShowCursor(int toggle);\n\n/*@{*/\n/** Used as a mask when testing buttons in buttonstate\n *  Button 1:\tLeft mouse button\n *  Button 2:\tMiddle mouse button\n *  Button 3:\tRight mouse button\n *  Button 4:\tMouse wheel up\t (may also be a real button)\n *  Button 5:\tMouse wheel down (may also be a real button)\n */\n#define SDL_BUTTON(X)\t\t(1 << ((X)-1))\n#define SDL_BUTTON_LEFT\t\t1\n#define SDL_BUTTON_MIDDLE\t2\n#define SDL_BUTTON_RIGHT\t3\n#define SDL_BUTTON_WHEELUP\t4\n#define SDL_BUTTON_WHEELDOWN\t5\n#define SDL_BUTTON_X1\t\t6\n#define SDL_BUTTON_X2\t\t7\n#define SDL_BUTTON_LMASK\tSDL_BUTTON(SDL_BUTTON_LEFT)\n#define SDL_BUTTON_MMASK\tSDL_BUTTON(SDL_BUTTON_MIDDLE)\n#define SDL_BUTTON_RMASK\tSDL_BUTTON(SDL_BUTTON_RIGHT)\n#define SDL_BUTTON_X1MASK\tSDL_BUTTON(SDL_BUTTON_X1)\n#define SDL_BUTTON_X2MASK\tSDL_BUTTON(SDL_BUTTON_X2)\n/*@}*/\n\n/* Ends C function definitions when using C++ */\n#ifdef __cplusplus\n}\n#endif\n#include \"close_code.h\"\n\n#endif /* _SDL_mouse_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_mutex.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n#ifndef _SDL_mutex_h\n#define _SDL_mutex_h\n\n/** @file SDL_mutex.h\n *  Functions to provide thread synchronization primitives\n *\n *  @note These are independent of the other SDL routines.\n */\n\n#include \"SDL_stdinc.h\"\n#include \"SDL_error.h\"\n\n#include \"begin_code.h\"\n/* Set up for C function definitions, even when using C++ */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/** Synchronization functions which can time out return this value\n *  if they time out.\n */\n#define SDL_MUTEX_TIMEDOUT\t1\n\n/** This is the timeout value which corresponds to never time out */\n#define SDL_MUTEX_MAXWAIT\t(~(Uint32)0)\n\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/** @name Mutex functions                                        */ /*@{*/\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n/** The SDL mutex structure, defined in SDL_mutex.c */\nstruct SDL_mutex;\ntypedef struct SDL_mutex SDL_mutex;\n\n/** Create a mutex, initialized unlocked */\nextern DECLSPEC SDL_mutex * SDLCALL SDL_CreateMutex(void);\n\n#define SDL_LockMutex(m)\tSDL_mutexP(m)\n/** Lock the mutex\n *  @return 0, or -1 on error\n */\nextern DECLSPEC int SDLCALL SDL_mutexP(SDL_mutex *mutex);\n\n#define SDL_UnlockMutex(m)\tSDL_mutexV(m)\n/** Unlock the mutex\n *  @return 0, or -1 on error\n *\n *  It is an error to unlock a mutex that has not been locked by\n *  the current thread, and doing so results in undefined behavior.\n */\nextern DECLSPEC int SDLCALL SDL_mutexV(SDL_mutex *mutex);\n\n/** Destroy a mutex */\nextern DECLSPEC void SDLCALL SDL_DestroyMutex(SDL_mutex *mutex);\n\n/*@}*/\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/** @name Semaphore functions                                    */ /*@{*/\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n/** The SDL semaphore structure, defined in SDL_sem.c */\nstruct SDL_semaphore;\ntypedef struct SDL_semaphore SDL_sem;\n\n/** Create a semaphore, initialized with value, returns NULL on failure. */\nextern DECLSPEC SDL_sem * SDLCALL SDL_CreateSemaphore(Uint32 initial_value);\n\n/** Destroy a semaphore */\nextern DECLSPEC void SDLCALL SDL_DestroySemaphore(SDL_sem *sem);\n\n/**\n * This function suspends the calling thread until the semaphore pointed \n * to by sem has a positive count. It then atomically decreases the semaphore\n * count.\n */\nextern DECLSPEC int SDLCALL SDL_SemWait(SDL_sem *sem);\n\n/** Non-blocking variant of SDL_SemWait().\n *  @return 0 if the wait succeeds,\n *  SDL_MUTEX_TIMEDOUT if the wait would block, and -1 on error.\n */\nextern DECLSPEC int SDLCALL SDL_SemTryWait(SDL_sem *sem);\n\n/** Variant of SDL_SemWait() with a timeout in milliseconds, returns 0 if\n *  the wait succeeds, SDL_MUTEX_TIMEDOUT if the wait does not succeed in\n *  the allotted time, and -1 on error.\n *\n *  On some platforms this function is implemented by looping with a delay\n *  of 1 ms, and so should be avoided if possible.\n */\nextern DECLSPEC int SDLCALL SDL_SemWaitTimeout(SDL_sem *sem, Uint32 ms);\n\n/** Atomically increases the semaphore's count (not blocking).\n *  @return 0, or -1 on error.\n */\nextern DECLSPEC int SDLCALL SDL_SemPost(SDL_sem *sem);\n\n/** Returns the current count of the semaphore */\nextern DECLSPEC Uint32 SDLCALL SDL_SemValue(SDL_sem *sem);\n\n/*@}*/\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/** @name Condition_variable_functions                           */ /*@{*/\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n/*@{*/\n/** The SDL condition variable structure, defined in SDL_cond.c */\nstruct SDL_cond;\ntypedef struct SDL_cond SDL_cond;\n/*@}*/\n\n/** Create a condition variable */\nextern DECLSPEC SDL_cond * SDLCALL SDL_CreateCond(void);\n\n/** Destroy a condition variable */\nextern DECLSPEC void SDLCALL SDL_DestroyCond(SDL_cond *cond);\n\n/** Restart one of the threads that are waiting on the condition variable,\n *  @return 0 or -1 on error.\n */\nextern DECLSPEC int SDLCALL SDL_CondSignal(SDL_cond *cond);\n\n/** Restart all threads that are waiting on the condition variable,\n *  @return 0 or -1 on error.\n */\nextern DECLSPEC int SDLCALL SDL_CondBroadcast(SDL_cond *cond);\n\n/** Wait on the condition variable, unlocking the provided mutex.\n *  The mutex must be locked before entering this function!\n *  The mutex is re-locked once the condition variable is signaled.\n *  @return 0 when it is signaled, or -1 on error.\n */\nextern DECLSPEC int SDLCALL SDL_CondWait(SDL_cond *cond, SDL_mutex *mut);\n\n/** Waits for at most 'ms' milliseconds, and returns 0 if the condition\n *  variable is signaled, SDL_MUTEX_TIMEDOUT if the condition is not\n *  signaled in the allotted time, and -1 on error.\n *  On some platforms this function is implemented by looping with a delay\n *  of 1 ms, and so should be avoided if possible.\n */\nextern DECLSPEC int SDLCALL SDL_CondWaitTimeout(SDL_cond *cond, SDL_mutex *mutex, Uint32 ms);\n\n/*@}*/\n\n/* Ends C function definitions when using C++ */\n#ifdef __cplusplus\n}\n#endif\n#include \"close_code.h\"\n\n#endif /* _SDL_mutex_h */\n\n"
  },
  {
    "path": "other/sdl/include/SDL_name.h",
    "content": "\n#ifndef _SDLname_h_\n#define _SDLname_h_\n\n#if defined(__STDC__) || defined(__cplusplus)\n#define NeedFunctionPrototypes 1\n#endif\n\n#define SDL_NAME(X)\tSDL_##X\n\n#endif /* _SDLname_h_ */\n"
  },
  {
    "path": "other/sdl/include/SDL_opengl.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/** @file SDL_opengl.h\n *  This is a simple file to encapsulate the OpenGL API headers\n */\n\n#include \"SDL_config.h\"\n\n#ifdef __WIN32__\n#define WIN32_LEAN_AND_MEAN\n#ifndef NOMINMAX\n#define NOMINMAX\t/* Don't defined min() and max() */\n#endif\n#include <windows.h>\n#endif\n#ifndef NO_SDL_GLEXT\n#define __glext_h_  /* Don't let gl.h include glext.h */\n#endif\n#if defined(__MACOSX__)\n#include <OpenGL/gl.h>\t/* Header File For The OpenGL Library */\n#include <OpenGL/glu.h>\t/* Header File For The GLU Library */\n#elif defined(__MACOS__)\n#include <gl.h>\t\t/* Header File For The OpenGL Library */\n#include <glu.h>\t/* Header File For The GLU Library */\n#else\n#include <GL/gl.h>\t/* Header File For The OpenGL Library */\n#include <GL/glu.h>\t/* Header File For The GLU Library */\n#endif\n#ifndef NO_SDL_GLEXT\n#undef __glext_h_\n#endif\n\n/** @name GLext.h\n *  This file taken from \"GLext.h\" from the Jeff Molofee OpenGL tutorials.\n *  It is included here because glext.h is not available on some systems.\n *  If you don't want this version included, simply define \"NO_SDL_GLEXT\"\n */\n/*@{*/\n#ifndef NO_SDL_GLEXT\n#if !defined(__glext_h_) && !defined(GL_GLEXT_LEGACY)\n#define __glext_h_\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/*\n** License Applicability. Except to the extent portions of this file are\n** made subject to an alternative license as permitted in the SGI Free\n** Software License B, Version 1.1 (the \"License\"), the contents of this\n** file are subject only to the provisions of the License. You may not use\n** this file except in compliance with the License. You may obtain a copy\n** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600\n** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:\n** \n** http://oss.sgi.com/projects/FreeB\n** \n** Note that, as provided in the License, the Software is distributed on an\n** \"AS IS\" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS\n** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND\n** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A\n** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.\n** \n** Original Code. The Original Code is: OpenGL Sample Implementation,\n** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,\n** Inc. The Original Code is Copyright (c) 1991-2004 Silicon Graphics, Inc.\n** Copyright in any portions created by third parties is as indicated\n** elsewhere herein. All Rights Reserved.\n** \n** Additional Notice Provisions: This software was created using the\n** OpenGL(R) version 1.2.1 Sample Implementation published by SGI, but has\n** not been independently verified as being compliant with the OpenGL(R)\n** version 1.2.1 Specification.\n*/\n\n#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)\n#define WIN32_LEAN_AND_MEAN 1\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/*************************************************************/\n\n/* Header file version number, required by OpenGL ABI for Linux */\n/* glext.h last updated 2005/06/20 */\n/* Current version at http://oss.sgi.com/projects/ogl-sample/registry/ */\n#define GL_GLEXT_VERSION 29\n\n#ifndef GL_VERSION_1_2\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_RESCALE_NORMAL                 0x803A\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_LIGHT_MODEL_COLOR_CONTROL      0x81F8\n#define GL_SINGLE_COLOR                   0x81F9\n#define GL_SEPARATE_SPECULAR_COLOR        0x81FA\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_POINT_SIZE_RANGE       0x846D\n#define GL_ALIASED_LINE_WIDTH_RANGE       0x846E\n#endif\n\n#ifndef GL_ARB_imaging\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\n#define GL_BLEND_COLOR                    0x8005\n#define GL_FUNC_ADD                       0x8006\n#define GL_MIN                            0x8007\n#define GL_MAX                            0x8008\n#define GL_BLEND_EQUATION                 0x8009\n#define GL_FUNC_SUBTRACT                  0x800A\n#define GL_FUNC_REVERSE_SUBTRACT          0x800B\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\n#endif\n\n#ifndef GL_VERSION_1_3\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_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                    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_MULTISAMPLE_BIT                0x20000000\n#define GL_NORMAL_MAP                     0x8511\n#define GL_REFLECTION_MAP                 0x8512\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_ALPHA               0x84E9\n#define GL_COMPRESSED_LUMINANCE           0x84EA\n#define GL_COMPRESSED_LUMINANCE_ALPHA     0x84EB\n#define GL_COMPRESSED_INTENSITY           0x84EC\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_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\n#endif\n\n#ifndef GL_VERSION_1_4\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_SIZE_MIN                 0x8126\n#define GL_POINT_SIZE_MAX                 0x8127\n#define GL_POINT_FADE_THRESHOLD_SIZE      0x8128\n#define GL_POINT_DISTANCE_ATTENUATION     0x8129\n#define GL_GENERATE_MIPMAP                0x8191\n#define GL_GENERATE_MIPMAP_HINT           0x8192\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_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_MAX_TEXTURE_LOD_BIAS           0x84FD\n#define GL_TEXTURE_FILTER_CONTROL         0x8500\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_DEPTH_TEXTURE_MODE             0x884B\n#define GL_TEXTURE_COMPARE_MODE           0x884C\n#define GL_TEXTURE_COMPARE_FUNC           0x884D\n#define GL_COMPARE_R_TO_TEXTURE           0x884E\n#endif\n\n#ifndef GL_VERSION_1_5\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_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_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_FOG_COORD_SRC                  GL_FOG_COORDINATE_SOURCE\n#define GL_FOG_COORD                      GL_FOG_COORDINATE\n#define GL_CURRENT_FOG_COORD              GL_CURRENT_FOG_COORDINATE\n#define GL_FOG_COORD_ARRAY_TYPE           GL_FOG_COORDINATE_ARRAY_TYPE\n#define GL_FOG_COORD_ARRAY_STRIDE         GL_FOG_COORDINATE_ARRAY_STRIDE\n#define GL_FOG_COORD_ARRAY_POINTER        GL_FOG_COORDINATE_ARRAY_POINTER\n#define GL_FOG_COORD_ARRAY                GL_FOG_COORDINATE_ARRAY\n#define GL_FOG_COORD_ARRAY_BUFFER_BINDING GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING\n#define GL_SRC0_RGB                       GL_SOURCE0_RGB\n#define GL_SRC1_RGB                       GL_SOURCE1_RGB\n#define GL_SRC2_RGB                       GL_SOURCE2_RGB\n#define GL_SRC0_ALPHA                     GL_SOURCE0_ALPHA\n#define GL_SRC1_ALPHA                     GL_SOURCE1_ALPHA\n#define GL_SRC2_ALPHA                     GL_SOURCE2_ALPHA\n#endif\n\n#ifndef GL_VERSION_2_0\n#define GL_BLEND_EQUATION_RGB             GL_BLEND_EQUATION\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_PROGRAM_TWO_SIDE        0x8643\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_POINT_SPRITE                   0x8861\n#define GL_COORD_REPLACE                  0x8862\n#define GL_MAX_VERTEX_ATTRIBS             0x8869\n#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A\n#define GL_MAX_TEXTURE_COORDS             0x8871\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#endif\n\n#ifndef GL_ARB_multitexture\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\n#endif\n\n#ifndef GL_ARB_transpose_matrix\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\n#endif\n\n#ifndef GL_ARB_multisample\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\n#endif\n\n#ifndef GL_ARB_texture_env_add\n#endif\n\n#ifndef GL_ARB_texture_cube_map\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\n\n#ifndef GL_ARB_texture_compression\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\n#endif\n\n#ifndef GL_ARB_texture_border_clamp\n#define GL_CLAMP_TO_BORDER_ARB            0x812D\n#endif\n\n#ifndef GL_ARB_point_parameters\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\n#endif\n\n#ifndef GL_ARB_vertex_blend\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\n#endif\n\n#ifndef GL_ARB_matrix_palette\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\n#endif\n\n#ifndef GL_ARB_texture_env_combine\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\n\n#ifndef GL_ARB_texture_env_crossbar\n#endif\n\n#ifndef GL_ARB_texture_env_dot3\n#define GL_DOT3_RGB_ARB                   0x86AE\n#define GL_DOT3_RGBA_ARB                  0x86AF\n#endif\n\n#ifndef GL_ARB_texture_mirrored_repeat\n#define GL_MIRRORED_REPEAT_ARB            0x8370\n#endif\n\n#ifndef GL_ARB_depth_texture\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\n\n#ifndef GL_ARB_shadow\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\n\n#ifndef GL_ARB_shadow_ambient\n#define GL_TEXTURE_COMPARE_FAIL_VALUE_ARB 0x80BF\n#endif\n\n#ifndef GL_ARB_window_pos\n#endif\n\n#ifndef GL_ARB_vertex_program\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_PROGRAM_LENGTH_ARB             0x8627\n#define GL_PROGRAM_STRING_ARB             0x8628\n#define GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB 0x862E\n#define GL_MAX_PROGRAM_MATRICES_ARB       0x862F\n#define GL_CURRENT_MATRIX_STACK_DEPTH_ARB 0x8640\n#define GL_CURRENT_MATRIX_ARB             0x8641\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_PROGRAM_ERROR_POSITION_ARB     0x864B\n#define GL_PROGRAM_BINDING_ARB            0x8677\n#define GL_MAX_VERTEX_ATTRIBS_ARB         0x8869\n#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB 0x886A\n#define GL_PROGRAM_ERROR_STRING_ARB       0x8874\n#define GL_PROGRAM_FORMAT_ASCII_ARB       0x8875\n#define GL_PROGRAM_FORMAT_ARB             0x8876\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_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\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_TRANSPOSE_CURRENT_MATRIX_ARB   0x88B7\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\n#endif\n\n#ifndef GL_ARB_fragment_program\n#define GL_FRAGMENT_PROGRAM_ARB           0x8804\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_MAX_TEXTURE_COORDS_ARB         0x8871\n#define GL_MAX_TEXTURE_IMAGE_UNITS_ARB    0x8872\n#endif\n\n#ifndef GL_ARB_vertex_buffer_object\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\n#endif\n\n#ifndef GL_ARB_occlusion_query\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\n#endif\n\n#ifndef GL_ARB_shader_objects\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\n#endif\n\n#ifndef GL_ARB_vertex_shader\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\n#endif\n\n#ifndef GL_ARB_fragment_shader\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\n\n#ifndef GL_ARB_shading_language_100\n#define GL_SHADING_LANGUAGE_VERSION_ARB   0x8B8C\n#endif\n\n#ifndef GL_ARB_texture_non_power_of_two\n#endif\n\n#ifndef GL_ARB_point_sprite\n#define GL_POINT_SPRITE_ARB               0x8861\n#define GL_COORD_REPLACE_ARB              0x8862\n#endif\n\n#ifndef GL_ARB_fragment_program_shadow\n#endif\n\n#ifndef GL_ARB_draw_buffers\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\n#endif\n\n#ifndef GL_ARB_texture_rectangle\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\n\n#ifndef GL_ARB_color_buffer_float\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\n#endif\n\n#ifndef GL_ARB_half_float_pixel\n#define GL_HALF_FLOAT_ARB                 0x140B\n#endif\n\n#ifndef GL_ARB_texture_float\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\n\n#ifndef GL_ARB_pixel_buffer_object\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\n\n#ifndef GL_EXT_abgr\n#define GL_ABGR_EXT                       0x8000\n#endif\n\n#ifndef GL_EXT_blend_color\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\n#endif\n\n#ifndef GL_EXT_polygon_offset\n#define GL_POLYGON_OFFSET_EXT             0x8037\n#define GL_POLYGON_OFFSET_FACTOR_EXT      0x8038\n#define GL_POLYGON_OFFSET_BIAS_EXT        0x8039\n#endif\n\n#ifndef GL_EXT_texture\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\n\n#ifndef GL_EXT_texture3D\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\n#endif\n\n#ifndef GL_SGIS_texture_filter4\n#define GL_FILTER4_SGIS                   0x8146\n#define GL_TEXTURE_FILTER4_SIZE_SGIS      0x8147\n#endif\n\n#ifndef GL_EXT_subtexture\n#endif\n\n#ifndef GL_EXT_copy_texture\n#endif\n\n#ifndef GL_EXT_histogram\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\n#endif\n\n#ifndef GL_EXT_convolution\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\n#endif\n\n#ifndef GL_SGI_color_matrix\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\n\n#ifndef GL_SGI_color_table\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\n#endif\n\n#ifndef GL_SGIS_pixel_texture\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\n#endif\n\n#ifndef GL_SGIX_pixel_texture\n#define GL_PIXEL_TEX_GEN_SGIX             0x8139\n#define GL_PIXEL_TEX_GEN_MODE_SGIX        0x832B\n#endif\n\n#ifndef GL_SGIS_texture4D\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\n#endif\n\n#ifndef GL_SGI_texture_color_table\n#define GL_TEXTURE_COLOR_TABLE_SGI        0x80BC\n#define GL_PROXY_TEXTURE_COLOR_TABLE_SGI  0x80BD\n#endif\n\n#ifndef GL_EXT_cmyka\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\n\n#ifndef GL_EXT_texture_object\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\n#endif\n\n#ifndef GL_SGIS_detail_texture\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\n#endif\n\n#ifndef GL_SGIS_sharpen_texture\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\n#endif\n\n#ifndef GL_EXT_packed_pixels\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\n\n#ifndef GL_SGIS_texture_lod\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\n\n#ifndef GL_SGIS_multisample\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\n#endif\n\n#ifndef GL_EXT_rescale_normal\n#define GL_RESCALE_NORMAL_EXT             0x803A\n#endif\n\n#ifndef GL_EXT_vertex_array\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\n#endif\n\n#ifndef GL_EXT_misc_attribute\n#endif\n\n#ifndef GL_SGIS_generate_mipmap\n#define GL_GENERATE_MIPMAP_SGIS           0x8191\n#define GL_GENERATE_MIPMAP_HINT_SGIS      0x8192\n#endif\n\n#ifndef GL_SGIX_clipmap\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\n\n#ifndef GL_SGIX_shadow\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\n\n#ifndef GL_SGIS_texture_edge_clamp\n#define GL_CLAMP_TO_EDGE_SGIS             0x812F\n#endif\n\n#ifndef GL_SGIS_texture_border_clamp\n#define GL_CLAMP_TO_BORDER_SGIS           0x812D\n#endif\n\n#ifndef GL_EXT_blend_minmax\n#define GL_FUNC_ADD_EXT                   0x8006\n#define GL_MIN_EXT                        0x8007\n#define GL_MAX_EXT                        0x8008\n#define GL_BLEND_EQUATION_EXT             0x8009\n#endif\n\n#ifndef GL_EXT_blend_subtract\n#define GL_FUNC_SUBTRACT_EXT              0x800A\n#define GL_FUNC_REVERSE_SUBTRACT_EXT      0x800B\n#endif\n\n#ifndef GL_EXT_blend_logic_op\n#endif\n\n#ifndef GL_SGIX_interlace\n#define GL_INTERLACE_SGIX                 0x8094\n#endif\n\n#ifndef GL_SGIX_pixel_tiles\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\n\n#ifndef GL_SGIS_texture_select\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\n\n#ifndef GL_SGIX_sprite\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\n#endif\n\n#ifndef GL_SGIX_texture_multi_buffer\n#define GL_TEXTURE_MULTI_BUFFER_HINT_SGIX 0x812E\n#endif\n\n#ifndef GL_EXT_point_parameters\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\n#endif\n\n#ifndef GL_SGIS_point_parameters\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\n#endif\n\n#ifndef GL_SGIX_instruments\n#define GL_INSTRUMENT_BUFFER_POINTER_SGIX 0x8180\n#define GL_INSTRUMENT_MEASUREMENTS_SGIX   0x8181\n#endif\n\n#ifndef GL_SGIX_texture_scale_bias\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\n\n#ifndef GL_SGIX_framezoom\n#define GL_FRAMEZOOM_SGIX                 0x818B\n#define GL_FRAMEZOOM_FACTOR_SGIX          0x818C\n#define GL_MAX_FRAMEZOOM_FACTOR_SGIX      0x818D\n#endif\n\n#ifndef GL_SGIX_tag_sample_buffer\n#endif\n\n#ifndef GL_FfdMaskSGIX\n#define GL_TEXTURE_DEFORMATION_BIT_SGIX   0x00000001\n#define GL_GEOMETRY_DEFORMATION_BIT_SGIX  0x00000002\n#endif\n\n#ifndef GL_SGIX_polynomial_ffd\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\n#endif\n\n#ifndef GL_SGIX_reference_plane\n#define GL_REFERENCE_PLANE_SGIX           0x817D\n#define GL_REFERENCE_PLANE_EQUATION_SGIX  0x817E\n#endif\n\n#ifndef GL_SGIX_flush_raster\n#endif\n\n#ifndef GL_SGIX_depth_texture\n#define GL_DEPTH_COMPONENT16_SGIX         0x81A5\n#define GL_DEPTH_COMPONENT24_SGIX         0x81A6\n#define GL_DEPTH_COMPONENT32_SGIX         0x81A7\n#endif\n\n#ifndef GL_SGIS_fog_function\n#define GL_FOG_FUNC_SGIS                  0x812A\n#define GL_FOG_FUNC_POINTS_SGIS           0x812B\n#define GL_MAX_FOG_FUNC_POINTS_SGIS       0x812C\n#endif\n\n#ifndef GL_SGIX_fog_offset\n#define GL_FOG_OFFSET_SGIX                0x8198\n#define GL_FOG_OFFSET_VALUE_SGIX          0x8199\n#endif\n\n#ifndef GL_HP_image_transform\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\n#endif\n\n#ifndef GL_HP_convolution_border_modes\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\n\n#ifndef GL_INGR_palette_buffer\n#endif\n\n#ifndef GL_SGIX_texture_add_env\n#define GL_TEXTURE_ENV_BIAS_SGIX          0x80BE\n#endif\n\n#ifndef GL_EXT_color_subtable\n#endif\n\n#ifndef GL_PGI_vertex_hints\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\n\n#ifndef GL_PGI_misc_hints\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\n#endif\n\n#ifndef GL_EXT_paletted_texture\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\n#endif\n\n#ifndef GL_EXT_clip_volume_hint\n#define GL_CLIP_VOLUME_CLIPPING_HINT_EXT  0x80F0\n#endif\n\n#ifndef GL_SGIX_list_priority\n#define GL_LIST_PRIORITY_SGIX             0x8182\n#endif\n\n#ifndef GL_SGIX_ir_instrument1\n#define GL_IR_INSTRUMENT1_SGIX            0x817F\n#endif\n\n#ifndef GL_SGIX_calligraphic_fragment\n#define GL_CALLIGRAPHIC_FRAGMENT_SGIX     0x8183\n#endif\n\n#ifndef GL_SGIX_texture_lod_bias\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\n\n#ifndef GL_SGIX_shadow_ambient\n#define GL_SHADOW_AMBIENT_SGIX            0x80BF\n#endif\n\n#ifndef GL_EXT_index_texture\n#endif\n\n#ifndef GL_EXT_index_material\n#define GL_INDEX_MATERIAL_EXT             0x81B8\n#define GL_INDEX_MATERIAL_PARAMETER_EXT   0x81B9\n#define GL_INDEX_MATERIAL_FACE_EXT        0x81BA\n#endif\n\n#ifndef GL_EXT_index_func\n#define GL_INDEX_TEST_EXT                 0x81B5\n#define GL_INDEX_TEST_FUNC_EXT            0x81B6\n#define GL_INDEX_TEST_REF_EXT             0x81B7\n#endif\n\n#ifndef GL_EXT_index_array_formats\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\n\n#ifndef GL_EXT_compiled_vertex_array\n#define GL_ARRAY_ELEMENT_LOCK_FIRST_EXT   0x81A8\n#define GL_ARRAY_ELEMENT_LOCK_COUNT_EXT   0x81A9\n#endif\n\n#ifndef GL_EXT_cull_vertex\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\n#endif\n\n#ifndef GL_SGIX_ycrcb\n#define GL_YCRCB_422_SGIX                 0x81BB\n#define GL_YCRCB_444_SGIX                 0x81BC\n#endif\n\n#ifndef GL_SGIX_fragment_lighting\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\n#endif\n\n#ifndef GL_IBM_rasterpos_clip\n#define GL_RASTER_POSITION_UNCLIPPED_IBM  0x19262\n#endif\n\n#ifndef GL_HP_texture_lighting\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\n\n#ifndef GL_EXT_draw_range_elements\n#define GL_MAX_ELEMENTS_VERTICES_EXT      0x80E8\n#define GL_MAX_ELEMENTS_INDICES_EXT       0x80E9\n#endif\n\n#ifndef GL_WIN_phong_shading\n#define GL_PHONG_WIN                      0x80EA\n#define GL_PHONG_HINT_WIN                 0x80EB\n#endif\n\n#ifndef GL_WIN_specular_fog\n#define GL_FOG_SPECULAR_TEXTURE_WIN       0x80EC\n#endif\n\n#ifndef GL_EXT_light_texture\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\n/* reuse GL_FRAGMENT_DEPTH_EXT */\n#endif\n\n#ifndef GL_SGIX_blend_alpha_minmax\n#define GL_ALPHA_MIN_SGIX                 0x8320\n#define GL_ALPHA_MAX_SGIX                 0x8321\n#endif\n\n#ifndef GL_SGIX_impact_pixel_texture\n#define GL_PIXEL_TEX_GEN_Q_CEILING_SGIX   0x8184\n#define GL_PIXEL_TEX_GEN_Q_ROUND_SGIX     0x8185\n#define GL_PIXEL_TEX_GEN_Q_FLOOR_SGIX     0x8186\n#define GL_PIXEL_TEX_GEN_ALPHA_REPLACE_SGIX 0x8187\n#define GL_PIXEL_TEX_GEN_ALPHA_NO_REPLACE_SGIX 0x8188\n#define GL_PIXEL_TEX_GEN_ALPHA_LS_SGIX    0x8189\n#define GL_PIXEL_TEX_GEN_ALPHA_MS_SGIX    0x818A\n#endif\n\n#ifndef GL_EXT_bgra\n#define GL_BGR_EXT                        0x80E0\n#define GL_BGRA_EXT                       0x80E1\n#endif\n\n#ifndef GL_SGIX_async\n#define GL_ASYNC_MARKER_SGIX              0x8329\n#endif\n\n#ifndef GL_SGIX_async_pixel\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\n\n#ifndef GL_SGIX_async_histogram\n#define GL_ASYNC_HISTOGRAM_SGIX           0x832C\n#define GL_MAX_ASYNC_HISTOGRAM_SGIX       0x832D\n#endif\n\n#ifndef GL_INTEL_texture_scissor\n#endif\n\n#ifndef GL_INTEL_parallel_arrays\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\n#endif\n\n#ifndef GL_HP_occlusion_test\n#define GL_OCCLUSION_TEST_HP              0x8165\n#define GL_OCCLUSION_TEST_RESULT_HP       0x8166\n#endif\n\n#ifndef GL_EXT_pixel_transform\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\n#endif\n\n#ifndef GL_EXT_pixel_transform_color_table\n#endif\n\n#ifndef GL_EXT_shared_texture_palette\n#define GL_SHARED_TEXTURE_PALETTE_EXT     0x81FB\n#endif\n\n#ifndef GL_EXT_separate_specular_color\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\n\n#ifndef GL_EXT_secondary_color\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\n#endif\n\n#ifndef GL_EXT_texture_perturb_normal\n#define GL_PERTURB_EXT                    0x85AE\n#define GL_TEXTURE_NORMAL_EXT             0x85AF\n#endif\n\n#ifndef GL_EXT_multi_draw_arrays\n#endif\n\n#ifndef GL_EXT_fog_coord\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\n#endif\n\n#ifndef GL_REND_screen_coordinates\n#define GL_SCREEN_COORDINATES_REND        0x8490\n#define GL_INVERTED_SCREEN_W_REND         0x8491\n#endif\n\n#ifndef GL_EXT_coordinate_frame\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\n#endif\n\n#ifndef GL_EXT_texture_env_combine\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\n\n#ifndef GL_APPLE_specular_vector\n#define GL_LIGHT_MODEL_SPECULAR_VECTOR_APPLE 0x85B0\n#endif\n\n#ifndef GL_APPLE_transform_hint\n#define GL_TRANSFORM_HINT_APPLE           0x85B1\n#endif\n\n#ifndef GL_SGIX_fog_scale\n#define GL_FOG_SCALE_SGIX                 0x81FC\n#define GL_FOG_SCALE_VALUE_SGIX           0x81FD\n#endif\n\n#ifndef GL_SUNX_constant_data\n#define GL_UNPACK_CONSTANT_DATA_SUNX      0x81D5\n#define GL_TEXTURE_CONSTANT_DATA_SUNX     0x81D6\n#endif\n\n#ifndef GL_SUN_global_alpha\n#define GL_GLOBAL_ALPHA_SUN               0x81D9\n#define GL_GLOBAL_ALPHA_FACTOR_SUN        0x81DA\n#endif\n\n#ifndef GL_SUN_triangle_list\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\n#endif\n\n#ifndef GL_SUN_vertex\n#endif\n\n#ifndef GL_EXT_blend_func_separate\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\n#endif\n\n#ifndef GL_INGR_color_clamp\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\n\n#ifndef GL_INGR_interlace_read\n#define GL_INTERLACE_READ_INGR            0x8568\n#endif\n\n#ifndef GL_EXT_stencil_wrap\n#define GL_INCR_WRAP_EXT                  0x8507\n#define GL_DECR_WRAP_EXT                  0x8508\n#endif\n\n#ifndef GL_EXT_422_pixels\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\n\n#ifndef GL_NV_texgen_reflection\n#define GL_NORMAL_MAP_NV                  0x8511\n#define GL_REFLECTION_MAP_NV              0x8512\n#endif\n\n#ifndef GL_EXT_texture_cube_map\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\n\n#ifndef GL_SUN_convolution_border_modes\n#define GL_WRAP_BORDER_SUN                0x81D4\n#endif\n\n#ifndef GL_EXT_texture_env_add\n#endif\n\n#ifndef GL_EXT_texture_lod_bias\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\n\n#ifndef GL_EXT_texture_filter_anisotropic\n#define GL_TEXTURE_MAX_ANISOTROPY_EXT     0x84FE\n#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF\n#endif\n\n#ifndef GL_EXT_vertex_weighting\n#define GL_MODELVIEW0_STACK_DEPTH_EXT     GL_MODELVIEW_STACK_DEPTH\n#define GL_MODELVIEW1_STACK_DEPTH_EXT     0x8502\n#define GL_MODELVIEW0_MATRIX_EXT          GL_MODELVIEW_MATRIX\n#define GL_MODELVIEW1_MATRIX_EXT          0x8506\n#define GL_VERTEX_WEIGHTING_EXT           0x8509\n#define GL_MODELVIEW0_EXT                 GL_MODELVIEW\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\n#endif\n\n#ifndef GL_NV_light_max_exponent\n#define GL_MAX_SHININESS_NV               0x8504\n#define GL_MAX_SPOT_EXPONENT_NV           0x8505\n#endif\n\n#ifndef GL_NV_vertex_array_range\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\n#endif\n\n#ifndef GL_NV_register_combiners\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_PRIMARY_COLOR_NV               0x852C\n#define GL_SECONDARY_COLOR_NV             0x852D\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\n/* reuse GL_TEXTURE0_ARB */\n/* reuse GL_TEXTURE1_ARB */\n/* reuse GL_ZERO */\n/* reuse GL_NONE */\n/* reuse GL_FOG */\n#endif\n\n#ifndef GL_NV_fog_distance\n#define GL_FOG_DISTANCE_MODE_NV           0x855A\n#define GL_EYE_RADIAL_NV                  0x855B\n#define GL_EYE_PLANE_ABSOLUTE_NV          0x855C\n/* reuse GL_EYE_PLANE */\n#endif\n\n#ifndef GL_NV_texgen_emboss\n#define GL_EMBOSS_LIGHT_NV                0x855D\n#define GL_EMBOSS_CONSTANT_NV             0x855E\n#define GL_EMBOSS_MAP_NV                  0x855F\n#endif\n\n#ifndef GL_NV_blend_square\n#endif\n\n#ifndef GL_NV_texture_env_combine4\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\n\n#ifndef GL_MESA_resize_buffers\n#endif\n\n#ifndef GL_MESA_window_pos\n#endif\n\n#ifndef GL_EXT_texture_compression_s3tc\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\n\n#ifndef GL_IBM_cull_vertex\n#define GL_CULL_VERTEX_IBM                103050\n#endif\n\n#ifndef GL_IBM_multimode_draw_arrays\n#endif\n\n#ifndef GL_IBM_vertex_array_lists\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\n#endif\n\n#ifndef GL_SGIX_subsample\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\n\n#ifndef GL_SGIX_ycrcb_subsample\n#endif\n\n#ifndef GL_SGIX_ycrcba\n#define GL_YCRCB_SGIX                     0x8318\n#define GL_YCRCBA_SGIX                    0x8319\n#endif\n\n#ifndef GL_SGI_depth_pass_instrument\n#define GL_DEPTH_PASS_INSTRUMENT_SGIX     0x8310\n#define GL_DEPTH_PASS_INSTRUMENT_COUNTERS_SGIX 0x8311\n#define GL_DEPTH_PASS_INSTRUMENT_MAX_SGIX 0x8312\n#endif\n\n#ifndef GL_3DFX_texture_compression_FXT1\n#define GL_COMPRESSED_RGB_FXT1_3DFX       0x86B0\n#define GL_COMPRESSED_RGBA_FXT1_3DFX      0x86B1\n#endif\n\n#ifndef GL_3DFX_multisample\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\n\n#ifndef GL_3DFX_tbuffer\n#endif\n\n#ifndef GL_EXT_multisample\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\n#endif\n\n#ifndef GL_SGIX_vertex_preclip\n#define GL_VERTEX_PRECLIP_SGIX            0x83EE\n#define GL_VERTEX_PRECLIP_HINT_SGIX       0x83EF\n#endif\n\n#ifndef GL_SGIX_convolution_accuracy\n#define GL_CONVOLUTION_HINT_SGIX          0x8316\n#endif\n\n#ifndef GL_SGIX_resample\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\n\n#ifndef GL_SGIS_point_line_texgen\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\n\n#ifndef GL_SGIS_texture_color_mask\n#define GL_TEXTURE_COLOR_WRITEMASK_SGIS   0x81EF\n#endif\n\n#ifndef GL_EXT_texture_env_dot3\n#define GL_DOT3_RGB_EXT                   0x8740\n#define GL_DOT3_RGBA_EXT                  0x8741\n#endif\n\n#ifndef GL_ATI_texture_mirror_once\n#define GL_MIRROR_CLAMP_ATI               0x8742\n#define GL_MIRROR_CLAMP_TO_EDGE_ATI       0x8743\n#endif\n\n#ifndef GL_NV_fence\n#define GL_ALL_COMPLETED_NV               0x84F2\n#define GL_FENCE_STATUS_NV                0x84F3\n#define GL_FENCE_CONDITION_NV             0x84F4\n#endif\n\n#ifndef GL_IBM_texture_mirrored_repeat\n#define GL_MIRRORED_REPEAT_IBM            0x8370\n#endif\n\n#ifndef GL_NV_evaluators\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\n#endif\n\n#ifndef GL_NV_packed_depth_stencil\n#define GL_DEPTH_STENCIL_NV               0x84F9\n#define GL_UNSIGNED_INT_24_8_NV           0x84FA\n#endif\n\n#ifndef GL_NV_register_combiners2\n#define GL_PER_STAGE_CONSTANTS_NV         0x8535\n#endif\n\n#ifndef GL_NV_texture_compression_vtc\n#endif\n\n#ifndef GL_NV_texture_rectangle\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\n\n#ifndef GL_NV_texture_shader\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    GL_OFFSET_TEXTURE_MATRIX_NV\n#define GL_OFFSET_TEXTURE_2D_SCALE_NV     GL_OFFSET_TEXTURE_SCALE_NV\n#define GL_OFFSET_TEXTURE_2D_BIAS_NV      GL_OFFSET_TEXTURE_BIAS_NV\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\n\n#ifndef GL_NV_texture_shader2\n#define GL_DOT_PRODUCT_TEXTURE_3D_NV      0x86EF\n#endif\n\n#ifndef GL_NV_vertex_array_range2\n#define GL_VERTEX_ARRAY_RANGE_WITHOUT_FLUSH_NV 0x8533\n#endif\n\n#ifndef GL_NV_vertex_program\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\n#endif\n\n#ifndef GL_SGIX_texture_coordinate_clamp\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\n\n#ifndef GL_SGIX_scalebias_hint\n#define GL_SCALEBIAS_HINT_SGIX            0x8322\n#endif\n\n#ifndef GL_OML_interlace\n#define GL_INTERLACE_OML                  0x8980\n#define GL_INTERLACE_READ_OML             0x8981\n#endif\n\n#ifndef GL_OML_subsample\n#define GL_FORMAT_SUBSAMPLE_24_24_OML     0x8982\n#define GL_FORMAT_SUBSAMPLE_244_244_OML   0x8983\n#endif\n\n#ifndef GL_OML_resample\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\n\n#ifndef GL_NV_copy_depth_to_color\n#define GL_DEPTH_STENCIL_TO_RGBA_NV       0x886E\n#define GL_DEPTH_STENCIL_TO_BGRA_NV       0x886F\n#endif\n\n#ifndef GL_ATI_envmap_bumpmap\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\n#endif\n\n#ifndef GL_ATI_fragment_shader\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\n#endif\n\n#ifndef GL_ATI_pn_triangles\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\n#endif\n\n#ifndef GL_ATI_vertex_array_object\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\n#endif\n\n#ifndef GL_EXT_vertex_shader\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\n#endif\n\n#ifndef GL_ATI_vertex_streams\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\n#endif\n\n#ifndef GL_ATI_element_array\n#define GL_ELEMENT_ARRAY_ATI              0x8768\n#define GL_ELEMENT_ARRAY_TYPE_ATI         0x8769\n#define GL_ELEMENT_ARRAY_POINTER_ATI      0x876A\n#endif\n\n#ifndef GL_SUN_mesh_array\n#define GL_QUAD_MESH_SUN                  0x8614\n#define GL_TRIANGLE_MESH_SUN              0x8615\n#endif\n\n#ifndef GL_SUN_slice_accum\n#define GL_SLICE_ACCUM_SUN                0x85CC\n#endif\n\n#ifndef GL_NV_multisample_filter_hint\n#define GL_MULTISAMPLE_FILTER_HINT_NV     0x8534\n#endif\n\n#ifndef GL_NV_depth_clamp\n#define GL_DEPTH_CLAMP_NV                 0x864F\n#endif\n\n#ifndef GL_NV_occlusion_query\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\n#endif\n\n#ifndef GL_NV_point_sprite\n#define GL_POINT_SPRITE_NV                0x8861\n#define GL_COORD_REPLACE_NV               0x8862\n#define GL_POINT_SPRITE_R_MODE_NV         0x8863\n#endif\n\n#ifndef GL_NV_texture_shader3\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\n\n#ifndef GL_NV_vertex_program1_1\n#endif\n\n#ifndef GL_EXT_shadow_funcs\n#endif\n\n#ifndef GL_EXT_stencil_two_side\n#define GL_STENCIL_TEST_TWO_SIDE_EXT      0x8910\n#define GL_ACTIVE_STENCIL_FACE_EXT        0x8911\n#endif\n\n#ifndef GL_ATI_text_fragment_shader\n#define GL_TEXT_FRAGMENT_SHADER_ATI       0x8200\n#endif\n\n#ifndef GL_APPLE_client_storage\n#define GL_UNPACK_CLIENT_STORAGE_APPLE    0x85B2\n#endif\n\n#ifndef GL_APPLE_element_array\n#define GL_ELEMENT_ARRAY_APPLE            0x8768\n#define GL_ELEMENT_ARRAY_TYPE_APPLE       0x8769\n#define GL_ELEMENT_ARRAY_POINTER_APPLE    0x876A\n#endif\n\n#ifndef GL_APPLE_fence\n#define GL_DRAW_PIXELS_APPLE              0x8A0A\n#define GL_FENCE_APPLE                    0x8A0B\n#endif\n\n#ifndef GL_APPLE_vertex_array_object\n#define GL_VERTEX_ARRAY_BINDING_APPLE     0x85B5\n#endif\n\n#ifndef GL_APPLE_vertex_array_range\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_CACHED_APPLE           0x85BE\n#define GL_STORAGE_SHARED_APPLE           0x85BF\n#endif\n\n#ifndef GL_APPLE_ycbcr_422\n#define GL_YCBCR_422_APPLE                0x85B9\n#define GL_UNSIGNED_SHORT_8_8_APPLE       0x85BA\n#define GL_UNSIGNED_SHORT_8_8_REV_APPLE   0x85BB\n#endif\n\n#ifndef GL_S3_s3tc\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#endif\n\n#ifndef GL_ATI_draw_buffers\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\n#endif\n\n#ifndef GL_ATI_pixel_format_float\n#define GL_TYPE_RGBA_FLOAT_ATI            0x8820\n#define GL_COLOR_CLEAR_UNCLAMPED_VALUE_ATI 0x8835\n#endif\n\n#ifndef GL_ATI_texture_env_combine3\n#define GL_MODULATE_ADD_ATI               0x8744\n#define GL_MODULATE_SIGNED_ADD_ATI        0x8745\n#define GL_MODULATE_SUBTRACT_ATI          0x8746\n#endif\n\n#ifndef GL_ATI_texture_float\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\n\n#ifndef GL_NV_float_buffer\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\n\n#ifndef GL_NV_fragment_program\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\n#endif\n\n#ifndef GL_NV_half_float\n#define GL_HALF_FLOAT_NV                  0x140B\n#endif\n\n#ifndef GL_NV_pixel_data_range\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\n#endif\n\n#ifndef GL_NV_primitive_restart\n#define GL_PRIMITIVE_RESTART_NV           0x8558\n#define GL_PRIMITIVE_RESTART_INDEX_NV     0x8559\n#endif\n\n#ifndef GL_NV_texture_expand_normal\n#define GL_TEXTURE_UNSIGNED_REMAP_MODE_NV 0x888F\n#endif\n\n#ifndef GL_NV_vertex_program2\n#endif\n\n#ifndef GL_ATI_map_object_buffer\n#endif\n\n#ifndef GL_ATI_separate_stencil\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\n#endif\n\n#ifndef GL_ATI_vertex_attrib_array_object\n#endif\n\n#ifndef GL_OES_read_format\n#define GL_IMPLEMENTATION_COLOR_READ_TYPE_OES 0x8B9A\n#define GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES 0x8B9B\n#endif\n\n#ifndef GL_EXT_depth_bounds_test\n#define GL_DEPTH_BOUNDS_TEST_EXT          0x8890\n#define GL_DEPTH_BOUNDS_EXT               0x8891\n#endif\n\n#ifndef GL_EXT_texture_mirror_clamp\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\n\n#ifndef GL_EXT_blend_equation_separate\n#define GL_BLEND_EQUATION_RGB_EXT         GL_BLEND_EQUATION\n#define GL_BLEND_EQUATION_ALPHA_EXT       0x883D\n#endif\n\n#ifndef GL_MESA_pack_invert\n#define GL_PACK_INVERT_MESA               0x8758\n#endif\n\n#ifndef GL_MESA_ycbcr_texture\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\n\n#ifndef GL_EXT_pixel_buffer_object\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\n\n#ifndef GL_NV_fragment_program_option\n#endif\n\n#ifndef GL_NV_fragment_program2\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\n\n#ifndef GL_NV_vertex_program2_option\n/* reuse GL_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV */\n/* reuse GL_MAX_PROGRAM_CALL_DEPTH_NV */\n#endif\n\n#ifndef GL_NV_vertex_program3\n/* reuse GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB */\n#endif\n\n#ifndef GL_EXT_framebuffer_object\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_DUPLICATE_ATTACHMENT_EXT 0x8CD8\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\n#endif\n\n#ifndef GL_GREMEDY_string_marker\n#endif\n\n\n/*************************************************************/\n\n#include <stddef.h>\n#ifndef GL_VERSION_2_0\n/* GL type for program/shader text */\ntypedef char GLchar;\t\t\t/* native character */\n#endif\n\n#ifndef GL_VERSION_1_5\n/* GL types for handling large vertex buffer objects */\ntypedef ptrdiff_t GLintptr;\ntypedef ptrdiff_t GLsizeiptr;\n#endif\n\n#ifndef GL_ARB_vertex_buffer_object\n/* GL types for handling large vertex buffer objects */\ntypedef ptrdiff_t GLintptrARB;\ntypedef ptrdiff_t GLsizeiptrARB;\n#endif\n\n#ifndef GL_ARB_shader_objects\n/* GL types for handling shader object handles and program/shader text */\ntypedef char GLcharARB;\t\t/* native character */\ntypedef unsigned int GLhandleARB;\t/* shader object handle */\n#endif\n\n/* GL types for \"half\" precision (s10e5) float data in host memory */\n#ifndef GL_ARB_half_float_pixel\ntypedef unsigned short GLhalfARB;\n#endif\n\n#ifndef GL_NV_half_float\ntypedef unsigned short GLhalfNV;\n#endif\n\n#ifndef GL_VERSION_1_2\n#define GL_VERSION_1_2 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBlendColor (GLclampf, GLclampf, GLclampf, GLclampf);\nGLAPI void APIENTRY glBlendEquation (GLenum);\nGLAPI void APIENTRY glDrawRangeElements (GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *);\nGLAPI void APIENTRY glColorTable (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);\nGLAPI void APIENTRY glColorTableParameterfv (GLenum, GLenum, const GLfloat *);\nGLAPI void APIENTRY glColorTableParameteriv (GLenum, GLenum, const GLint *);\nGLAPI void APIENTRY glCopyColorTable (GLenum, GLenum, GLint, GLint, GLsizei);\nGLAPI void APIENTRY glGetColorTable (GLenum, GLenum, GLenum, GLvoid *);\nGLAPI void APIENTRY glGetColorTableParameterfv (GLenum, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetColorTableParameteriv (GLenum, GLenum, GLint *);\nGLAPI void APIENTRY glColorSubTable (GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);\nGLAPI void APIENTRY glCopyColorSubTable (GLenum, GLsizei, GLint, GLint, GLsizei);\nGLAPI void APIENTRY glConvolutionFilter1D (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);\nGLAPI void APIENTRY glConvolutionFilter2D (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);\nGLAPI void APIENTRY glConvolutionParameterf (GLenum, GLenum, GLfloat);\nGLAPI void APIENTRY glConvolutionParameterfv (GLenum, GLenum, const GLfloat *);\nGLAPI void APIENTRY glConvolutionParameteri (GLenum, GLenum, GLint);\nGLAPI void APIENTRY glConvolutionParameteriv (GLenum, GLenum, const GLint *);\nGLAPI void APIENTRY glCopyConvolutionFilter1D (GLenum, GLenum, GLint, GLint, GLsizei);\nGLAPI void APIENTRY glCopyConvolutionFilter2D (GLenum, GLenum, GLint, GLint, GLsizei, GLsizei);\nGLAPI void APIENTRY glGetConvolutionFilter (GLenum, GLenum, GLenum, GLvoid *);\nGLAPI void APIENTRY glGetConvolutionParameterfv (GLenum, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetConvolutionParameteriv (GLenum, GLenum, GLint *);\nGLAPI void APIENTRY glGetSeparableFilter (GLenum, GLenum, GLenum, GLvoid *, GLvoid *, GLvoid *);\nGLAPI void APIENTRY glSeparableFilter2D (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *, const GLvoid *);\nGLAPI void APIENTRY glGetHistogram (GLenum, GLboolean, GLenum, GLenum, GLvoid *);\nGLAPI void APIENTRY glGetHistogramParameterfv (GLenum, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetHistogramParameteriv (GLenum, GLenum, GLint *);\nGLAPI void APIENTRY glGetMinmax (GLenum, GLboolean, GLenum, GLenum, GLvoid *);\nGLAPI void APIENTRY glGetMinmaxParameterfv (GLenum, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetMinmaxParameteriv (GLenum, GLenum, GLint *);\nGLAPI void APIENTRY glHistogram (GLenum, GLsizei, GLenum, GLboolean);\nGLAPI void APIENTRY glMinmax (GLenum, GLenum, GLboolean);\nGLAPI void APIENTRY glResetHistogram (GLenum);\nGLAPI void APIENTRY glResetMinmax (GLenum);\nGLAPI void APIENTRY glTexImage3D (GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);\nGLAPI void APIENTRY glTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);\nGLAPI void APIENTRY glCopyTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLBLENDCOLORPROC) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);\ntypedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode);\ntypedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices);\ntypedef void (APIENTRYP PFNGLCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *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, GLvoid *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 GLvoid *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 GLvoid *image);\ntypedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *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, GLvoid *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, GLvoid *row, GLvoid *column, GLvoid *span);\ntypedef void (APIENTRYP PFNGLSEPARABLEFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column);\ntypedef void (APIENTRYP PFNGLGETHISTOGRAMPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *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, GLvoid *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);\ntypedef void (APIENTRYP PFNGLTEXIMAGE3DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *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 GLvoid *pixels);\ntypedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);\n#endif\n\n#ifndef GL_VERSION_1_3\n#define GL_VERSION_1_3 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glActiveTexture (GLenum);\nGLAPI void APIENTRY glClientActiveTexture (GLenum);\nGLAPI void APIENTRY glMultiTexCoord1d (GLenum, GLdouble);\nGLAPI void APIENTRY glMultiTexCoord1dv (GLenum, const GLdouble *);\nGLAPI void APIENTRY glMultiTexCoord1f (GLenum, GLfloat);\nGLAPI void APIENTRY glMultiTexCoord1fv (GLenum, const GLfloat *);\nGLAPI void APIENTRY glMultiTexCoord1i (GLenum, GLint);\nGLAPI void APIENTRY glMultiTexCoord1iv (GLenum, const GLint *);\nGLAPI void APIENTRY glMultiTexCoord1s (GLenum, GLshort);\nGLAPI void APIENTRY glMultiTexCoord1sv (GLenum, const GLshort *);\nGLAPI void APIENTRY glMultiTexCoord2d (GLenum, GLdouble, GLdouble);\nGLAPI void APIENTRY glMultiTexCoord2dv (GLenum, const GLdouble *);\nGLAPI void APIENTRY glMultiTexCoord2f (GLenum, GLfloat, GLfloat);\nGLAPI void APIENTRY glMultiTexCoord2fv (GLenum, const GLfloat *);\nGLAPI void APIENTRY glMultiTexCoord2i (GLenum, GLint, GLint);\nGLAPI void APIENTRY glMultiTexCoord2iv (GLenum, const GLint *);\nGLAPI void APIENTRY glMultiTexCoord2s (GLenum, GLshort, GLshort);\nGLAPI void APIENTRY glMultiTexCoord2sv (GLenum, const GLshort *);\nGLAPI void APIENTRY glMultiTexCoord3d (GLenum, GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glMultiTexCoord3dv (GLenum, const GLdouble *);\nGLAPI void APIENTRY glMultiTexCoord3f (GLenum, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glMultiTexCoord3fv (GLenum, const GLfloat *);\nGLAPI void APIENTRY glMultiTexCoord3i (GLenum, GLint, GLint, GLint);\nGLAPI void APIENTRY glMultiTexCoord3iv (GLenum, const GLint *);\nGLAPI void APIENTRY glMultiTexCoord3s (GLenum, GLshort, GLshort, GLshort);\nGLAPI void APIENTRY glMultiTexCoord3sv (GLenum, const GLshort *);\nGLAPI void APIENTRY glMultiTexCoord4d (GLenum, GLdouble, GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glMultiTexCoord4dv (GLenum, const GLdouble *);\nGLAPI void APIENTRY glMultiTexCoord4f (GLenum, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glMultiTexCoord4fv (GLenum, const GLfloat *);\nGLAPI void APIENTRY glMultiTexCoord4i (GLenum, GLint, GLint, GLint, GLint);\nGLAPI void APIENTRY glMultiTexCoord4iv (GLenum, const GLint *);\nGLAPI void APIENTRY glMultiTexCoord4s (GLenum, GLshort, GLshort, GLshort, GLshort);\nGLAPI void APIENTRY glMultiTexCoord4sv (GLenum, const GLshort *);\nGLAPI void APIENTRY glLoadTransposeMatrixf (const GLfloat *);\nGLAPI void APIENTRY glLoadTransposeMatrixd (const GLdouble *);\nGLAPI void APIENTRY glMultTransposeMatrixf (const GLfloat *);\nGLAPI void APIENTRY glMultTransposeMatrixd (const GLdouble *);\nGLAPI void APIENTRY glSampleCoverage (GLclampf, GLboolean);\nGLAPI void APIENTRY glCompressedTexImage3D (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glCompressedTexImage2D (GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glCompressedTexImage1D (GLenum, GLint, GLenum, GLsizei, GLint, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glCompressedTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glCompressedTexSubImage2D (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glCompressedTexSubImage1D (GLenum, GLint, GLint, GLsizei, GLenum, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glGetCompressedTexImage (GLenum, GLint, GLvoid *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture);\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);\ntypedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC) (GLclampf value, GLboolean invert);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *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 GLvoid *data);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data);\ntypedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC) (GLenum target, GLint level, GLvoid *img);\n#endif\n\n#ifndef GL_VERSION_1_4\n#define GL_VERSION_1_4 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBlendFuncSeparate (GLenum, GLenum, GLenum, GLenum);\nGLAPI void APIENTRY glFogCoordf (GLfloat);\nGLAPI void APIENTRY glFogCoordfv (const GLfloat *);\nGLAPI void APIENTRY glFogCoordd (GLdouble);\nGLAPI void APIENTRY glFogCoorddv (const GLdouble *);\nGLAPI void APIENTRY glFogCoordPointer (GLenum, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glMultiDrawArrays (GLenum, GLint *, GLsizei *, GLsizei);\nGLAPI void APIENTRY glMultiDrawElements (GLenum, const GLsizei *, GLenum, const GLvoid* *, GLsizei);\nGLAPI void APIENTRY glPointParameterf (GLenum, GLfloat);\nGLAPI void APIENTRY glPointParameterfv (GLenum, const GLfloat *);\nGLAPI void APIENTRY glPointParameteri (GLenum, GLint);\nGLAPI void APIENTRY glPointParameteriv (GLenum, const GLint *);\nGLAPI void APIENTRY glSecondaryColor3b (GLbyte, GLbyte, GLbyte);\nGLAPI void APIENTRY glSecondaryColor3bv (const GLbyte *);\nGLAPI void APIENTRY glSecondaryColor3d (GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glSecondaryColor3dv (const GLdouble *);\nGLAPI void APIENTRY glSecondaryColor3f (GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glSecondaryColor3fv (const GLfloat *);\nGLAPI void APIENTRY glSecondaryColor3i (GLint, GLint, GLint);\nGLAPI void APIENTRY glSecondaryColor3iv (const GLint *);\nGLAPI void APIENTRY glSecondaryColor3s (GLshort, GLshort, GLshort);\nGLAPI void APIENTRY glSecondaryColor3sv (const GLshort *);\nGLAPI void APIENTRY glSecondaryColor3ub (GLubyte, GLubyte, GLubyte);\nGLAPI void APIENTRY glSecondaryColor3ubv (const GLubyte *);\nGLAPI void APIENTRY glSecondaryColor3ui (GLuint, GLuint, GLuint);\nGLAPI void APIENTRY glSecondaryColor3uiv (const GLuint *);\nGLAPI void APIENTRY glSecondaryColor3us (GLushort, GLushort, GLushort);\nGLAPI void APIENTRY glSecondaryColor3usv (const GLushort *);\nGLAPI void APIENTRY glSecondaryColorPointer (GLint, GLenum, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glWindowPos2d (GLdouble, GLdouble);\nGLAPI void APIENTRY glWindowPos2dv (const GLdouble *);\nGLAPI void APIENTRY glWindowPos2f (GLfloat, GLfloat);\nGLAPI void APIENTRY glWindowPos2fv (const GLfloat *);\nGLAPI void APIENTRY glWindowPos2i (GLint, GLint);\nGLAPI void APIENTRY glWindowPos2iv (const GLint *);\nGLAPI void APIENTRY glWindowPos2s (GLshort, GLshort);\nGLAPI void APIENTRY glWindowPos2sv (const GLshort *);\nGLAPI void APIENTRY glWindowPos3d (GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glWindowPos3dv (const GLdouble *);\nGLAPI void APIENTRY glWindowPos3f (GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glWindowPos3fv (const GLfloat *);\nGLAPI void APIENTRY glWindowPos3i (GLint, GLint, GLint);\nGLAPI void APIENTRY glWindowPos3iv (const GLint *);\nGLAPI void APIENTRY glWindowPos3s (GLshort, GLshort, GLshort);\nGLAPI void APIENTRY glWindowPos3sv (const GLshort *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);\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 GLvoid *pointer);\ntypedef void (APIENTRYP PFNGLMULTIDRAWARRAYSPROC) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount);\ntypedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount);\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 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 GLvoid *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);\n#endif\n\n#ifndef GL_VERSION_1_5\n#define GL_VERSION_1_5 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glGenQueries (GLsizei, GLuint *);\nGLAPI void APIENTRY glDeleteQueries (GLsizei, const GLuint *);\nGLAPI GLboolean APIENTRY glIsQuery (GLuint);\nGLAPI void APIENTRY glBeginQuery (GLenum, GLuint);\nGLAPI void APIENTRY glEndQuery (GLenum);\nGLAPI void APIENTRY glGetQueryiv (GLenum, GLenum, GLint *);\nGLAPI void APIENTRY glGetQueryObjectiv (GLuint, GLenum, GLint *);\nGLAPI void APIENTRY glGetQueryObjectuiv (GLuint, GLenum, GLuint *);\nGLAPI void APIENTRY glBindBuffer (GLenum, GLuint);\nGLAPI void APIENTRY glDeleteBuffers (GLsizei, const GLuint *);\nGLAPI void APIENTRY glGenBuffers (GLsizei, GLuint *);\nGLAPI GLboolean APIENTRY glIsBuffer (GLuint);\nGLAPI void APIENTRY glBufferData (GLenum, GLsizeiptr, const GLvoid *, GLenum);\nGLAPI void APIENTRY glBufferSubData (GLenum, GLintptr, GLsizeiptr, const GLvoid *);\nGLAPI void APIENTRY glGetBufferSubData (GLenum, GLintptr, GLsizeiptr, GLvoid *);\nGLAPI GLvoid* APIENTRY glMapBuffer (GLenum, GLenum);\nGLAPI GLboolean APIENTRY glUnmapBuffer (GLenum);\nGLAPI void APIENTRY glGetBufferParameteriv (GLenum, GLenum, GLint *);\nGLAPI void APIENTRY glGetBufferPointerv (GLenum, GLenum, GLvoid* *);\n#endif /* GL_GLEXT_PROTOTYPES */\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 GLvoid *data, GLenum usage);\ntypedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data);\ntypedef void (APIENTRYP PFNGLGETBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, GLvoid *data);\ntypedef GLvoid* (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, GLvoid* *params);\n#endif\n\n#ifndef GL_VERSION_2_0\n#define GL_VERSION_2_0 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBlendEquationSeparate (GLenum, GLenum);\nGLAPI void APIENTRY glDrawBuffers (GLsizei, const GLenum *);\nGLAPI void APIENTRY glStencilOpSeparate (GLenum, GLenum, GLenum, GLenum);\nGLAPI void APIENTRY glStencilFuncSeparate (GLenum, GLenum, GLint, GLuint);\nGLAPI void APIENTRY glStencilMaskSeparate (GLenum, GLuint);\nGLAPI void APIENTRY glAttachShader (GLuint, GLuint);\nGLAPI void APIENTRY glBindAttribLocation (GLuint, GLuint, const GLchar *);\nGLAPI void APIENTRY glCompileShader (GLuint);\nGLAPI GLuint APIENTRY glCreateProgram (void);\nGLAPI GLuint APIENTRY glCreateShader (GLenum);\nGLAPI void APIENTRY glDeleteProgram (GLuint);\nGLAPI void APIENTRY glDeleteShader (GLuint);\nGLAPI void APIENTRY glDetachShader (GLuint, GLuint);\nGLAPI void APIENTRY glDisableVertexAttribArray (GLuint);\nGLAPI void APIENTRY glEnableVertexAttribArray (GLuint);\nGLAPI void APIENTRY glGetActiveAttrib (GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *);\nGLAPI void APIENTRY glGetActiveUniform (GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *);\nGLAPI void APIENTRY glGetAttachedShaders (GLuint, GLsizei, GLsizei *, GLuint *);\nGLAPI GLint APIENTRY glGetAttribLocation (GLuint, const GLchar *);\nGLAPI void APIENTRY glGetProgramiv (GLuint, GLenum, GLint *);\nGLAPI void APIENTRY glGetProgramInfoLog (GLuint, GLsizei, GLsizei *, GLchar *);\nGLAPI void APIENTRY glGetShaderiv (GLuint, GLenum, GLint *);\nGLAPI void APIENTRY glGetShaderInfoLog (GLuint, GLsizei, GLsizei *, GLchar *);\nGLAPI void APIENTRY glGetShaderSource (GLuint, GLsizei, GLsizei *, GLchar *);\nGLAPI GLint APIENTRY glGetUniformLocation (GLuint, const GLchar *);\nGLAPI void APIENTRY glGetUniformfv (GLuint, GLint, GLfloat *);\nGLAPI void APIENTRY glGetUniformiv (GLuint, GLint, GLint *);\nGLAPI void APIENTRY glGetVertexAttribdv (GLuint, GLenum, GLdouble *);\nGLAPI void APIENTRY glGetVertexAttribfv (GLuint, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetVertexAttribiv (GLuint, GLenum, GLint *);\nGLAPI void APIENTRY glGetVertexAttribPointerv (GLuint, GLenum, GLvoid* *);\nGLAPI GLboolean APIENTRY glIsProgram (GLuint);\nGLAPI GLboolean APIENTRY glIsShader (GLuint);\nGLAPI void APIENTRY glLinkProgram (GLuint);\nGLAPI void APIENTRY glShaderSource (GLuint, GLsizei, const GLchar* *, const GLint *);\nGLAPI void APIENTRY glUseProgram (GLuint);\nGLAPI void APIENTRY glUniform1f (GLint, GLfloat);\nGLAPI void APIENTRY glUniform2f (GLint, GLfloat, GLfloat);\nGLAPI void APIENTRY glUniform3f (GLint, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glUniform4f (GLint, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glUniform1i (GLint, GLint);\nGLAPI void APIENTRY glUniform2i (GLint, GLint, GLint);\nGLAPI void APIENTRY glUniform3i (GLint, GLint, GLint, GLint);\nGLAPI void APIENTRY glUniform4i (GLint, GLint, GLint, GLint, GLint);\nGLAPI void APIENTRY glUniform1fv (GLint, GLsizei, const GLfloat *);\nGLAPI void APIENTRY glUniform2fv (GLint, GLsizei, const GLfloat *);\nGLAPI void APIENTRY glUniform3fv (GLint, GLsizei, const GLfloat *);\nGLAPI void APIENTRY glUniform4fv (GLint, GLsizei, const GLfloat *);\nGLAPI void APIENTRY glUniform1iv (GLint, GLsizei, const GLint *);\nGLAPI void APIENTRY glUniform2iv (GLint, GLsizei, const GLint *);\nGLAPI void APIENTRY glUniform3iv (GLint, GLsizei, const GLint *);\nGLAPI void APIENTRY glUniform4iv (GLint, GLsizei, const GLint *);\nGLAPI void APIENTRY glUniformMatrix2fv (GLint, GLsizei, GLboolean, const GLfloat *);\nGLAPI void APIENTRY glUniformMatrix3fv (GLint, GLsizei, GLboolean, const GLfloat *);\nGLAPI void APIENTRY glUniformMatrix4fv (GLint, GLsizei, GLboolean, const GLfloat *);\nGLAPI void APIENTRY glValidateProgram (GLuint);\nGLAPI void APIENTRY glVertexAttrib1d (GLuint, GLdouble);\nGLAPI void APIENTRY glVertexAttrib1dv (GLuint, const GLdouble *);\nGLAPI void APIENTRY glVertexAttrib1f (GLuint, GLfloat);\nGLAPI void APIENTRY glVertexAttrib1fv (GLuint, const GLfloat *);\nGLAPI void APIENTRY glVertexAttrib1s (GLuint, GLshort);\nGLAPI void APIENTRY glVertexAttrib1sv (GLuint, const GLshort *);\nGLAPI void APIENTRY glVertexAttrib2d (GLuint, GLdouble, GLdouble);\nGLAPI void APIENTRY glVertexAttrib2dv (GLuint, const GLdouble *);\nGLAPI void APIENTRY glVertexAttrib2f (GLuint, GLfloat, GLfloat);\nGLAPI void APIENTRY glVertexAttrib2fv (GLuint, const GLfloat *);\nGLAPI void APIENTRY glVertexAttrib2s (GLuint, GLshort, GLshort);\nGLAPI void APIENTRY glVertexAttrib2sv (GLuint, const GLshort *);\nGLAPI void APIENTRY glVertexAttrib3d (GLuint, GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glVertexAttrib3dv (GLuint, const GLdouble *);\nGLAPI void APIENTRY glVertexAttrib3f (GLuint, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glVertexAttrib3fv (GLuint, const GLfloat *);\nGLAPI void APIENTRY glVertexAttrib3s (GLuint, GLshort, GLshort, GLshort);\nGLAPI void APIENTRY glVertexAttrib3sv (GLuint, const GLshort *);\nGLAPI void APIENTRY glVertexAttrib4Nbv (GLuint, const GLbyte *);\nGLAPI void APIENTRY glVertexAttrib4Niv (GLuint, const GLint *);\nGLAPI void APIENTRY glVertexAttrib4Nsv (GLuint, const GLshort *);\nGLAPI void APIENTRY glVertexAttrib4Nub (GLuint, GLubyte, GLubyte, GLubyte, GLubyte);\nGLAPI void APIENTRY glVertexAttrib4Nubv (GLuint, const GLubyte *);\nGLAPI void APIENTRY glVertexAttrib4Nuiv (GLuint, const GLuint *);\nGLAPI void APIENTRY glVertexAttrib4Nusv (GLuint, const GLushort *);\nGLAPI void APIENTRY glVertexAttrib4bv (GLuint, const GLbyte *);\nGLAPI void APIENTRY glVertexAttrib4d (GLuint, GLdouble, GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glVertexAttrib4dv (GLuint, const GLdouble *);\nGLAPI void APIENTRY glVertexAttrib4f (GLuint, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glVertexAttrib4fv (GLuint, const GLfloat *);\nGLAPI void APIENTRY glVertexAttrib4iv (GLuint, const GLint *);\nGLAPI void APIENTRY glVertexAttrib4s (GLuint, GLshort, GLshort, GLshort, GLshort);\nGLAPI void APIENTRY glVertexAttrib4sv (GLuint, const GLshort *);\nGLAPI void APIENTRY glVertexAttrib4ubv (GLuint, const GLubyte *);\nGLAPI void APIENTRY glVertexAttrib4uiv (GLuint, const GLuint *);\nGLAPI void APIENTRY glVertexAttrib4usv (GLuint, const GLushort *);\nGLAPI void APIENTRY glVertexAttribPointer (GLuint, GLint, GLenum, GLboolean, GLsizei, const GLvoid *);\n#endif /* GL_GLEXT_PROTOTYPES */\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 frontfunc, GLenum backfunc, 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 *obj);\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, GLvoid* *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* *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 GLvoid *pointer);\n#endif\n\n#ifndef GL_ARB_multitexture\n#define GL_ARB_multitexture 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glActiveTextureARB (GLenum);\nGLAPI void APIENTRY glClientActiveTextureARB (GLenum);\nGLAPI void APIENTRY glMultiTexCoord1dARB (GLenum, GLdouble);\nGLAPI void APIENTRY glMultiTexCoord1dvARB (GLenum, const GLdouble *);\nGLAPI void APIENTRY glMultiTexCoord1fARB (GLenum, GLfloat);\nGLAPI void APIENTRY glMultiTexCoord1fvARB (GLenum, const GLfloat *);\nGLAPI void APIENTRY glMultiTexCoord1iARB (GLenum, GLint);\nGLAPI void APIENTRY glMultiTexCoord1ivARB (GLenum, const GLint *);\nGLAPI void APIENTRY glMultiTexCoord1sARB (GLenum, GLshort);\nGLAPI void APIENTRY glMultiTexCoord1svARB (GLenum, const GLshort *);\nGLAPI void APIENTRY glMultiTexCoord2dARB (GLenum, GLdouble, GLdouble);\nGLAPI void APIENTRY glMultiTexCoord2dvARB (GLenum, const GLdouble *);\nGLAPI void APIENTRY glMultiTexCoord2fARB (GLenum, GLfloat, GLfloat);\nGLAPI void APIENTRY glMultiTexCoord2fvARB (GLenum, const GLfloat *);\nGLAPI void APIENTRY glMultiTexCoord2iARB (GLenum, GLint, GLint);\nGLAPI void APIENTRY glMultiTexCoord2ivARB (GLenum, const GLint *);\nGLAPI void APIENTRY glMultiTexCoord2sARB (GLenum, GLshort, GLshort);\nGLAPI void APIENTRY glMultiTexCoord2svARB (GLenum, const GLshort *);\nGLAPI void APIENTRY glMultiTexCoord3dARB (GLenum, GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glMultiTexCoord3dvARB (GLenum, const GLdouble *);\nGLAPI void APIENTRY glMultiTexCoord3fARB (GLenum, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glMultiTexCoord3fvARB (GLenum, const GLfloat *);\nGLAPI void APIENTRY glMultiTexCoord3iARB (GLenum, GLint, GLint, GLint);\nGLAPI void APIENTRY glMultiTexCoord3ivARB (GLenum, const GLint *);\nGLAPI void APIENTRY glMultiTexCoord3sARB (GLenum, GLshort, GLshort, GLshort);\nGLAPI void APIENTRY glMultiTexCoord3svARB (GLenum, const GLshort *);\nGLAPI void APIENTRY glMultiTexCoord4dARB (GLenum, GLdouble, GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glMultiTexCoord4dvARB (GLenum, const GLdouble *);\nGLAPI void APIENTRY glMultiTexCoord4fARB (GLenum, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glMultiTexCoord4fvARB (GLenum, const GLfloat *);\nGLAPI void APIENTRY glMultiTexCoord4iARB (GLenum, GLint, GLint, GLint, GLint);\nGLAPI void APIENTRY glMultiTexCoord4ivARB (GLenum, const GLint *);\nGLAPI void APIENTRY glMultiTexCoord4sARB (GLenum, GLshort, GLshort, GLshort, GLshort);\nGLAPI void APIENTRY glMultiTexCoord4svARB (GLenum, const GLshort *);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_ARB_transpose_matrix\n#define GL_ARB_transpose_matrix 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glLoadTransposeMatrixfARB (const GLfloat *);\nGLAPI void APIENTRY glLoadTransposeMatrixdARB (const GLdouble *);\nGLAPI void APIENTRY glMultTransposeMatrixfARB (const GLfloat *);\nGLAPI void APIENTRY glMultTransposeMatrixdARB (const GLdouble *);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_ARB_multisample\n#define GL_ARB_multisample 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glSampleCoverageARB (GLclampf, GLboolean);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLSAMPLECOVERAGEARBPROC) (GLclampf value, GLboolean invert);\n#endif\n\n#ifndef GL_ARB_texture_env_add\n#define GL_ARB_texture_env_add 1\n#endif\n\n#ifndef GL_ARB_texture_cube_map\n#define GL_ARB_texture_cube_map 1\n#endif\n\n#ifndef GL_ARB_texture_compression\n#define GL_ARB_texture_compression 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glCompressedTexImage3DARB (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glCompressedTexImage2DARB (GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glCompressedTexImage1DARB (GLenum, GLint, GLenum, GLsizei, GLint, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glCompressedTexSubImage3DARB (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glCompressedTexSubImage2DARB (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glCompressedTexSubImage1DARB (GLenum, GLint, GLint, GLsizei, GLenum, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glGetCompressedTexImageARB (GLenum, GLint, GLvoid *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *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 GLvoid *data);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data);\ntypedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data);\ntypedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GLint level, GLvoid *img);\n#endif\n\n#ifndef GL_ARB_texture_border_clamp\n#define GL_ARB_texture_border_clamp 1\n#endif\n\n#ifndef GL_ARB_point_parameters\n#define GL_ARB_point_parameters 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPointParameterfARB (GLenum, GLfloat);\nGLAPI void APIENTRY glPointParameterfvARB (GLenum, const GLfloat *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLPOINTPARAMETERFARBPROC) (GLenum pname, GLfloat param);\ntypedef void (APIENTRYP PFNGLPOINTPARAMETERFVARBPROC) (GLenum pname, const GLfloat *params);\n#endif\n\n#ifndef GL_ARB_vertex_blend\n#define GL_ARB_vertex_blend 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glWeightbvARB (GLint, const GLbyte *);\nGLAPI void APIENTRY glWeightsvARB (GLint, const GLshort *);\nGLAPI void APIENTRY glWeightivARB (GLint, const GLint *);\nGLAPI void APIENTRY glWeightfvARB (GLint, const GLfloat *);\nGLAPI void APIENTRY glWeightdvARB (GLint, const GLdouble *);\nGLAPI void APIENTRY glWeightubvARB (GLint, const GLubyte *);\nGLAPI void APIENTRY glWeightusvARB (GLint, const GLushort *);\nGLAPI void APIENTRY glWeightuivARB (GLint, const GLuint *);\nGLAPI void APIENTRY glWeightPointerARB (GLint, GLenum, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glVertexBlendARB (GLint);\n#endif /* GL_GLEXT_PROTOTYPES */\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 GLvoid *pointer);\ntypedef void (APIENTRYP PFNGLVERTEXBLENDARBPROC) (GLint count);\n#endif\n\n#ifndef GL_ARB_matrix_palette\n#define GL_ARB_matrix_palette 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glCurrentPaletteMatrixARB (GLint);\nGLAPI void APIENTRY glMatrixIndexubvARB (GLint, const GLubyte *);\nGLAPI void APIENTRY glMatrixIndexusvARB (GLint, const GLushort *);\nGLAPI void APIENTRY glMatrixIndexuivARB (GLint, const GLuint *);\nGLAPI void APIENTRY glMatrixIndexPointerARB (GLint, GLenum, GLsizei, const GLvoid *);\n#endif /* GL_GLEXT_PROTOTYPES */\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 GLvoid *pointer);\n#endif\n\n#ifndef GL_ARB_texture_env_combine\n#define GL_ARB_texture_env_combine 1\n#endif\n\n#ifndef GL_ARB_texture_env_crossbar\n#define GL_ARB_texture_env_crossbar 1\n#endif\n\n#ifndef GL_ARB_texture_env_dot3\n#define GL_ARB_texture_env_dot3 1\n#endif\n\n#ifndef GL_ARB_texture_mirrored_repeat\n#define GL_ARB_texture_mirrored_repeat 1\n#endif\n\n#ifndef GL_ARB_depth_texture\n#define GL_ARB_depth_texture 1\n#endif\n\n#ifndef GL_ARB_shadow\n#define GL_ARB_shadow 1\n#endif\n\n#ifndef GL_ARB_shadow_ambient\n#define GL_ARB_shadow_ambient 1\n#endif\n\n#ifndef GL_ARB_window_pos\n#define GL_ARB_window_pos 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glWindowPos2dARB (GLdouble, GLdouble);\nGLAPI void APIENTRY glWindowPos2dvARB (const GLdouble *);\nGLAPI void APIENTRY glWindowPos2fARB (GLfloat, GLfloat);\nGLAPI void APIENTRY glWindowPos2fvARB (const GLfloat *);\nGLAPI void APIENTRY glWindowPos2iARB (GLint, GLint);\nGLAPI void APIENTRY glWindowPos2ivARB (const GLint *);\nGLAPI void APIENTRY glWindowPos2sARB (GLshort, GLshort);\nGLAPI void APIENTRY glWindowPos2svARB (const GLshort *);\nGLAPI void APIENTRY glWindowPos3dARB (GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glWindowPos3dvARB (const GLdouble *);\nGLAPI void APIENTRY glWindowPos3fARB (GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glWindowPos3fvARB (const GLfloat *);\nGLAPI void APIENTRY glWindowPos3iARB (GLint, GLint, GLint);\nGLAPI void APIENTRY glWindowPos3ivARB (const GLint *);\nGLAPI void APIENTRY glWindowPos3sARB (GLshort, GLshort, GLshort);\nGLAPI void APIENTRY glWindowPos3svARB (const GLshort *);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_ARB_vertex_program\n#define GL_ARB_vertex_program 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glVertexAttrib1dARB (GLuint, GLdouble);\nGLAPI void APIENTRY glVertexAttrib1dvARB (GLuint, const GLdouble *);\nGLAPI void APIENTRY glVertexAttrib1fARB (GLuint, GLfloat);\nGLAPI void APIENTRY glVertexAttrib1fvARB (GLuint, const GLfloat *);\nGLAPI void APIENTRY glVertexAttrib1sARB (GLuint, GLshort);\nGLAPI void APIENTRY glVertexAttrib1svARB (GLuint, const GLshort *);\nGLAPI void APIENTRY glVertexAttrib2dARB (GLuint, GLdouble, GLdouble);\nGLAPI void APIENTRY glVertexAttrib2dvARB (GLuint, const GLdouble *);\nGLAPI void APIENTRY glVertexAttrib2fARB (GLuint, GLfloat, GLfloat);\nGLAPI void APIENTRY glVertexAttrib2fvARB (GLuint, const GLfloat *);\nGLAPI void APIENTRY glVertexAttrib2sARB (GLuint, GLshort, GLshort);\nGLAPI void APIENTRY glVertexAttrib2svARB (GLuint, const GLshort *);\nGLAPI void APIENTRY glVertexAttrib3dARB (GLuint, GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glVertexAttrib3dvARB (GLuint, const GLdouble *);\nGLAPI void APIENTRY glVertexAttrib3fARB (GLuint, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glVertexAttrib3fvARB (GLuint, const GLfloat *);\nGLAPI void APIENTRY glVertexAttrib3sARB (GLuint, GLshort, GLshort, GLshort);\nGLAPI void APIENTRY glVertexAttrib3svARB (GLuint, const GLshort *);\nGLAPI void APIENTRY glVertexAttrib4NbvARB (GLuint, const GLbyte *);\nGLAPI void APIENTRY glVertexAttrib4NivARB (GLuint, const GLint *);\nGLAPI void APIENTRY glVertexAttrib4NsvARB (GLuint, const GLshort *);\nGLAPI void APIENTRY glVertexAttrib4NubARB (GLuint, GLubyte, GLubyte, GLubyte, GLubyte);\nGLAPI void APIENTRY glVertexAttrib4NubvARB (GLuint, const GLubyte *);\nGLAPI void APIENTRY glVertexAttrib4NuivARB (GLuint, const GLuint *);\nGLAPI void APIENTRY glVertexAttrib4NusvARB (GLuint, const GLushort *);\nGLAPI void APIENTRY glVertexAttrib4bvARB (GLuint, const GLbyte *);\nGLAPI void APIENTRY glVertexAttrib4dARB (GLuint, GLdouble, GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glVertexAttrib4dvARB (GLuint, const GLdouble *);\nGLAPI void APIENTRY glVertexAttrib4fARB (GLuint, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glVertexAttrib4fvARB (GLuint, const GLfloat *);\nGLAPI void APIENTRY glVertexAttrib4ivARB (GLuint, const GLint *);\nGLAPI void APIENTRY glVertexAttrib4sARB (GLuint, GLshort, GLshort, GLshort, GLshort);\nGLAPI void APIENTRY glVertexAttrib4svARB (GLuint, const GLshort *);\nGLAPI void APIENTRY glVertexAttrib4ubvARB (GLuint, const GLubyte *);\nGLAPI void APIENTRY glVertexAttrib4uivARB (GLuint, const GLuint *);\nGLAPI void APIENTRY glVertexAttrib4usvARB (GLuint, const GLushort *);\nGLAPI void APIENTRY glVertexAttribPointerARB (GLuint, GLint, GLenum, GLboolean, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glEnableVertexAttribArrayARB (GLuint);\nGLAPI void APIENTRY glDisableVertexAttribArrayARB (GLuint);\nGLAPI void APIENTRY glProgramStringARB (GLenum, GLenum, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glBindProgramARB (GLenum, GLuint);\nGLAPI void APIENTRY glDeleteProgramsARB (GLsizei, const GLuint *);\nGLAPI void APIENTRY glGenProgramsARB (GLsizei, GLuint *);\nGLAPI void APIENTRY glProgramEnvParameter4dARB (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glProgramEnvParameter4dvARB (GLenum, GLuint, const GLdouble *);\nGLAPI void APIENTRY glProgramEnvParameter4fARB (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glProgramEnvParameter4fvARB (GLenum, GLuint, const GLfloat *);\nGLAPI void APIENTRY glProgramLocalParameter4dARB (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glProgramLocalParameter4dvARB (GLenum, GLuint, const GLdouble *);\nGLAPI void APIENTRY glProgramLocalParameter4fARB (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glProgramLocalParameter4fvARB (GLenum, GLuint, const GLfloat *);\nGLAPI void APIENTRY glGetProgramEnvParameterdvARB (GLenum, GLuint, GLdouble *);\nGLAPI void APIENTRY glGetProgramEnvParameterfvARB (GLenum, GLuint, GLfloat *);\nGLAPI void APIENTRY glGetProgramLocalParameterdvARB (GLenum, GLuint, GLdouble *);\nGLAPI void APIENTRY glGetProgramLocalParameterfvARB (GLenum, GLuint, GLfloat *);\nGLAPI void APIENTRY glGetProgramivARB (GLenum, GLenum, GLint *);\nGLAPI void APIENTRY glGetProgramStringARB (GLenum, GLenum, GLvoid *);\nGLAPI void APIENTRY glGetVertexAttribdvARB (GLuint, GLenum, GLdouble *);\nGLAPI void APIENTRY glGetVertexAttribfvARB (GLuint, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetVertexAttribivARB (GLuint, GLenum, GLint *);\nGLAPI void APIENTRY glGetVertexAttribPointervARB (GLuint, GLenum, GLvoid* *);\nGLAPI GLboolean APIENTRY glIsProgramARB (GLuint);\n#endif /* GL_GLEXT_PROTOTYPES */\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 GLvoid *pointer);\ntypedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYARBPROC) (GLuint index);\ntypedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYARBPROC) (GLuint index);\ntypedef void (APIENTRYP PFNGLPROGRAMSTRINGARBPROC) (GLenum target, GLenum format, GLsizei len, const GLvoid *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, GLvoid *string);\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, GLvoid* *pointer);\ntypedef GLboolean (APIENTRYP PFNGLISPROGRAMARBPROC) (GLuint program);\n#endif\n\n#ifndef GL_ARB_fragment_program\n#define GL_ARB_fragment_program 1\n/* All ARB_fragment_program entry points are shared with ARB_vertex_program. */\n#endif\n\n#ifndef GL_ARB_vertex_buffer_object\n#define GL_ARB_vertex_buffer_object 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBindBufferARB (GLenum, GLuint);\nGLAPI void APIENTRY glDeleteBuffersARB (GLsizei, const GLuint *);\nGLAPI void APIENTRY glGenBuffersARB (GLsizei, GLuint *);\nGLAPI GLboolean APIENTRY glIsBufferARB (GLuint);\nGLAPI void APIENTRY glBufferDataARB (GLenum, GLsizeiptrARB, const GLvoid *, GLenum);\nGLAPI void APIENTRY glBufferSubDataARB (GLenum, GLintptrARB, GLsizeiptrARB, const GLvoid *);\nGLAPI void APIENTRY glGetBufferSubDataARB (GLenum, GLintptrARB, GLsizeiptrARB, GLvoid *);\nGLAPI GLvoid* APIENTRY glMapBufferARB (GLenum, GLenum);\nGLAPI GLboolean APIENTRY glUnmapBufferARB (GLenum);\nGLAPI void APIENTRY glGetBufferParameterivARB (GLenum, GLenum, GLint *);\nGLAPI void APIENTRY glGetBufferPointervARB (GLenum, GLenum, GLvoid* *);\n#endif /* GL_GLEXT_PROTOTYPES */\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 GLvoid *data, GLenum usage);\ntypedef void (APIENTRYP PFNGLBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data);\ntypedef void (APIENTRYP PFNGLGETBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data);\ntypedef GLvoid* (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, GLvoid* *params);\n#endif\n\n#ifndef GL_ARB_occlusion_query\n#define GL_ARB_occlusion_query 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glGenQueriesARB (GLsizei, GLuint *);\nGLAPI void APIENTRY glDeleteQueriesARB (GLsizei, const GLuint *);\nGLAPI GLboolean APIENTRY glIsQueryARB (GLuint);\nGLAPI void APIENTRY glBeginQueryARB (GLenum, GLuint);\nGLAPI void APIENTRY glEndQueryARB (GLenum);\nGLAPI void APIENTRY glGetQueryivARB (GLenum, GLenum, GLint *);\nGLAPI void APIENTRY glGetQueryObjectivARB (GLuint, GLenum, GLint *);\nGLAPI void APIENTRY glGetQueryObjectuivARB (GLuint, GLenum, GLuint *);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_ARB_shader_objects\n#define GL_ARB_shader_objects 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDeleteObjectARB (GLhandleARB);\nGLAPI GLhandleARB APIENTRY glGetHandleARB (GLenum);\nGLAPI void APIENTRY glDetachObjectARB (GLhandleARB, GLhandleARB);\nGLAPI GLhandleARB APIENTRY glCreateShaderObjectARB (GLenum);\nGLAPI void APIENTRY glShaderSourceARB (GLhandleARB, GLsizei, const GLcharARB* *, const GLint *);\nGLAPI void APIENTRY glCompileShaderARB (GLhandleARB);\nGLAPI GLhandleARB APIENTRY glCreateProgramObjectARB (void);\nGLAPI void APIENTRY glAttachObjectARB (GLhandleARB, GLhandleARB);\nGLAPI void APIENTRY glLinkProgramARB (GLhandleARB);\nGLAPI void APIENTRY glUseProgramObjectARB (GLhandleARB);\nGLAPI void APIENTRY glValidateProgramARB (GLhandleARB);\nGLAPI void APIENTRY glUniform1fARB (GLint, GLfloat);\nGLAPI void APIENTRY glUniform2fARB (GLint, GLfloat, GLfloat);\nGLAPI void APIENTRY glUniform3fARB (GLint, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glUniform4fARB (GLint, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glUniform1iARB (GLint, GLint);\nGLAPI void APIENTRY glUniform2iARB (GLint, GLint, GLint);\nGLAPI void APIENTRY glUniform3iARB (GLint, GLint, GLint, GLint);\nGLAPI void APIENTRY glUniform4iARB (GLint, GLint, GLint, GLint, GLint);\nGLAPI void APIENTRY glUniform1fvARB (GLint, GLsizei, const GLfloat *);\nGLAPI void APIENTRY glUniform2fvARB (GLint, GLsizei, const GLfloat *);\nGLAPI void APIENTRY glUniform3fvARB (GLint, GLsizei, const GLfloat *);\nGLAPI void APIENTRY glUniform4fvARB (GLint, GLsizei, const GLfloat *);\nGLAPI void APIENTRY glUniform1ivARB (GLint, GLsizei, const GLint *);\nGLAPI void APIENTRY glUniform2ivARB (GLint, GLsizei, const GLint *);\nGLAPI void APIENTRY glUniform3ivARB (GLint, GLsizei, const GLint *);\nGLAPI void APIENTRY glUniform4ivARB (GLint, GLsizei, const GLint *);\nGLAPI void APIENTRY glUniformMatrix2fvARB (GLint, GLsizei, GLboolean, const GLfloat *);\nGLAPI void APIENTRY glUniformMatrix3fvARB (GLint, GLsizei, GLboolean, const GLfloat *);\nGLAPI void APIENTRY glUniformMatrix4fvARB (GLint, GLsizei, GLboolean, const GLfloat *);\nGLAPI void APIENTRY glGetObjectParameterfvARB (GLhandleARB, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetObjectParameterivARB (GLhandleARB, GLenum, GLint *);\nGLAPI void APIENTRY glGetInfoLogARB (GLhandleARB, GLsizei, GLsizei *, GLcharARB *);\nGLAPI void APIENTRY glGetAttachedObjectsARB (GLhandleARB, GLsizei, GLsizei *, GLhandleARB *);\nGLAPI GLint APIENTRY glGetUniformLocationARB (GLhandleARB, const GLcharARB *);\nGLAPI void APIENTRY glGetActiveUniformARB (GLhandleARB, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLcharARB *);\nGLAPI void APIENTRY glGetUniformfvARB (GLhandleARB, GLint, GLfloat *);\nGLAPI void APIENTRY glGetUniformivARB (GLhandleARB, GLint, GLint *);\nGLAPI void APIENTRY glGetShaderSourceARB (GLhandleARB, GLsizei, GLsizei *, GLcharARB *);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_ARB_vertex_shader\n#define GL_ARB_vertex_shader 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBindAttribLocationARB (GLhandleARB, GLuint, const GLcharARB *);\nGLAPI void APIENTRY glGetActiveAttribARB (GLhandleARB, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLcharARB *);\nGLAPI GLint APIENTRY glGetAttribLocationARB (GLhandleARB, const GLcharARB *);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_ARB_fragment_shader\n#define GL_ARB_fragment_shader 1\n#endif\n\n#ifndef GL_ARB_shading_language_100\n#define GL_ARB_shading_language_100 1\n#endif\n\n#ifndef GL_ARB_texture_non_power_of_two\n#define GL_ARB_texture_non_power_of_two 1\n#endif\n\n#ifndef GL_ARB_point_sprite\n#define GL_ARB_point_sprite 1\n#endif\n\n#ifndef GL_ARB_fragment_program_shadow\n#define GL_ARB_fragment_program_shadow 1\n#endif\n\n#ifndef GL_ARB_draw_buffers\n#define GL_ARB_draw_buffers 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDrawBuffersARB (GLsizei, const GLenum *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLDRAWBUFFERSARBPROC) (GLsizei n, const GLenum *bufs);\n#endif\n\n#ifndef GL_ARB_texture_rectangle\n#define GL_ARB_texture_rectangle 1\n#endif\n\n#ifndef GL_ARB_color_buffer_float\n#define GL_ARB_color_buffer_float 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glClampColorARB (GLenum, GLenum);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLCLAMPCOLORARBPROC) (GLenum target, GLenum clamp);\n#endif\n\n#ifndef GL_ARB_half_float_pixel\n#define GL_ARB_half_float_pixel 1\n#endif\n\n#ifndef GL_ARB_texture_float\n#define GL_ARB_texture_float 1\n#endif\n\n#ifndef GL_ARB_pixel_buffer_object\n#define GL_ARB_pixel_buffer_object 1\n#endif\n\n#ifndef GL_EXT_abgr\n#define GL_EXT_abgr 1\n#endif\n\n#ifndef GL_EXT_blend_color\n#define GL_EXT_blend_color 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBlendColorEXT (GLclampf, GLclampf, GLclampf, GLclampf);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLBLENDCOLOREXTPROC) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);\n#endif\n\n#ifndef GL_EXT_polygon_offset\n#define GL_EXT_polygon_offset 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPolygonOffsetEXT (GLfloat, GLfloat);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLPOLYGONOFFSETEXTPROC) (GLfloat factor, GLfloat bias);\n#endif\n\n#ifndef GL_EXT_texture\n#define GL_EXT_texture 1\n#endif\n\n#ifndef GL_EXT_texture3D\n#define GL_EXT_texture3D 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTexImage3DEXT (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);\nGLAPI void APIENTRY glTexSubImage3DEXT (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLTEXIMAGE3DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *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 GLvoid *pixels);\n#endif\n\n#ifndef GL_SGIS_texture_filter4\n#define GL_SGIS_texture_filter4 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glGetTexFilterFuncSGIS (GLenum, GLenum, GLfloat *);\nGLAPI void APIENTRY glTexFilterFuncSGIS (GLenum, GLenum, GLsizei, const GLfloat *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLGETTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLfloat *weights);\ntypedef void (APIENTRYP PFNGLTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLsizei n, const GLfloat *weights);\n#endif\n\n#ifndef GL_EXT_subtexture\n#define GL_EXT_subtexture 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTexSubImage1DEXT (GLenum, GLint, GLint, GLsizei, GLenum, GLenum, const GLvoid *);\nGLAPI void APIENTRY glTexSubImage2DEXT (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);\ntypedef void (APIENTRYP PFNGLTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);\n#endif\n\n#ifndef GL_EXT_copy_texture\n#define GL_EXT_copy_texture 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glCopyTexImage1DEXT (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLint);\nGLAPI void APIENTRY glCopyTexImage2DEXT (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint);\nGLAPI void APIENTRY glCopyTexSubImage1DEXT (GLenum, GLint, GLint, GLint, GLint, GLsizei);\nGLAPI void APIENTRY glCopyTexSubImage2DEXT (GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei);\nGLAPI void APIENTRY glCopyTexSubImage3DEXT (GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_EXT_histogram\n#define GL_EXT_histogram 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glGetHistogramEXT (GLenum, GLboolean, GLenum, GLenum, GLvoid *);\nGLAPI void APIENTRY glGetHistogramParameterfvEXT (GLenum, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetHistogramParameterivEXT (GLenum, GLenum, GLint *);\nGLAPI void APIENTRY glGetMinmaxEXT (GLenum, GLboolean, GLenum, GLenum, GLvoid *);\nGLAPI void APIENTRY glGetMinmaxParameterfvEXT (GLenum, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetMinmaxParameterivEXT (GLenum, GLenum, GLint *);\nGLAPI void APIENTRY glHistogramEXT (GLenum, GLsizei, GLenum, GLboolean);\nGLAPI void APIENTRY glMinmaxEXT (GLenum, GLenum, GLboolean);\nGLAPI void APIENTRY glResetHistogramEXT (GLenum);\nGLAPI void APIENTRY glResetMinmaxEXT (GLenum);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLGETHISTOGRAMEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *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, GLvoid *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#endif\n\n#ifndef GL_EXT_convolution\n#define GL_EXT_convolution 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glConvolutionFilter1DEXT (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);\nGLAPI void APIENTRY glConvolutionFilter2DEXT (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);\nGLAPI void APIENTRY glConvolutionParameterfEXT (GLenum, GLenum, GLfloat);\nGLAPI void APIENTRY glConvolutionParameterfvEXT (GLenum, GLenum, const GLfloat *);\nGLAPI void APIENTRY glConvolutionParameteriEXT (GLenum, GLenum, GLint);\nGLAPI void APIENTRY glConvolutionParameterivEXT (GLenum, GLenum, const GLint *);\nGLAPI void APIENTRY glCopyConvolutionFilter1DEXT (GLenum, GLenum, GLint, GLint, GLsizei);\nGLAPI void APIENTRY glCopyConvolutionFilter2DEXT (GLenum, GLenum, GLint, GLint, GLsizei, GLsizei);\nGLAPI void APIENTRY glGetConvolutionFilterEXT (GLenum, GLenum, GLenum, GLvoid *);\nGLAPI void APIENTRY glGetConvolutionParameterfvEXT (GLenum, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetConvolutionParameterivEXT (GLenum, GLenum, GLint *);\nGLAPI void APIENTRY glGetSeparableFilterEXT (GLenum, GLenum, GLenum, GLvoid *, GLvoid *, GLvoid *);\nGLAPI void APIENTRY glSeparableFilter2DEXT (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *, const GLvoid *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image);\ntypedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *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, GLvoid *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, GLvoid *row, GLvoid *column, GLvoid *span);\ntypedef void (APIENTRYP PFNGLSEPARABLEFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column);\n#endif\n\n#ifndef GL_EXT_color_matrix\n#define GL_EXT_color_matrix 1\n#endif\n\n#ifndef GL_SGI_color_table\n#define GL_SGI_color_table 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glColorTableSGI (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);\nGLAPI void APIENTRY glColorTableParameterfvSGI (GLenum, GLenum, const GLfloat *);\nGLAPI void APIENTRY glColorTableParameterivSGI (GLenum, GLenum, const GLint *);\nGLAPI void APIENTRY glCopyColorTableSGI (GLenum, GLenum, GLint, GLint, GLsizei);\nGLAPI void APIENTRY glGetColorTableSGI (GLenum, GLenum, GLenum, GLvoid *);\nGLAPI void APIENTRY glGetColorTableParameterfvSGI (GLenum, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetColorTableParameterivSGI (GLenum, GLenum, GLint *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *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, GLvoid *table);\ntypedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, GLint *params);\n#endif\n\n#ifndef GL_SGIX_pixel_texture\n#define GL_SGIX_pixel_texture 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPixelTexGenSGIX (GLenum);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLPIXELTEXGENSGIXPROC) (GLenum mode);\n#endif\n\n#ifndef GL_SGIS_pixel_texture\n#define GL_SGIS_pixel_texture 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPixelTexGenParameteriSGIS (GLenum, GLint);\nGLAPI void APIENTRY glPixelTexGenParameterivSGIS (GLenum, const GLint *);\nGLAPI void APIENTRY glPixelTexGenParameterfSGIS (GLenum, GLfloat);\nGLAPI void APIENTRY glPixelTexGenParameterfvSGIS (GLenum, const GLfloat *);\nGLAPI void APIENTRY glGetPixelTexGenParameterivSGIS (GLenum, GLint *);\nGLAPI void APIENTRY glGetPixelTexGenParameterfvSGIS (GLenum, GLfloat *);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_SGIS_texture4D\n#define GL_SGIS_texture4D 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTexImage4DSGIS (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);\nGLAPI void APIENTRY glTexSubImage4DSGIS (GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);\n#endif /* GL_GLEXT_PROTOTYPES */\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 GLvoid *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 GLvoid *pixels);\n#endif\n\n#ifndef GL_SGI_texture_color_table\n#define GL_SGI_texture_color_table 1\n#endif\n\n#ifndef GL_EXT_cmyka\n#define GL_EXT_cmyka 1\n#endif\n\n#ifndef GL_EXT_texture_object\n#define GL_EXT_texture_object 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI GLboolean APIENTRY glAreTexturesResidentEXT (GLsizei, const GLuint *, GLboolean *);\nGLAPI void APIENTRY glBindTextureEXT (GLenum, GLuint);\nGLAPI void APIENTRY glDeleteTexturesEXT (GLsizei, const GLuint *);\nGLAPI void APIENTRY glGenTexturesEXT (GLsizei, GLuint *);\nGLAPI GLboolean APIENTRY glIsTextureEXT (GLuint);\nGLAPI void APIENTRY glPrioritizeTexturesEXT (GLsizei, const GLuint *, const GLclampf *);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_SGIS_detail_texture\n#define GL_SGIS_detail_texture 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDetailTexFuncSGIS (GLenum, GLsizei, const GLfloat *);\nGLAPI void APIENTRY glGetDetailTexFuncSGIS (GLenum, GLfloat *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLDETAILTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points);\ntypedef void (APIENTRYP PFNGLGETDETAILTEXFUNCSGISPROC) (GLenum target, GLfloat *points);\n#endif\n\n#ifndef GL_SGIS_sharpen_texture\n#define GL_SGIS_sharpen_texture 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glSharpenTexFuncSGIS (GLenum, GLsizei, const GLfloat *);\nGLAPI void APIENTRY glGetSharpenTexFuncSGIS (GLenum, GLfloat *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLSHARPENTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points);\ntypedef void (APIENTRYP PFNGLGETSHARPENTEXFUNCSGISPROC) (GLenum target, GLfloat *points);\n#endif\n\n#ifndef GL_EXT_packed_pixels\n#define GL_EXT_packed_pixels 1\n#endif\n\n#ifndef GL_SGIS_texture_lod\n#define GL_SGIS_texture_lod 1\n#endif\n\n#ifndef GL_SGIS_multisample\n#define GL_SGIS_multisample 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glSampleMaskSGIS (GLclampf, GLboolean);\nGLAPI void APIENTRY glSamplePatternSGIS (GLenum);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLSAMPLEMASKSGISPROC) (GLclampf value, GLboolean invert);\ntypedef void (APIENTRYP PFNGLSAMPLEPATTERNSGISPROC) (GLenum pattern);\n#endif\n\n#ifndef GL_EXT_rescale_normal\n#define GL_EXT_rescale_normal 1\n#endif\n\n#ifndef GL_EXT_vertex_array\n#define GL_EXT_vertex_array 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glArrayElementEXT (GLint);\nGLAPI void APIENTRY glColorPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glDrawArraysEXT (GLenum, GLint, GLsizei);\nGLAPI void APIENTRY glEdgeFlagPointerEXT (GLsizei, GLsizei, const GLboolean *);\nGLAPI void APIENTRY glGetPointervEXT (GLenum, GLvoid* *);\nGLAPI void APIENTRY glIndexPointerEXT (GLenum, GLsizei, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glNormalPointerEXT (GLenum, GLsizei, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glTexCoordPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glVertexPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLARRAYELEMENTEXTPROC) (GLint i);\ntypedef void (APIENTRYP PFNGLCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *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, GLvoid* *params);\ntypedef void (APIENTRYP PFNGLINDEXPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);\ntypedef void (APIENTRYP PFNGLNORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);\ntypedef void (APIENTRYP PFNGLTEXCOORDPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);\ntypedef void (APIENTRYP PFNGLVERTEXPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);\n#endif\n\n#ifndef GL_EXT_misc_attribute\n#define GL_EXT_misc_attribute 1\n#endif\n\n#ifndef GL_SGIS_generate_mipmap\n#define GL_SGIS_generate_mipmap 1\n#endif\n\n#ifndef GL_SGIX_clipmap\n#define GL_SGIX_clipmap 1\n#endif\n\n#ifndef GL_SGIX_shadow\n#define GL_SGIX_shadow 1\n#endif\n\n#ifndef GL_SGIS_texture_edge_clamp\n#define GL_SGIS_texture_edge_clamp 1\n#endif\n\n#ifndef GL_SGIS_texture_border_clamp\n#define GL_SGIS_texture_border_clamp 1\n#endif\n\n#ifndef GL_EXT_blend_minmax\n#define GL_EXT_blend_minmax 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBlendEquationEXT (GLenum);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLBLENDEQUATIONEXTPROC) (GLenum mode);\n#endif\n\n#ifndef GL_EXT_blend_subtract\n#define GL_EXT_blend_subtract 1\n#endif\n\n#ifndef GL_EXT_blend_logic_op\n#define GL_EXT_blend_logic_op 1\n#endif\n\n#ifndef GL_SGIX_interlace\n#define GL_SGIX_interlace 1\n#endif\n\n#ifndef GL_SGIX_pixel_tiles\n#define GL_SGIX_pixel_tiles 1\n#endif\n\n#ifndef GL_SGIX_texture_select\n#define GL_SGIX_texture_select 1\n#endif\n\n#ifndef GL_SGIX_sprite\n#define GL_SGIX_sprite 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glSpriteParameterfSGIX (GLenum, GLfloat);\nGLAPI void APIENTRY glSpriteParameterfvSGIX (GLenum, const GLfloat *);\nGLAPI void APIENTRY glSpriteParameteriSGIX (GLenum, GLint);\nGLAPI void APIENTRY glSpriteParameterivSGIX (GLenum, const GLint *);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_SGIX_texture_multi_buffer\n#define GL_SGIX_texture_multi_buffer 1\n#endif\n\n#ifndef GL_EXT_point_parameters\n#define GL_EXT_point_parameters 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPointParameterfEXT (GLenum, GLfloat);\nGLAPI void APIENTRY glPointParameterfvEXT (GLenum, const GLfloat *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLPOINTPARAMETERFEXTPROC) (GLenum pname, GLfloat param);\ntypedef void (APIENTRYP PFNGLPOINTPARAMETERFVEXTPROC) (GLenum pname, const GLfloat *params);\n#endif\n\n#ifndef GL_SGIS_point_parameters\n#define GL_SGIS_point_parameters 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPointParameterfSGIS (GLenum, GLfloat);\nGLAPI void APIENTRY glPointParameterfvSGIS (GLenum, const GLfloat *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLPOINTPARAMETERFSGISPROC) (GLenum pname, GLfloat param);\ntypedef void (APIENTRYP PFNGLPOINTPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params);\n#endif\n\n#ifndef GL_SGIX_instruments\n#define GL_SGIX_instruments 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI GLint APIENTRY glGetInstrumentsSGIX (void);\nGLAPI void APIENTRY glInstrumentsBufferSGIX (GLsizei, GLint *);\nGLAPI GLint APIENTRY glPollInstrumentsSGIX (GLint *);\nGLAPI void APIENTRY glReadInstrumentsSGIX (GLint);\nGLAPI void APIENTRY glStartInstrumentsSGIX (void);\nGLAPI void APIENTRY glStopInstrumentsSGIX (GLint);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_SGIX_texture_scale_bias\n#define GL_SGIX_texture_scale_bias 1\n#endif\n\n#ifndef GL_SGIX_framezoom\n#define GL_SGIX_framezoom 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glFrameZoomSGIX (GLint);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLFRAMEZOOMSGIXPROC) (GLint factor);\n#endif\n\n#ifndef GL_SGIX_tag_sample_buffer\n#define GL_SGIX_tag_sample_buffer 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTagSampleBufferSGIX (void);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLTAGSAMPLEBUFFERSGIXPROC) (void);\n#endif\n\n#ifndef GL_SGIX_polynomial_ffd\n#define GL_SGIX_polynomial_ffd 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDeformationMap3dSGIX (GLenum, GLdouble, GLdouble, GLint, GLint, GLdouble, GLdouble, GLint, GLint, GLdouble, GLdouble, GLint, GLint, const GLdouble *);\nGLAPI void APIENTRY glDeformationMap3fSGIX (GLenum, GLfloat, GLfloat, GLint, GLint, GLfloat, GLfloat, GLint, GLint, GLfloat, GLfloat, GLint, GLint, const GLfloat *);\nGLAPI void APIENTRY glDeformSGIX (GLbitfield);\nGLAPI void APIENTRY glLoadIdentityDeformationMapSGIX (GLbitfield);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_SGIX_reference_plane\n#define GL_SGIX_reference_plane 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glReferencePlaneSGIX (const GLdouble *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLREFERENCEPLANESGIXPROC) (const GLdouble *equation);\n#endif\n\n#ifndef GL_SGIX_flush_raster\n#define GL_SGIX_flush_raster 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glFlushRasterSGIX (void);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLFLUSHRASTERSGIXPROC) (void);\n#endif\n\n#ifndef GL_SGIX_depth_texture\n#define GL_SGIX_depth_texture 1\n#endif\n\n#ifndef GL_SGIS_fog_function\n#define GL_SGIS_fog_function 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glFogFuncSGIS (GLsizei, const GLfloat *);\nGLAPI void APIENTRY glGetFogFuncSGIS (GLfloat *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLFOGFUNCSGISPROC) (GLsizei n, const GLfloat *points);\ntypedef void (APIENTRYP PFNGLGETFOGFUNCSGISPROC) (GLfloat *points);\n#endif\n\n#ifndef GL_SGIX_fog_offset\n#define GL_SGIX_fog_offset 1\n#endif\n\n#ifndef GL_HP_image_transform\n#define GL_HP_image_transform 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glImageTransformParameteriHP (GLenum, GLenum, GLint);\nGLAPI void APIENTRY glImageTransformParameterfHP (GLenum, GLenum, GLfloat);\nGLAPI void APIENTRY glImageTransformParameterivHP (GLenum, GLenum, const GLint *);\nGLAPI void APIENTRY glImageTransformParameterfvHP (GLenum, GLenum, const GLfloat *);\nGLAPI void APIENTRY glGetImageTransformParameterivHP (GLenum, GLenum, GLint *);\nGLAPI void APIENTRY glGetImageTransformParameterfvHP (GLenum, GLenum, GLfloat *);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_HP_convolution_border_modes\n#define GL_HP_convolution_border_modes 1\n#endif\n\n#ifndef GL_SGIX_texture_add_env\n#define GL_SGIX_texture_add_env 1\n#endif\n\n#ifndef GL_EXT_color_subtable\n#define GL_EXT_color_subtable 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glColorSubTableEXT (GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);\nGLAPI void APIENTRY glCopyColorSubTableEXT (GLenum, GLsizei, GLint, GLint, GLsizei);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data);\ntypedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width);\n#endif\n\n#ifndef GL_PGI_vertex_hints\n#define GL_PGI_vertex_hints 1\n#endif\n\n#ifndef GL_PGI_misc_hints\n#define GL_PGI_misc_hints 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glHintPGI (GLenum, GLint);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLHINTPGIPROC) (GLenum target, GLint mode);\n#endif\n\n#ifndef GL_EXT_paletted_texture\n#define GL_EXT_paletted_texture 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glColorTableEXT (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);\nGLAPI void APIENTRY glGetColorTableEXT (GLenum, GLenum, GLenum, GLvoid *);\nGLAPI void APIENTRY glGetColorTableParameterivEXT (GLenum, GLenum, GLint *);\nGLAPI void APIENTRY glGetColorTableParameterfvEXT (GLenum, GLenum, GLfloat *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLCOLORTABLEEXTPROC) (GLenum target, GLenum internalFormat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);\ntypedef void (APIENTRYP PFNGLGETCOLORTABLEEXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *data);\ntypedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);\ntypedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);\n#endif\n\n#ifndef GL_EXT_clip_volume_hint\n#define GL_EXT_clip_volume_hint 1\n#endif\n\n#ifndef GL_SGIX_list_priority\n#define GL_SGIX_list_priority 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glGetListParameterfvSGIX (GLuint, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetListParameterivSGIX (GLuint, GLenum, GLint *);\nGLAPI void APIENTRY glListParameterfSGIX (GLuint, GLenum, GLfloat);\nGLAPI void APIENTRY glListParameterfvSGIX (GLuint, GLenum, const GLfloat *);\nGLAPI void APIENTRY glListParameteriSGIX (GLuint, GLenum, GLint);\nGLAPI void APIENTRY glListParameterivSGIX (GLuint, GLenum, const GLint *);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_SGIX_ir_instrument1\n#define GL_SGIX_ir_instrument1 1\n#endif\n\n#ifndef GL_SGIX_calligraphic_fragment\n#define GL_SGIX_calligraphic_fragment 1\n#endif\n\n#ifndef GL_SGIX_texture_lod_bias\n#define GL_SGIX_texture_lod_bias 1\n#endif\n\n#ifndef GL_SGIX_shadow_ambient\n#define GL_SGIX_shadow_ambient 1\n#endif\n\n#ifndef GL_EXT_index_texture\n#define GL_EXT_index_texture 1\n#endif\n\n#ifndef GL_EXT_index_material\n#define GL_EXT_index_material 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glIndexMaterialEXT (GLenum, GLenum);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLINDEXMATERIALEXTPROC) (GLenum face, GLenum mode);\n#endif\n\n#ifndef GL_EXT_index_func\n#define GL_EXT_index_func 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glIndexFuncEXT (GLenum, GLclampf);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLINDEXFUNCEXTPROC) (GLenum func, GLclampf ref);\n#endif\n\n#ifndef GL_EXT_index_array_formats\n#define GL_EXT_index_array_formats 1\n#endif\n\n#ifndef GL_EXT_compiled_vertex_array\n#define GL_EXT_compiled_vertex_array 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glLockArraysEXT (GLint, GLsizei);\nGLAPI void APIENTRY glUnlockArraysEXT (void);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLLOCKARRAYSEXTPROC) (GLint first, GLsizei count);\ntypedef void (APIENTRYP PFNGLUNLOCKARRAYSEXTPROC) (void);\n#endif\n\n#ifndef GL_EXT_cull_vertex\n#define GL_EXT_cull_vertex 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glCullParameterdvEXT (GLenum, GLdouble *);\nGLAPI void APIENTRY glCullParameterfvEXT (GLenum, GLfloat *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLCULLPARAMETERDVEXTPROC) (GLenum pname, GLdouble *params);\ntypedef void (APIENTRYP PFNGLCULLPARAMETERFVEXTPROC) (GLenum pname, GLfloat *params);\n#endif\n\n#ifndef GL_SGIX_ycrcb\n#define GL_SGIX_ycrcb 1\n#endif\n\n#ifndef GL_SGIX_fragment_lighting\n#define GL_SGIX_fragment_lighting 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glFragmentColorMaterialSGIX (GLenum, GLenum);\nGLAPI void APIENTRY glFragmentLightfSGIX (GLenum, GLenum, GLfloat);\nGLAPI void APIENTRY glFragmentLightfvSGIX (GLenum, GLenum, const GLfloat *);\nGLAPI void APIENTRY glFragmentLightiSGIX (GLenum, GLenum, GLint);\nGLAPI void APIENTRY glFragmentLightivSGIX (GLenum, GLenum, const GLint *);\nGLAPI void APIENTRY glFragmentLightModelfSGIX (GLenum, GLfloat);\nGLAPI void APIENTRY glFragmentLightModelfvSGIX (GLenum, const GLfloat *);\nGLAPI void APIENTRY glFragmentLightModeliSGIX (GLenum, GLint);\nGLAPI void APIENTRY glFragmentLightModelivSGIX (GLenum, const GLint *);\nGLAPI void APIENTRY glFragmentMaterialfSGIX (GLenum, GLenum, GLfloat);\nGLAPI void APIENTRY glFragmentMaterialfvSGIX (GLenum, GLenum, const GLfloat *);\nGLAPI void APIENTRY glFragmentMaterialiSGIX (GLenum, GLenum, GLint);\nGLAPI void APIENTRY glFragmentMaterialivSGIX (GLenum, GLenum, const GLint *);\nGLAPI void APIENTRY glGetFragmentLightfvSGIX (GLenum, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetFragmentLightivSGIX (GLenum, GLenum, GLint *);\nGLAPI void APIENTRY glGetFragmentMaterialfvSGIX (GLenum, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetFragmentMaterialivSGIX (GLenum, GLenum, GLint *);\nGLAPI void APIENTRY glLightEnviSGIX (GLenum, GLint);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_IBM_rasterpos_clip\n#define GL_IBM_rasterpos_clip 1\n#endif\n\n#ifndef GL_HP_texture_lighting\n#define GL_HP_texture_lighting 1\n#endif\n\n#ifndef GL_EXT_draw_range_elements\n#define GL_EXT_draw_range_elements 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDrawRangeElementsEXT (GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSEXTPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices);\n#endif\n\n#ifndef GL_WIN_phong_shading\n#define GL_WIN_phong_shading 1\n#endif\n\n#ifndef GL_WIN_specular_fog\n#define GL_WIN_specular_fog 1\n#endif\n\n#ifndef GL_EXT_light_texture\n#define GL_EXT_light_texture 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glApplyTextureEXT (GLenum);\nGLAPI void APIENTRY glTextureLightEXT (GLenum);\nGLAPI void APIENTRY glTextureMaterialEXT (GLenum, GLenum);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLAPPLYTEXTUREEXTPROC) (GLenum mode);\ntypedef void (APIENTRYP PFNGLTEXTURELIGHTEXTPROC) (GLenum pname);\ntypedef void (APIENTRYP PFNGLTEXTUREMATERIALEXTPROC) (GLenum face, GLenum mode);\n#endif\n\n#ifndef GL_SGIX_blend_alpha_minmax\n#define GL_SGIX_blend_alpha_minmax 1\n#endif\n\n#ifndef GL_EXT_bgra\n#define GL_EXT_bgra 1\n#endif\n\n#ifndef GL_SGIX_async\n#define GL_SGIX_async 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glAsyncMarkerSGIX (GLuint);\nGLAPI GLint APIENTRY glFinishAsyncSGIX (GLuint *);\nGLAPI GLint APIENTRY glPollAsyncSGIX (GLuint *);\nGLAPI GLuint APIENTRY glGenAsyncMarkersSGIX (GLsizei);\nGLAPI void APIENTRY glDeleteAsyncMarkersSGIX (GLuint, GLsizei);\nGLAPI GLboolean APIENTRY glIsAsyncMarkerSGIX (GLuint);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_SGIX_async_pixel\n#define GL_SGIX_async_pixel 1\n#endif\n\n#ifndef GL_SGIX_async_histogram\n#define GL_SGIX_async_histogram 1\n#endif\n\n#ifndef GL_INTEL_parallel_arrays\n#define GL_INTEL_parallel_arrays 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glVertexPointervINTEL (GLint, GLenum, const GLvoid* *);\nGLAPI void APIENTRY glNormalPointervINTEL (GLenum, const GLvoid* *);\nGLAPI void APIENTRY glColorPointervINTEL (GLint, GLenum, const GLvoid* *);\nGLAPI void APIENTRY glTexCoordPointervINTEL (GLint, GLenum, const GLvoid* *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLVERTEXPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer);\ntypedef void (APIENTRYP PFNGLNORMALPOINTERVINTELPROC) (GLenum type, const GLvoid* *pointer);\ntypedef void (APIENTRYP PFNGLCOLORPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer);\ntypedef void (APIENTRYP PFNGLTEXCOORDPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer);\n#endif\n\n#ifndef GL_HP_occlusion_test\n#define GL_HP_occlusion_test 1\n#endif\n\n#ifndef GL_EXT_pixel_transform\n#define GL_EXT_pixel_transform 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPixelTransformParameteriEXT (GLenum, GLenum, GLint);\nGLAPI void APIENTRY glPixelTransformParameterfEXT (GLenum, GLenum, GLfloat);\nGLAPI void APIENTRY glPixelTransformParameterivEXT (GLenum, GLenum, const GLint *);\nGLAPI void APIENTRY glPixelTransformParameterfvEXT (GLenum, GLenum, const GLfloat *);\n#endif /* GL_GLEXT_PROTOTYPES */\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);\n#endif\n\n#ifndef GL_EXT_pixel_transform_color_table\n#define GL_EXT_pixel_transform_color_table 1\n#endif\n\n#ifndef GL_EXT_shared_texture_palette\n#define GL_EXT_shared_texture_palette 1\n#endif\n\n#ifndef GL_EXT_separate_specular_color\n#define GL_EXT_separate_specular_color 1\n#endif\n\n#ifndef GL_EXT_secondary_color\n#define GL_EXT_secondary_color 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glSecondaryColor3bEXT (GLbyte, GLbyte, GLbyte);\nGLAPI void APIENTRY glSecondaryColor3bvEXT (const GLbyte *);\nGLAPI void APIENTRY glSecondaryColor3dEXT (GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glSecondaryColor3dvEXT (const GLdouble *);\nGLAPI void APIENTRY glSecondaryColor3fEXT (GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glSecondaryColor3fvEXT (const GLfloat *);\nGLAPI void APIENTRY glSecondaryColor3iEXT (GLint, GLint, GLint);\nGLAPI void APIENTRY glSecondaryColor3ivEXT (const GLint *);\nGLAPI void APIENTRY glSecondaryColor3sEXT (GLshort, GLshort, GLshort);\nGLAPI void APIENTRY glSecondaryColor3svEXT (const GLshort *);\nGLAPI void APIENTRY glSecondaryColor3ubEXT (GLubyte, GLubyte, GLubyte);\nGLAPI void APIENTRY glSecondaryColor3ubvEXT (const GLubyte *);\nGLAPI void APIENTRY glSecondaryColor3uiEXT (GLuint, GLuint, GLuint);\nGLAPI void APIENTRY glSecondaryColor3uivEXT (const GLuint *);\nGLAPI void APIENTRY glSecondaryColor3usEXT (GLushort, GLushort, GLushort);\nGLAPI void APIENTRY glSecondaryColor3usvEXT (const GLushort *);\nGLAPI void APIENTRY glSecondaryColorPointerEXT (GLint, GLenum, GLsizei, const GLvoid *);\n#endif /* GL_GLEXT_PROTOTYPES */\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 GLvoid *pointer);\n#endif\n\n#ifndef GL_EXT_texture_perturb_normal\n#define GL_EXT_texture_perturb_normal 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTextureNormalEXT (GLenum);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLTEXTURENORMALEXTPROC) (GLenum mode);\n#endif\n\n#ifndef GL_EXT_multi_draw_arrays\n#define GL_EXT_multi_draw_arrays 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glMultiDrawArraysEXT (GLenum, GLint *, GLsizei *, GLsizei);\nGLAPI void APIENTRY glMultiDrawElementsEXT (GLenum, const GLsizei *, GLenum, const GLvoid* *, GLsizei);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLMULTIDRAWARRAYSEXTPROC) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount);\ntypedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSEXTPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount);\n#endif\n\n#ifndef GL_EXT_fog_coord\n#define GL_EXT_fog_coord 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glFogCoordfEXT (GLfloat);\nGLAPI void APIENTRY glFogCoordfvEXT (const GLfloat *);\nGLAPI void APIENTRY glFogCoorddEXT (GLdouble);\nGLAPI void APIENTRY glFogCoorddvEXT (const GLdouble *);\nGLAPI void APIENTRY glFogCoordPointerEXT (GLenum, GLsizei, const GLvoid *);\n#endif /* GL_GLEXT_PROTOTYPES */\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 GLvoid *pointer);\n#endif\n\n#ifndef GL_REND_screen_coordinates\n#define GL_REND_screen_coordinates 1\n#endif\n\n#ifndef GL_EXT_coordinate_frame\n#define GL_EXT_coordinate_frame 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTangent3bEXT (GLbyte, GLbyte, GLbyte);\nGLAPI void APIENTRY glTangent3bvEXT (const GLbyte *);\nGLAPI void APIENTRY glTangent3dEXT (GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glTangent3dvEXT (const GLdouble *);\nGLAPI void APIENTRY glTangent3fEXT (GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glTangent3fvEXT (const GLfloat *);\nGLAPI void APIENTRY glTangent3iEXT (GLint, GLint, GLint);\nGLAPI void APIENTRY glTangent3ivEXT (const GLint *);\nGLAPI void APIENTRY glTangent3sEXT (GLshort, GLshort, GLshort);\nGLAPI void APIENTRY glTangent3svEXT (const GLshort *);\nGLAPI void APIENTRY glBinormal3bEXT (GLbyte, GLbyte, GLbyte);\nGLAPI void APIENTRY glBinormal3bvEXT (const GLbyte *);\nGLAPI void APIENTRY glBinormal3dEXT (GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glBinormal3dvEXT (const GLdouble *);\nGLAPI void APIENTRY glBinormal3fEXT (GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glBinormal3fvEXT (const GLfloat *);\nGLAPI void APIENTRY glBinormal3iEXT (GLint, GLint, GLint);\nGLAPI void APIENTRY glBinormal3ivEXT (const GLint *);\nGLAPI void APIENTRY glBinormal3sEXT (GLshort, GLshort, GLshort);\nGLAPI void APIENTRY glBinormal3svEXT (const GLshort *);\nGLAPI void APIENTRY glTangentPointerEXT (GLenum, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glBinormalPointerEXT (GLenum, GLsizei, const GLvoid *);\n#endif /* GL_GLEXT_PROTOTYPES */\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 GLvoid *pointer);\ntypedef void (APIENTRYP PFNGLBINORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, const GLvoid *pointer);\n#endif\n\n#ifndef GL_EXT_texture_env_combine\n#define GL_EXT_texture_env_combine 1\n#endif\n\n#ifndef GL_APPLE_specular_vector\n#define GL_APPLE_specular_vector 1\n#endif\n\n#ifndef GL_APPLE_transform_hint\n#define GL_APPLE_transform_hint 1\n#endif\n\n#ifndef GL_SGIX_fog_scale\n#define GL_SGIX_fog_scale 1\n#endif\n\n#ifndef GL_SUNX_constant_data\n#define GL_SUNX_constant_data 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glFinishTextureSUNX (void);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLFINISHTEXTURESUNXPROC) (void);\n#endif\n\n#ifndef GL_SUN_global_alpha\n#define GL_SUN_global_alpha 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glGlobalAlphaFactorbSUN (GLbyte);\nGLAPI void APIENTRY glGlobalAlphaFactorsSUN (GLshort);\nGLAPI void APIENTRY glGlobalAlphaFactoriSUN (GLint);\nGLAPI void APIENTRY glGlobalAlphaFactorfSUN (GLfloat);\nGLAPI void APIENTRY glGlobalAlphaFactordSUN (GLdouble);\nGLAPI void APIENTRY glGlobalAlphaFactorubSUN (GLubyte);\nGLAPI void APIENTRY glGlobalAlphaFactorusSUN (GLushort);\nGLAPI void APIENTRY glGlobalAlphaFactoruiSUN (GLuint);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_SUN_triangle_list\n#define GL_SUN_triangle_list 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glReplacementCodeuiSUN (GLuint);\nGLAPI void APIENTRY glReplacementCodeusSUN (GLushort);\nGLAPI void APIENTRY glReplacementCodeubSUN (GLubyte);\nGLAPI void APIENTRY glReplacementCodeuivSUN (const GLuint *);\nGLAPI void APIENTRY glReplacementCodeusvSUN (const GLushort *);\nGLAPI void APIENTRY glReplacementCodeubvSUN (const GLubyte *);\nGLAPI void APIENTRY glReplacementCodePointerSUN (GLenum, GLsizei, const GLvoid* *);\n#endif /* GL_GLEXT_PROTOTYPES */\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 GLvoid* *pointer);\n#endif\n\n#ifndef GL_SUN_vertex\n#define GL_SUN_vertex 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glColor4ubVertex2fSUN (GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat);\nGLAPI void APIENTRY glColor4ubVertex2fvSUN (const GLubyte *, const GLfloat *);\nGLAPI void APIENTRY glColor4ubVertex3fSUN (GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glColor4ubVertex3fvSUN (const GLubyte *, const GLfloat *);\nGLAPI void APIENTRY glColor3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glColor3fVertex3fvSUN (const GLfloat *, const GLfloat *);\nGLAPI void APIENTRY glNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *);\nGLAPI void APIENTRY glColor4fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glColor4fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *);\nGLAPI void APIENTRY glTexCoord2fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glTexCoord2fVertex3fvSUN (const GLfloat *, const GLfloat *);\nGLAPI void APIENTRY glTexCoord4fVertex4fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glTexCoord4fVertex4fvSUN (const GLfloat *, const GLfloat *);\nGLAPI void APIENTRY glTexCoord2fColor4ubVertex3fSUN (GLfloat, GLfloat, GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glTexCoord2fColor4ubVertex3fvSUN (const GLfloat *, const GLubyte *, const GLfloat *);\nGLAPI void APIENTRY glTexCoord2fColor3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glTexCoord2fColor3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *);\nGLAPI void APIENTRY glTexCoord2fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glTexCoord2fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *);\nGLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *);\nGLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fvSUN (const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *);\nGLAPI void APIENTRY glReplacementCodeuiVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glReplacementCodeuiVertex3fvSUN (const GLuint *, const GLfloat *);\nGLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fSUN (GLuint, GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fvSUN (const GLuint *, const GLubyte *, const GLfloat *);\nGLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *);\nGLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *);\nGLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *);\nGLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *);\nGLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *);\nGLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_EXT_blend_func_separate\n#define GL_EXT_blend_func_separate 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBlendFuncSeparateEXT (GLenum, GLenum, GLenum, GLenum);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEEXTPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);\n#endif\n\n#ifndef GL_INGR_blend_func_separate\n#define GL_INGR_blend_func_separate 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBlendFuncSeparateINGR (GLenum, GLenum, GLenum, GLenum);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEINGRPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);\n#endif\n\n#ifndef GL_INGR_color_clamp\n#define GL_INGR_color_clamp 1\n#endif\n\n#ifndef GL_INGR_interlace_read\n#define GL_INGR_interlace_read 1\n#endif\n\n#ifndef GL_EXT_stencil_wrap\n#define GL_EXT_stencil_wrap 1\n#endif\n\n#ifndef GL_EXT_422_pixels\n#define GL_EXT_422_pixels 1\n#endif\n\n#ifndef GL_NV_texgen_reflection\n#define GL_NV_texgen_reflection 1\n#endif\n\n#ifndef GL_SUN_convolution_border_modes\n#define GL_SUN_convolution_border_modes 1\n#endif\n\n#ifndef GL_EXT_texture_env_add\n#define GL_EXT_texture_env_add 1\n#endif\n\n#ifndef GL_EXT_texture_lod_bias\n#define GL_EXT_texture_lod_bias 1\n#endif\n\n#ifndef GL_EXT_texture_filter_anisotropic\n#define GL_EXT_texture_filter_anisotropic 1\n#endif\n\n#ifndef GL_EXT_vertex_weighting\n#define GL_EXT_vertex_weighting 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glVertexWeightfEXT (GLfloat);\nGLAPI void APIENTRY glVertexWeightfvEXT (const GLfloat *);\nGLAPI void APIENTRY glVertexWeightPointerEXT (GLsizei, GLenum, GLsizei, const GLvoid *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLVERTEXWEIGHTFEXTPROC) (GLfloat weight);\ntypedef void (APIENTRYP PFNGLVERTEXWEIGHTFVEXTPROC) (const GLfloat *weight);\ntypedef void (APIENTRYP PFNGLVERTEXWEIGHTPOINTEREXTPROC) (GLsizei size, GLenum type, GLsizei stride, const GLvoid *pointer);\n#endif\n\n#ifndef GL_NV_light_max_exponent\n#define GL_NV_light_max_exponent 1\n#endif\n\n#ifndef GL_NV_vertex_array_range\n#define GL_NV_vertex_array_range 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glFlushVertexArrayRangeNV (void);\nGLAPI void APIENTRY glVertexArrayRangeNV (GLsizei, const GLvoid *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGENVPROC) (void);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYRANGENVPROC) (GLsizei length, const GLvoid *pointer);\n#endif\n\n#ifndef GL_NV_register_combiners\n#define GL_NV_register_combiners 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glCombinerParameterfvNV (GLenum, const GLfloat *);\nGLAPI void APIENTRY glCombinerParameterfNV (GLenum, GLfloat);\nGLAPI void APIENTRY glCombinerParameterivNV (GLenum, const GLint *);\nGLAPI void APIENTRY glCombinerParameteriNV (GLenum, GLint);\nGLAPI void APIENTRY glCombinerInputNV (GLenum, GLenum, GLenum, GLenum, GLenum, GLenum);\nGLAPI void APIENTRY glCombinerOutputNV (GLenum, GLenum, GLenum, GLenum, GLenum, GLenum, GLenum, GLboolean, GLboolean, GLboolean);\nGLAPI void APIENTRY glFinalCombinerInputNV (GLenum, GLenum, GLenum, GLenum);\nGLAPI void APIENTRY glGetCombinerInputParameterfvNV (GLenum, GLenum, GLenum, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetCombinerInputParameterivNV (GLenum, GLenum, GLenum, GLenum, GLint *);\nGLAPI void APIENTRY glGetCombinerOutputParameterfvNV (GLenum, GLenum, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetCombinerOutputParameterivNV (GLenum, GLenum, GLenum, GLint *);\nGLAPI void APIENTRY glGetFinalCombinerInputParameterfvNV (GLenum, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetFinalCombinerInputParameterivNV (GLenum, GLenum, GLint *);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_NV_fog_distance\n#define GL_NV_fog_distance 1\n#endif\n\n#ifndef GL_NV_texgen_emboss\n#define GL_NV_texgen_emboss 1\n#endif\n\n#ifndef GL_NV_blend_square\n#define GL_NV_blend_square 1\n#endif\n\n#ifndef GL_NV_texture_env_combine4\n#define GL_NV_texture_env_combine4 1\n#endif\n\n#ifndef GL_MESA_resize_buffers\n#define GL_MESA_resize_buffers 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glResizeBuffersMESA (void);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLRESIZEBUFFERSMESAPROC) (void);\n#endif\n\n#ifndef GL_MESA_window_pos\n#define GL_MESA_window_pos 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glWindowPos2dMESA (GLdouble, GLdouble);\nGLAPI void APIENTRY glWindowPos2dvMESA (const GLdouble *);\nGLAPI void APIENTRY glWindowPos2fMESA (GLfloat, GLfloat);\nGLAPI void APIENTRY glWindowPos2fvMESA (const GLfloat *);\nGLAPI void APIENTRY glWindowPos2iMESA (GLint, GLint);\nGLAPI void APIENTRY glWindowPos2ivMESA (const GLint *);\nGLAPI void APIENTRY glWindowPos2sMESA (GLshort, GLshort);\nGLAPI void APIENTRY glWindowPos2svMESA (const GLshort *);\nGLAPI void APIENTRY glWindowPos3dMESA (GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glWindowPos3dvMESA (const GLdouble *);\nGLAPI void APIENTRY glWindowPos3fMESA (GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glWindowPos3fvMESA (const GLfloat *);\nGLAPI void APIENTRY glWindowPos3iMESA (GLint, GLint, GLint);\nGLAPI void APIENTRY glWindowPos3ivMESA (const GLint *);\nGLAPI void APIENTRY glWindowPos3sMESA (GLshort, GLshort, GLshort);\nGLAPI void APIENTRY glWindowPos3svMESA (const GLshort *);\nGLAPI void APIENTRY glWindowPos4dMESA (GLdouble, GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glWindowPos4dvMESA (const GLdouble *);\nGLAPI void APIENTRY glWindowPos4fMESA (GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glWindowPos4fvMESA (const GLfloat *);\nGLAPI void APIENTRY glWindowPos4iMESA (GLint, GLint, GLint, GLint);\nGLAPI void APIENTRY glWindowPos4ivMESA (const GLint *);\nGLAPI void APIENTRY glWindowPos4sMESA (GLshort, GLshort, GLshort, GLshort);\nGLAPI void APIENTRY glWindowPos4svMESA (const GLshort *);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_IBM_cull_vertex\n#define GL_IBM_cull_vertex 1\n#endif\n\n#ifndef GL_IBM_multimode_draw_arrays\n#define GL_IBM_multimode_draw_arrays 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glMultiModeDrawArraysIBM (const GLenum *, const GLint *, const GLsizei *, GLsizei, GLint);\nGLAPI void APIENTRY glMultiModeDrawElementsIBM (const GLenum *, const GLsizei *, GLenum, const GLvoid* const *, GLsizei, GLint);\n#endif /* GL_GLEXT_PROTOTYPES */\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 GLvoid* const *indices, GLsizei primcount, GLint modestride);\n#endif\n\n#ifndef GL_IBM_vertex_array_lists\n#define GL_IBM_vertex_array_lists 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glColorPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint);\nGLAPI void APIENTRY glSecondaryColorPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint);\nGLAPI void APIENTRY glEdgeFlagPointerListIBM (GLint, const GLboolean* *, GLint);\nGLAPI void APIENTRY glFogCoordPointerListIBM (GLenum, GLint, const GLvoid* *, GLint);\nGLAPI void APIENTRY glIndexPointerListIBM (GLenum, GLint, const GLvoid* *, GLint);\nGLAPI void APIENTRY glNormalPointerListIBM (GLenum, GLint, const GLvoid* *, GLint);\nGLAPI void APIENTRY glTexCoordPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint);\nGLAPI void APIENTRY glVertexPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);\ntypedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);\ntypedef void (APIENTRYP PFNGLEDGEFLAGPOINTERLISTIBMPROC) (GLint stride, const GLboolean* *pointer, GLint ptrstride);\ntypedef void (APIENTRYP PFNGLFOGCOORDPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);\ntypedef void (APIENTRYP PFNGLINDEXPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);\ntypedef void (APIENTRYP PFNGLNORMALPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);\ntypedef void (APIENTRYP PFNGLTEXCOORDPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);\ntypedef void (APIENTRYP PFNGLVERTEXPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);\n#endif\n\n#ifndef GL_SGIX_subsample\n#define GL_SGIX_subsample 1\n#endif\n\n#ifndef GL_SGIX_ycrcba\n#define GL_SGIX_ycrcba 1\n#endif\n\n#ifndef GL_SGIX_ycrcb_subsample\n#define GL_SGIX_ycrcb_subsample 1\n#endif\n\n#ifndef GL_SGIX_depth_pass_instrument\n#define GL_SGIX_depth_pass_instrument 1\n#endif\n\n#ifndef GL_3DFX_texture_compression_FXT1\n#define GL_3DFX_texture_compression_FXT1 1\n#endif\n\n#ifndef GL_3DFX_multisample\n#define GL_3DFX_multisample 1\n#endif\n\n#ifndef GL_3DFX_tbuffer\n#define GL_3DFX_tbuffer 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTbufferMask3DFX (GLuint);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLTBUFFERMASK3DFXPROC) (GLuint mask);\n#endif\n\n#ifndef GL_EXT_multisample\n#define GL_EXT_multisample 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glSampleMaskEXT (GLclampf, GLboolean);\nGLAPI void APIENTRY glSamplePatternEXT (GLenum);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLSAMPLEMASKEXTPROC) (GLclampf value, GLboolean invert);\ntypedef void (APIENTRYP PFNGLSAMPLEPATTERNEXTPROC) (GLenum pattern);\n#endif\n\n#ifndef GL_SGIX_vertex_preclip\n#define GL_SGIX_vertex_preclip 1\n#endif\n\n#ifndef GL_SGIX_convolution_accuracy\n#define GL_SGIX_convolution_accuracy 1\n#endif\n\n#ifndef GL_SGIX_resample\n#define GL_SGIX_resample 1\n#endif\n\n#ifndef GL_SGIS_point_line_texgen\n#define GL_SGIS_point_line_texgen 1\n#endif\n\n#ifndef GL_SGIS_texture_color_mask\n#define GL_SGIS_texture_color_mask 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTextureColorMaskSGIS (GLboolean, GLboolean, GLboolean, GLboolean);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLTEXTURECOLORMASKSGISPROC) (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);\n#endif\n\n#ifndef GL_SGIX_igloo_interface\n#define GL_SGIX_igloo_interface 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glIglooInterfaceSGIX (GLenum, const GLvoid *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLIGLOOINTERFACESGIXPROC) (GLenum pname, const GLvoid *params);\n#endif\n\n#ifndef GL_EXT_texture_env_dot3\n#define GL_EXT_texture_env_dot3 1\n#endif\n\n#ifndef GL_ATI_texture_mirror_once\n#define GL_ATI_texture_mirror_once 1\n#endif\n\n#ifndef GL_NV_fence\n#define GL_NV_fence 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDeleteFencesNV (GLsizei, const GLuint *);\nGLAPI void APIENTRY glGenFencesNV (GLsizei, GLuint *);\nGLAPI GLboolean APIENTRY glIsFenceNV (GLuint);\nGLAPI GLboolean APIENTRY glTestFenceNV (GLuint);\nGLAPI void APIENTRY glGetFenceivNV (GLuint, GLenum, GLint *);\nGLAPI void APIENTRY glFinishFenceNV (GLuint);\nGLAPI void APIENTRY glSetFenceNV (GLuint, GLenum);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_NV_evaluators\n#define GL_NV_evaluators 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glMapControlPointsNV (GLenum, GLuint, GLenum, GLsizei, GLsizei, GLint, GLint, GLboolean, const GLvoid *);\nGLAPI void APIENTRY glMapParameterivNV (GLenum, GLenum, const GLint *);\nGLAPI void APIENTRY glMapParameterfvNV (GLenum, GLenum, const GLfloat *);\nGLAPI void APIENTRY glGetMapControlPointsNV (GLenum, GLuint, GLenum, GLsizei, GLsizei, GLboolean, GLvoid *);\nGLAPI void APIENTRY glGetMapParameterivNV (GLenum, GLenum, GLint *);\nGLAPI void APIENTRY glGetMapParameterfvNV (GLenum, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetMapAttribParameterivNV (GLenum, GLuint, GLenum, GLint *);\nGLAPI void APIENTRY glGetMapAttribParameterfvNV (GLenum, GLuint, GLenum, GLfloat *);\nGLAPI void APIENTRY glEvalMapsNV (GLenum, GLenum);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLint uorder, GLint vorder, GLboolean packed, const GLvoid *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, GLvoid *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#endif\n\n#ifndef GL_NV_packed_depth_stencil\n#define GL_NV_packed_depth_stencil 1\n#endif\n\n#ifndef GL_NV_register_combiners2\n#define GL_NV_register_combiners2 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glCombinerStageParameterfvNV (GLenum, GLenum, const GLfloat *);\nGLAPI void APIENTRY glGetCombinerStageParameterfvNV (GLenum, GLenum, GLfloat *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, const GLfloat *params);\ntypedef void (APIENTRYP PFNGLGETCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, GLfloat *params);\n#endif\n\n#ifndef GL_NV_texture_compression_vtc\n#define GL_NV_texture_compression_vtc 1\n#endif\n\n#ifndef GL_NV_texture_rectangle\n#define GL_NV_texture_rectangle 1\n#endif\n\n#ifndef GL_NV_texture_shader\n#define GL_NV_texture_shader 1\n#endif\n\n#ifndef GL_NV_texture_shader2\n#define GL_NV_texture_shader2 1\n#endif\n\n#ifndef GL_NV_vertex_array_range2\n#define GL_NV_vertex_array_range2 1\n#endif\n\n#ifndef GL_NV_vertex_program\n#define GL_NV_vertex_program 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI GLboolean APIENTRY glAreProgramsResidentNV (GLsizei, const GLuint *, GLboolean *);\nGLAPI void APIENTRY glBindProgramNV (GLenum, GLuint);\nGLAPI void APIENTRY glDeleteProgramsNV (GLsizei, const GLuint *);\nGLAPI void APIENTRY glExecuteProgramNV (GLenum, GLuint, const GLfloat *);\nGLAPI void APIENTRY glGenProgramsNV (GLsizei, GLuint *);\nGLAPI void APIENTRY glGetProgramParameterdvNV (GLenum, GLuint, GLenum, GLdouble *);\nGLAPI void APIENTRY glGetProgramParameterfvNV (GLenum, GLuint, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetProgramivNV (GLuint, GLenum, GLint *);\nGLAPI void APIENTRY glGetProgramStringNV (GLuint, GLenum, GLubyte *);\nGLAPI void APIENTRY glGetTrackMatrixivNV (GLenum, GLuint, GLenum, GLint *);\nGLAPI void APIENTRY glGetVertexAttribdvNV (GLuint, GLenum, GLdouble *);\nGLAPI void APIENTRY glGetVertexAttribfvNV (GLuint, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetVertexAttribivNV (GLuint, GLenum, GLint *);\nGLAPI void APIENTRY glGetVertexAttribPointervNV (GLuint, GLenum, GLvoid* *);\nGLAPI GLboolean APIENTRY glIsProgramNV (GLuint);\nGLAPI void APIENTRY glLoadProgramNV (GLenum, GLuint, GLsizei, const GLubyte *);\nGLAPI void APIENTRY glProgramParameter4dNV (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glProgramParameter4dvNV (GLenum, GLuint, const GLdouble *);\nGLAPI void APIENTRY glProgramParameter4fNV (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glProgramParameter4fvNV (GLenum, GLuint, const GLfloat *);\nGLAPI void APIENTRY glProgramParameters4dvNV (GLenum, GLuint, GLuint, const GLdouble *);\nGLAPI void APIENTRY glProgramParameters4fvNV (GLenum, GLuint, GLuint, const GLfloat *);\nGLAPI void APIENTRY glRequestResidentProgramsNV (GLsizei, const GLuint *);\nGLAPI void APIENTRY glTrackMatrixNV (GLenum, GLuint, GLenum, GLenum);\nGLAPI void APIENTRY glVertexAttribPointerNV (GLuint, GLint, GLenum, GLsizei, const GLvoid *);\nGLAPI void APIENTRY glVertexAttrib1dNV (GLuint, GLdouble);\nGLAPI void APIENTRY glVertexAttrib1dvNV (GLuint, const GLdouble *);\nGLAPI void APIENTRY glVertexAttrib1fNV (GLuint, GLfloat);\nGLAPI void APIENTRY glVertexAttrib1fvNV (GLuint, const GLfloat *);\nGLAPI void APIENTRY glVertexAttrib1sNV (GLuint, GLshort);\nGLAPI void APIENTRY glVertexAttrib1svNV (GLuint, const GLshort *);\nGLAPI void APIENTRY glVertexAttrib2dNV (GLuint, GLdouble, GLdouble);\nGLAPI void APIENTRY glVertexAttrib2dvNV (GLuint, const GLdouble *);\nGLAPI void APIENTRY glVertexAttrib2fNV (GLuint, GLfloat, GLfloat);\nGLAPI void APIENTRY glVertexAttrib2fvNV (GLuint, const GLfloat *);\nGLAPI void APIENTRY glVertexAttrib2sNV (GLuint, GLshort, GLshort);\nGLAPI void APIENTRY glVertexAttrib2svNV (GLuint, const GLshort *);\nGLAPI void APIENTRY glVertexAttrib3dNV (GLuint, GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glVertexAttrib3dvNV (GLuint, const GLdouble *);\nGLAPI void APIENTRY glVertexAttrib3fNV (GLuint, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glVertexAttrib3fvNV (GLuint, const GLfloat *);\nGLAPI void APIENTRY glVertexAttrib3sNV (GLuint, GLshort, GLshort, GLshort);\nGLAPI void APIENTRY glVertexAttrib3svNV (GLuint, const GLshort *);\nGLAPI void APIENTRY glVertexAttrib4dNV (GLuint, GLdouble, GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glVertexAttrib4dvNV (GLuint, const GLdouble *);\nGLAPI void APIENTRY glVertexAttrib4fNV (GLuint, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glVertexAttrib4fvNV (GLuint, const GLfloat *);\nGLAPI void APIENTRY glVertexAttrib4sNV (GLuint, GLshort, GLshort, GLshort, GLshort);\nGLAPI void APIENTRY glVertexAttrib4svNV (GLuint, const GLshort *);\nGLAPI void APIENTRY glVertexAttrib4ubNV (GLuint, GLubyte, GLubyte, GLubyte, GLubyte);\nGLAPI void APIENTRY glVertexAttrib4ubvNV (GLuint, const GLubyte *);\nGLAPI void APIENTRY glVertexAttribs1dvNV (GLuint, GLsizei, const GLdouble *);\nGLAPI void APIENTRY glVertexAttribs1fvNV (GLuint, GLsizei, const GLfloat *);\nGLAPI void APIENTRY glVertexAttribs1svNV (GLuint, GLsizei, const GLshort *);\nGLAPI void APIENTRY glVertexAttribs2dvNV (GLuint, GLsizei, const GLdouble *);\nGLAPI void APIENTRY glVertexAttribs2fvNV (GLuint, GLsizei, const GLfloat *);\nGLAPI void APIENTRY glVertexAttribs2svNV (GLuint, GLsizei, const GLshort *);\nGLAPI void APIENTRY glVertexAttribs3dvNV (GLuint, GLsizei, const GLdouble *);\nGLAPI void APIENTRY glVertexAttribs3fvNV (GLuint, GLsizei, const GLfloat *);\nGLAPI void APIENTRY glVertexAttribs3svNV (GLuint, GLsizei, const GLshort *);\nGLAPI void APIENTRY glVertexAttribs4dvNV (GLuint, GLsizei, const GLdouble *);\nGLAPI void APIENTRY glVertexAttribs4fvNV (GLuint, GLsizei, const GLfloat *);\nGLAPI void APIENTRY glVertexAttribs4svNV (GLuint, GLsizei, const GLshort *);\nGLAPI void APIENTRY glVertexAttribs4ubvNV (GLuint, GLsizei, const GLubyte *);\n#endif /* GL_GLEXT_PROTOTYPES */\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, GLvoid* *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, GLuint count, const GLdouble *v);\ntypedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4FVNVPROC) (GLenum target, GLuint index, GLuint 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 GLvoid *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#endif\n\n#ifndef GL_SGIX_texture_coordinate_clamp\n#define GL_SGIX_texture_coordinate_clamp 1\n#endif\n\n#ifndef GL_SGIX_scalebias_hint\n#define GL_SGIX_scalebias_hint 1\n#endif\n\n#ifndef GL_OML_interlace\n#define GL_OML_interlace 1\n#endif\n\n#ifndef GL_OML_subsample\n#define GL_OML_subsample 1\n#endif\n\n#ifndef GL_OML_resample\n#define GL_OML_resample 1\n#endif\n\n#ifndef GL_NV_copy_depth_to_color\n#define GL_NV_copy_depth_to_color 1\n#endif\n\n#ifndef GL_ATI_envmap_bumpmap\n#define GL_ATI_envmap_bumpmap 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glTexBumpParameterivATI (GLenum, const GLint *);\nGLAPI void APIENTRY glTexBumpParameterfvATI (GLenum, const GLfloat *);\nGLAPI void APIENTRY glGetTexBumpParameterivATI (GLenum, GLint *);\nGLAPI void APIENTRY glGetTexBumpParameterfvATI (GLenum, GLfloat *);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_ATI_fragment_shader\n#define GL_ATI_fragment_shader 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI GLuint APIENTRY glGenFragmentShadersATI (GLuint);\nGLAPI void APIENTRY glBindFragmentShaderATI (GLuint);\nGLAPI void APIENTRY glDeleteFragmentShaderATI (GLuint);\nGLAPI void APIENTRY glBeginFragmentShaderATI (void);\nGLAPI void APIENTRY glEndFragmentShaderATI (void);\nGLAPI void APIENTRY glPassTexCoordATI (GLuint, GLuint, GLenum);\nGLAPI void APIENTRY glSampleMapATI (GLuint, GLuint, GLenum);\nGLAPI void APIENTRY glColorFragmentOp1ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);\nGLAPI void APIENTRY glColorFragmentOp2ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);\nGLAPI void APIENTRY glColorFragmentOp3ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);\nGLAPI void APIENTRY glAlphaFragmentOp1ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint);\nGLAPI void APIENTRY glAlphaFragmentOp2ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);\nGLAPI void APIENTRY glAlphaFragmentOp3ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);\nGLAPI void APIENTRY glSetFragmentShaderConstantATI (GLuint, const GLfloat *);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_ATI_pn_triangles\n#define GL_ATI_pn_triangles 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPNTrianglesiATI (GLenum, GLint);\nGLAPI void APIENTRY glPNTrianglesfATI (GLenum, GLfloat);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLPNTRIANGLESIATIPROC) (GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLPNTRIANGLESFATIPROC) (GLenum pname, GLfloat param);\n#endif\n\n#ifndef GL_ATI_vertex_array_object\n#define GL_ATI_vertex_array_object 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI GLuint APIENTRY glNewObjectBufferATI (GLsizei, const GLvoid *, GLenum);\nGLAPI GLboolean APIENTRY glIsObjectBufferATI (GLuint);\nGLAPI void APIENTRY glUpdateObjectBufferATI (GLuint, GLuint, GLsizei, const GLvoid *, GLenum);\nGLAPI void APIENTRY glGetObjectBufferfvATI (GLuint, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetObjectBufferivATI (GLuint, GLenum, GLint *);\nGLAPI void APIENTRY glFreeObjectBufferATI (GLuint);\nGLAPI void APIENTRY glArrayObjectATI (GLenum, GLint, GLenum, GLsizei, GLuint, GLuint);\nGLAPI void APIENTRY glGetArrayObjectfvATI (GLenum, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetArrayObjectivATI (GLenum, GLenum, GLint *);\nGLAPI void APIENTRY glVariantArrayObjectATI (GLuint, GLenum, GLsizei, GLuint, GLuint);\nGLAPI void APIENTRY glGetVariantArrayObjectfvATI (GLuint, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetVariantArrayObjectivATI (GLuint, GLenum, GLint *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef GLuint (APIENTRYP PFNGLNEWOBJECTBUFFERATIPROC) (GLsizei size, const GLvoid *pointer, GLenum usage);\ntypedef GLboolean (APIENTRYP PFNGLISOBJECTBUFFERATIPROC) (GLuint buffer);\ntypedef void (APIENTRYP PFNGLUPDATEOBJECTBUFFERATIPROC) (GLuint buffer, GLuint offset, GLsizei size, const GLvoid *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#endif\n\n#ifndef GL_EXT_vertex_shader\n#define GL_EXT_vertex_shader 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBeginVertexShaderEXT (void);\nGLAPI void APIENTRY glEndVertexShaderEXT (void);\nGLAPI void APIENTRY glBindVertexShaderEXT (GLuint);\nGLAPI GLuint APIENTRY glGenVertexShadersEXT (GLuint);\nGLAPI void APIENTRY glDeleteVertexShaderEXT (GLuint);\nGLAPI void APIENTRY glShaderOp1EXT (GLenum, GLuint, GLuint);\nGLAPI void APIENTRY glShaderOp2EXT (GLenum, GLuint, GLuint, GLuint);\nGLAPI void APIENTRY glShaderOp3EXT (GLenum, GLuint, GLuint, GLuint, GLuint);\nGLAPI void APIENTRY glSwizzleEXT (GLuint, GLuint, GLenum, GLenum, GLenum, GLenum);\nGLAPI void APIENTRY glWriteMaskEXT (GLuint, GLuint, GLenum, GLenum, GLenum, GLenum);\nGLAPI void APIENTRY glInsertComponentEXT (GLuint, GLuint, GLuint);\nGLAPI void APIENTRY glExtractComponentEXT (GLuint, GLuint, GLuint);\nGLAPI GLuint APIENTRY glGenSymbolsEXT (GLenum, GLenum, GLenum, GLuint);\nGLAPI void APIENTRY glSetInvariantEXT (GLuint, GLenum, const GLvoid *);\nGLAPI void APIENTRY glSetLocalConstantEXT (GLuint, GLenum, const GLvoid *);\nGLAPI void APIENTRY glVariantbvEXT (GLuint, const GLbyte *);\nGLAPI void APIENTRY glVariantsvEXT (GLuint, const GLshort *);\nGLAPI void APIENTRY glVariantivEXT (GLuint, const GLint *);\nGLAPI void APIENTRY glVariantfvEXT (GLuint, const GLfloat *);\nGLAPI void APIENTRY glVariantdvEXT (GLuint, const GLdouble *);\nGLAPI void APIENTRY glVariantubvEXT (GLuint, const GLubyte *);\nGLAPI void APIENTRY glVariantusvEXT (GLuint, const GLushort *);\nGLAPI void APIENTRY glVariantuivEXT (GLuint, const GLuint *);\nGLAPI void APIENTRY glVariantPointerEXT (GLuint, GLenum, GLuint, const GLvoid *);\nGLAPI void APIENTRY glEnableVariantClientStateEXT (GLuint);\nGLAPI void APIENTRY glDisableVariantClientStateEXT (GLuint);\nGLAPI GLuint APIENTRY glBindLightParameterEXT (GLenum, GLenum);\nGLAPI GLuint APIENTRY glBindMaterialParameterEXT (GLenum, GLenum);\nGLAPI GLuint APIENTRY glBindTexGenParameterEXT (GLenum, GLenum, GLenum);\nGLAPI GLuint APIENTRY glBindTextureUnitParameterEXT (GLenum, GLenum);\nGLAPI GLuint APIENTRY glBindParameterEXT (GLenum);\nGLAPI GLboolean APIENTRY glIsVariantEnabledEXT (GLuint, GLenum);\nGLAPI void APIENTRY glGetVariantBooleanvEXT (GLuint, GLenum, GLboolean *);\nGLAPI void APIENTRY glGetVariantIntegervEXT (GLuint, GLenum, GLint *);\nGLAPI void APIENTRY glGetVariantFloatvEXT (GLuint, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetVariantPointervEXT (GLuint, GLenum, GLvoid* *);\nGLAPI void APIENTRY glGetInvariantBooleanvEXT (GLuint, GLenum, GLboolean *);\nGLAPI void APIENTRY glGetInvariantIntegervEXT (GLuint, GLenum, GLint *);\nGLAPI void APIENTRY glGetInvariantFloatvEXT (GLuint, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetLocalConstantBooleanvEXT (GLuint, GLenum, GLboolean *);\nGLAPI void APIENTRY glGetLocalConstantIntegervEXT (GLuint, GLenum, GLint *);\nGLAPI void APIENTRY glGetLocalConstantFloatvEXT (GLuint, GLenum, GLfloat *);\n#endif /* GL_GLEXT_PROTOTYPES */\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 GLvoid *addr);\ntypedef void (APIENTRYP PFNGLSETLOCALCONSTANTEXTPROC) (GLuint id, GLenum type, const GLvoid *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 GLvoid *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, GLvoid* *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#endif\n\n#ifndef GL_ATI_vertex_streams\n#define GL_ATI_vertex_streams 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glVertexStream1sATI (GLenum, GLshort);\nGLAPI void APIENTRY glVertexStream1svATI (GLenum, const GLshort *);\nGLAPI void APIENTRY glVertexStream1iATI (GLenum, GLint);\nGLAPI void APIENTRY glVertexStream1ivATI (GLenum, const GLint *);\nGLAPI void APIENTRY glVertexStream1fATI (GLenum, GLfloat);\nGLAPI void APIENTRY glVertexStream1fvATI (GLenum, const GLfloat *);\nGLAPI void APIENTRY glVertexStream1dATI (GLenum, GLdouble);\nGLAPI void APIENTRY glVertexStream1dvATI (GLenum, const GLdouble *);\nGLAPI void APIENTRY glVertexStream2sATI (GLenum, GLshort, GLshort);\nGLAPI void APIENTRY glVertexStream2svATI (GLenum, const GLshort *);\nGLAPI void APIENTRY glVertexStream2iATI (GLenum, GLint, GLint);\nGLAPI void APIENTRY glVertexStream2ivATI (GLenum, const GLint *);\nGLAPI void APIENTRY glVertexStream2fATI (GLenum, GLfloat, GLfloat);\nGLAPI void APIENTRY glVertexStream2fvATI (GLenum, const GLfloat *);\nGLAPI void APIENTRY glVertexStream2dATI (GLenum, GLdouble, GLdouble);\nGLAPI void APIENTRY glVertexStream2dvATI (GLenum, const GLdouble *);\nGLAPI void APIENTRY glVertexStream3sATI (GLenum, GLshort, GLshort, GLshort);\nGLAPI void APIENTRY glVertexStream3svATI (GLenum, const GLshort *);\nGLAPI void APIENTRY glVertexStream3iATI (GLenum, GLint, GLint, GLint);\nGLAPI void APIENTRY glVertexStream3ivATI (GLenum, const GLint *);\nGLAPI void APIENTRY glVertexStream3fATI (GLenum, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glVertexStream3fvATI (GLenum, const GLfloat *);\nGLAPI void APIENTRY glVertexStream3dATI (GLenum, GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glVertexStream3dvATI (GLenum, const GLdouble *);\nGLAPI void APIENTRY glVertexStream4sATI (GLenum, GLshort, GLshort, GLshort, GLshort);\nGLAPI void APIENTRY glVertexStream4svATI (GLenum, const GLshort *);\nGLAPI void APIENTRY glVertexStream4iATI (GLenum, GLint, GLint, GLint, GLint);\nGLAPI void APIENTRY glVertexStream4ivATI (GLenum, const GLint *);\nGLAPI void APIENTRY glVertexStream4fATI (GLenum, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glVertexStream4fvATI (GLenum, const GLfloat *);\nGLAPI void APIENTRY glVertexStream4dATI (GLenum, GLdouble, GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glVertexStream4dvATI (GLenum, const GLdouble *);\nGLAPI void APIENTRY glNormalStream3bATI (GLenum, GLbyte, GLbyte, GLbyte);\nGLAPI void APIENTRY glNormalStream3bvATI (GLenum, const GLbyte *);\nGLAPI void APIENTRY glNormalStream3sATI (GLenum, GLshort, GLshort, GLshort);\nGLAPI void APIENTRY glNormalStream3svATI (GLenum, const GLshort *);\nGLAPI void APIENTRY glNormalStream3iATI (GLenum, GLint, GLint, GLint);\nGLAPI void APIENTRY glNormalStream3ivATI (GLenum, const GLint *);\nGLAPI void APIENTRY glNormalStream3fATI (GLenum, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glNormalStream3fvATI (GLenum, const GLfloat *);\nGLAPI void APIENTRY glNormalStream3dATI (GLenum, GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glNormalStream3dvATI (GLenum, const GLdouble *);\nGLAPI void APIENTRY glClientActiveVertexStreamATI (GLenum);\nGLAPI void APIENTRY glVertexBlendEnviATI (GLenum, GLint);\nGLAPI void APIENTRY glVertexBlendEnvfATI (GLenum, GLfloat);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_ATI_element_array\n#define GL_ATI_element_array 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glElementPointerATI (GLenum, const GLvoid *);\nGLAPI void APIENTRY glDrawElementArrayATI (GLenum, GLsizei);\nGLAPI void APIENTRY glDrawRangeElementArrayATI (GLenum, GLuint, GLuint, GLsizei);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLELEMENTPOINTERATIPROC) (GLenum type, const GLvoid *pointer);\ntypedef void (APIENTRYP PFNGLDRAWELEMENTARRAYATIPROC) (GLenum mode, GLsizei count);\ntypedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYATIPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count);\n#endif\n\n#ifndef GL_SUN_mesh_array\n#define GL_SUN_mesh_array 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDrawMeshArraysSUN (GLenum, GLint, GLsizei, GLsizei);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLDRAWMESHARRAYSSUNPROC) (GLenum mode, GLint first, GLsizei count, GLsizei width);\n#endif\n\n#ifndef GL_SUN_slice_accum\n#define GL_SUN_slice_accum 1\n#endif\n\n#ifndef GL_NV_multisample_filter_hint\n#define GL_NV_multisample_filter_hint 1\n#endif\n\n#ifndef GL_NV_depth_clamp\n#define GL_NV_depth_clamp 1\n#endif\n\n#ifndef GL_NV_occlusion_query\n#define GL_NV_occlusion_query 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glGenOcclusionQueriesNV (GLsizei, GLuint *);\nGLAPI void APIENTRY glDeleteOcclusionQueriesNV (GLsizei, const GLuint *);\nGLAPI GLboolean APIENTRY glIsOcclusionQueryNV (GLuint);\nGLAPI void APIENTRY glBeginOcclusionQueryNV (GLuint);\nGLAPI void APIENTRY glEndOcclusionQueryNV (void);\nGLAPI void APIENTRY glGetOcclusionQueryivNV (GLuint, GLenum, GLint *);\nGLAPI void APIENTRY glGetOcclusionQueryuivNV (GLuint, GLenum, GLuint *);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_NV_point_sprite\n#define GL_NV_point_sprite 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPointParameteriNV (GLenum, GLint);\nGLAPI void APIENTRY glPointParameterivNV (GLenum, const GLint *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLPOINTPARAMETERINVPROC) (GLenum pname, GLint param);\ntypedef void (APIENTRYP PFNGLPOINTPARAMETERIVNVPROC) (GLenum pname, const GLint *params);\n#endif\n\n#ifndef GL_NV_texture_shader3\n#define GL_NV_texture_shader3 1\n#endif\n\n#ifndef GL_NV_vertex_program1_1\n#define GL_NV_vertex_program1_1 1\n#endif\n\n#ifndef GL_EXT_shadow_funcs\n#define GL_EXT_shadow_funcs 1\n#endif\n\n#ifndef GL_EXT_stencil_two_side\n#define GL_EXT_stencil_two_side 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glActiveStencilFaceEXT (GLenum);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLACTIVESTENCILFACEEXTPROC) (GLenum face);\n#endif\n\n#ifndef GL_ATI_text_fragment_shader\n#define GL_ATI_text_fragment_shader 1\n#endif\n\n#ifndef GL_APPLE_client_storage\n#define GL_APPLE_client_storage 1\n#endif\n\n#ifndef GL_APPLE_element_array\n#define GL_APPLE_element_array 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glElementPointerAPPLE (GLenum, const GLvoid *);\nGLAPI void APIENTRY glDrawElementArrayAPPLE (GLenum, GLint, GLsizei);\nGLAPI void APIENTRY glDrawRangeElementArrayAPPLE (GLenum, GLuint, GLuint, GLint, GLsizei);\nGLAPI void APIENTRY glMultiDrawElementArrayAPPLE (GLenum, const GLint *, const GLsizei *, GLsizei);\nGLAPI void APIENTRY glMultiDrawRangeElementArrayAPPLE (GLenum, GLuint, GLuint, const GLint *, const GLsizei *, GLsizei);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLELEMENTPOINTERAPPLEPROC) (GLenum type, const GLvoid *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#endif\n\n#ifndef GL_APPLE_fence\n#define GL_APPLE_fence 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glGenFencesAPPLE (GLsizei, GLuint *);\nGLAPI void APIENTRY glDeleteFencesAPPLE (GLsizei, const GLuint *);\nGLAPI void APIENTRY glSetFenceAPPLE (GLuint);\nGLAPI GLboolean APIENTRY glIsFenceAPPLE (GLuint);\nGLAPI GLboolean APIENTRY glTestFenceAPPLE (GLuint);\nGLAPI void APIENTRY glFinishFenceAPPLE (GLuint);\nGLAPI GLboolean APIENTRY glTestObjectAPPLE (GLenum, GLuint);\nGLAPI void APIENTRY glFinishObjectAPPLE (GLenum, GLint);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_APPLE_vertex_array_object\n#define GL_APPLE_vertex_array_object 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBindVertexArrayAPPLE (GLuint);\nGLAPI void APIENTRY glDeleteVertexArraysAPPLE (GLsizei, const GLuint *);\nGLAPI void APIENTRY glGenVertexArraysAPPLE (GLsizei, const GLuint *);\nGLAPI GLboolean APIENTRY glIsVertexArrayAPPLE (GLuint);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLBINDVERTEXARRAYAPPLEPROC) (GLuint array);\ntypedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSAPPLEPROC) (GLsizei n, const GLuint *arrays);\ntypedef void (APIENTRYP PFNGLGENVERTEXARRAYSAPPLEPROC) (GLsizei n, const GLuint *arrays);\ntypedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYAPPLEPROC) (GLuint array);\n#endif\n\n#ifndef GL_APPLE_vertex_array_range\n#define GL_APPLE_vertex_array_range 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glVertexArrayRangeAPPLE (GLsizei, GLvoid *);\nGLAPI void APIENTRY glFlushVertexArrayRangeAPPLE (GLsizei, GLvoid *);\nGLAPI void APIENTRY glVertexArrayParameteriAPPLE (GLenum, GLint);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, GLvoid *pointer);\ntypedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, GLvoid *pointer);\ntypedef void (APIENTRYP PFNGLVERTEXARRAYPARAMETERIAPPLEPROC) (GLenum pname, GLint param);\n#endif\n\n#ifndef GL_APPLE_ycbcr_422\n#define GL_APPLE_ycbcr_422 1\n#endif\n\n#ifndef GL_S3_s3tc\n#define GL_S3_s3tc 1\n#endif\n\n#ifndef GL_ATI_draw_buffers\n#define GL_ATI_draw_buffers 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDrawBuffersATI (GLsizei, const GLenum *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLDRAWBUFFERSATIPROC) (GLsizei n, const GLenum *bufs);\n#endif\n\n#ifndef GL_ATI_pixel_format_float\n#define GL_ATI_pixel_format_float 1\n/* This is really a WGL extension, but defines some associated GL enums.\n * ATI does not export \"GL_ATI_pixel_format_float\" in the GL_EXTENSIONS string.\n */\n#endif\n\n#ifndef GL_ATI_texture_env_combine3\n#define GL_ATI_texture_env_combine3 1\n#endif\n\n#ifndef GL_ATI_texture_float\n#define GL_ATI_texture_float 1\n#endif\n\n#ifndef GL_NV_float_buffer\n#define GL_NV_float_buffer 1\n#endif\n\n#ifndef GL_NV_fragment_program\n#define GL_NV_fragment_program 1\n/* Some NV_fragment_program entry points are shared with ARB_vertex_program. */\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glProgramNamedParameter4fNV (GLuint, GLsizei, const GLubyte *, GLfloat, GLfloat, GLfloat, GLfloat);\nGLAPI void APIENTRY glProgramNamedParameter4dNV (GLuint, GLsizei, const GLubyte *, GLdouble, GLdouble, GLdouble, GLdouble);\nGLAPI void APIENTRY glProgramNamedParameter4fvNV (GLuint, GLsizei, const GLubyte *, const GLfloat *);\nGLAPI void APIENTRY glProgramNamedParameter4dvNV (GLuint, GLsizei, const GLubyte *, const GLdouble *);\nGLAPI void APIENTRY glGetProgramNamedParameterfvNV (GLuint, GLsizei, const GLubyte *, GLfloat *);\nGLAPI void APIENTRY glGetProgramNamedParameterdvNV (GLuint, GLsizei, const GLubyte *, GLdouble *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w);\ntypedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble x, GLdouble y, GLdouble z, GLdouble w);\ntypedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLfloat *v);\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#endif\n\n#ifndef GL_NV_half_float\n#define GL_NV_half_float 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glVertex2hNV (GLhalfNV, GLhalfNV);\nGLAPI void APIENTRY glVertex2hvNV (const GLhalfNV *);\nGLAPI void APIENTRY glVertex3hNV (GLhalfNV, GLhalfNV, GLhalfNV);\nGLAPI void APIENTRY glVertex3hvNV (const GLhalfNV *);\nGLAPI void APIENTRY glVertex4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);\nGLAPI void APIENTRY glVertex4hvNV (const GLhalfNV *);\nGLAPI void APIENTRY glNormal3hNV (GLhalfNV, GLhalfNV, GLhalfNV);\nGLAPI void APIENTRY glNormal3hvNV (const GLhalfNV *);\nGLAPI void APIENTRY glColor3hNV (GLhalfNV, GLhalfNV, GLhalfNV);\nGLAPI void APIENTRY glColor3hvNV (const GLhalfNV *);\nGLAPI void APIENTRY glColor4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);\nGLAPI void APIENTRY glColor4hvNV (const GLhalfNV *);\nGLAPI void APIENTRY glTexCoord1hNV (GLhalfNV);\nGLAPI void APIENTRY glTexCoord1hvNV (const GLhalfNV *);\nGLAPI void APIENTRY glTexCoord2hNV (GLhalfNV, GLhalfNV);\nGLAPI void APIENTRY glTexCoord2hvNV (const GLhalfNV *);\nGLAPI void APIENTRY glTexCoord3hNV (GLhalfNV, GLhalfNV, GLhalfNV);\nGLAPI void APIENTRY glTexCoord3hvNV (const GLhalfNV *);\nGLAPI void APIENTRY glTexCoord4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);\nGLAPI void APIENTRY glTexCoord4hvNV (const GLhalfNV *);\nGLAPI void APIENTRY glMultiTexCoord1hNV (GLenum, GLhalfNV);\nGLAPI void APIENTRY glMultiTexCoord1hvNV (GLenum, const GLhalfNV *);\nGLAPI void APIENTRY glMultiTexCoord2hNV (GLenum, GLhalfNV, GLhalfNV);\nGLAPI void APIENTRY glMultiTexCoord2hvNV (GLenum, const GLhalfNV *);\nGLAPI void APIENTRY glMultiTexCoord3hNV (GLenum, GLhalfNV, GLhalfNV, GLhalfNV);\nGLAPI void APIENTRY glMultiTexCoord3hvNV (GLenum, const GLhalfNV *);\nGLAPI void APIENTRY glMultiTexCoord4hNV (GLenum, GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);\nGLAPI void APIENTRY glMultiTexCoord4hvNV (GLenum, const GLhalfNV *);\nGLAPI void APIENTRY glFogCoordhNV (GLhalfNV);\nGLAPI void APIENTRY glFogCoordhvNV (const GLhalfNV *);\nGLAPI void APIENTRY glSecondaryColor3hNV (GLhalfNV, GLhalfNV, GLhalfNV);\nGLAPI void APIENTRY glSecondaryColor3hvNV (const GLhalfNV *);\nGLAPI void APIENTRY glVertexWeighthNV (GLhalfNV);\nGLAPI void APIENTRY glVertexWeighthvNV (const GLhalfNV *);\nGLAPI void APIENTRY glVertexAttrib1hNV (GLuint, GLhalfNV);\nGLAPI void APIENTRY glVertexAttrib1hvNV (GLuint, const GLhalfNV *);\nGLAPI void APIENTRY glVertexAttrib2hNV (GLuint, GLhalfNV, GLhalfNV);\nGLAPI void APIENTRY glVertexAttrib2hvNV (GLuint, const GLhalfNV *);\nGLAPI void APIENTRY glVertexAttrib3hNV (GLuint, GLhalfNV, GLhalfNV, GLhalfNV);\nGLAPI void APIENTRY glVertexAttrib3hvNV (GLuint, const GLhalfNV *);\nGLAPI void APIENTRY glVertexAttrib4hNV (GLuint, GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);\nGLAPI void APIENTRY glVertexAttrib4hvNV (GLuint, const GLhalfNV *);\nGLAPI void APIENTRY glVertexAttribs1hvNV (GLuint, GLsizei, const GLhalfNV *);\nGLAPI void APIENTRY glVertexAttribs2hvNV (GLuint, GLsizei, const GLhalfNV *);\nGLAPI void APIENTRY glVertexAttribs3hvNV (GLuint, GLsizei, const GLhalfNV *);\nGLAPI void APIENTRY glVertexAttribs4hvNV (GLuint, GLsizei, const GLhalfNV *);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_NV_pixel_data_range\n#define GL_NV_pixel_data_range 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPixelDataRangeNV (GLenum, GLsizei, GLvoid *);\nGLAPI void APIENTRY glFlushPixelDataRangeNV (GLenum);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLPIXELDATARANGENVPROC) (GLenum target, GLsizei length, GLvoid *pointer);\ntypedef void (APIENTRYP PFNGLFLUSHPIXELDATARANGENVPROC) (GLenum target);\n#endif\n\n#ifndef GL_NV_primitive_restart\n#define GL_NV_primitive_restart 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glPrimitiveRestartNV (void);\nGLAPI void APIENTRY glPrimitiveRestartIndexNV (GLuint);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLPRIMITIVERESTARTNVPROC) (void);\ntypedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXNVPROC) (GLuint index);\n#endif\n\n#ifndef GL_NV_texture_expand_normal\n#define GL_NV_texture_expand_normal 1\n#endif\n\n#ifndef GL_NV_vertex_program2\n#define GL_NV_vertex_program2 1\n#endif\n\n#ifndef GL_ATI_map_object_buffer\n#define GL_ATI_map_object_buffer 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI GLvoid* APIENTRY glMapObjectBufferATI (GLuint);\nGLAPI void APIENTRY glUnmapObjectBufferATI (GLuint);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef GLvoid* (APIENTRYP PFNGLMAPOBJECTBUFFERATIPROC) (GLuint buffer);\ntypedef void (APIENTRYP PFNGLUNMAPOBJECTBUFFERATIPROC) (GLuint buffer);\n#endif\n\n#ifndef GL_ATI_separate_stencil\n#define GL_ATI_separate_stencil 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glStencilOpSeparateATI (GLenum, GLenum, GLenum, GLenum);\nGLAPI void APIENTRY glStencilFuncSeparateATI (GLenum, GLenum, GLint, GLuint);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_ATI_vertex_attrib_array_object\n#define GL_ATI_vertex_attrib_array_object 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glVertexAttribArrayObjectATI (GLuint, GLint, GLenum, GLboolean, GLsizei, GLuint, GLuint);\nGLAPI void APIENTRY glGetVertexAttribArrayObjectfvATI (GLuint, GLenum, GLfloat *);\nGLAPI void APIENTRY glGetVertexAttribArrayObjectivATI (GLuint, GLenum, GLint *);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_OES_read_format\n#define GL_OES_read_format 1\n#endif\n\n#ifndef GL_EXT_depth_bounds_test\n#define GL_EXT_depth_bounds_test 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glDepthBoundsEXT (GLclampd, GLclampd);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLDEPTHBOUNDSEXTPROC) (GLclampd zmin, GLclampd zmax);\n#endif\n\n#ifndef GL_EXT_texture_mirror_clamp\n#define GL_EXT_texture_mirror_clamp 1\n#endif\n\n#ifndef GL_EXT_blend_equation_separate\n#define GL_EXT_blend_equation_separate 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glBlendEquationSeparateEXT (GLenum, GLenum);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEEXTPROC) (GLenum modeRGB, GLenum modeAlpha);\n#endif\n\n#ifndef GL_MESA_pack_invert\n#define GL_MESA_pack_invert 1\n#endif\n\n#ifndef GL_MESA_ycbcr_texture\n#define GL_MESA_ycbcr_texture 1\n#endif\n\n#ifndef GL_EXT_pixel_buffer_object\n#define GL_EXT_pixel_buffer_object 1\n#endif\n\n#ifndef GL_NV_fragment_program_option\n#define GL_NV_fragment_program_option 1\n#endif\n\n#ifndef GL_NV_fragment_program2\n#define GL_NV_fragment_program2 1\n#endif\n\n#ifndef GL_NV_vertex_program2_option\n#define GL_NV_vertex_program2_option 1\n#endif\n\n#ifndef GL_NV_vertex_program3\n#define GL_NV_vertex_program3 1\n#endif\n\n#ifndef GL_EXT_framebuffer_object\n#define GL_EXT_framebuffer_object 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI GLboolean APIENTRY glIsRenderbufferEXT (GLuint);\nGLAPI void APIENTRY glBindRenderbufferEXT (GLenum, GLuint);\nGLAPI void APIENTRY glDeleteRenderbuffersEXT (GLsizei, const GLuint *);\nGLAPI void APIENTRY glGenRenderbuffersEXT (GLsizei, GLuint *);\nGLAPI void APIENTRY glRenderbufferStorageEXT (GLenum, GLenum, GLsizei, GLsizei);\nGLAPI void APIENTRY glGetRenderbufferParameterivEXT (GLenum, GLenum, GLint *);\nGLAPI GLboolean APIENTRY glIsFramebufferEXT (GLuint);\nGLAPI void APIENTRY glBindFramebufferEXT (GLenum, GLuint);\nGLAPI void APIENTRY glDeleteFramebuffersEXT (GLsizei, const GLuint *);\nGLAPI void APIENTRY glGenFramebuffersEXT (GLsizei, GLuint *);\nGLAPI GLenum APIENTRY glCheckFramebufferStatusEXT (GLenum);\nGLAPI void APIENTRY glFramebufferTexture1DEXT (GLenum, GLenum, GLenum, GLuint, GLint);\nGLAPI void APIENTRY glFramebufferTexture2DEXT (GLenum, GLenum, GLenum, GLuint, GLint);\nGLAPI void APIENTRY glFramebufferTexture3DEXT (GLenum, GLenum, GLenum, GLuint, GLint, GLint);\nGLAPI void APIENTRY glFramebufferRenderbufferEXT (GLenum, GLenum, GLenum, GLuint);\nGLAPI void APIENTRY glGetFramebufferAttachmentParameterivEXT (GLenum, GLenum, GLenum, GLint *);\nGLAPI void APIENTRY glGenerateMipmapEXT (GLenum);\n#endif /* GL_GLEXT_PROTOTYPES */\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#endif\n\n#ifndef GL_GREMEDY_string_marker\n#define GL_GREMEDY_string_marker 1\n#ifdef GL_GLEXT_PROTOTYPES\nGLAPI void APIENTRY glStringMarkerGREMEDY (GLsizei, const GLvoid *);\n#endif /* GL_GLEXT_PROTOTYPES */\ntypedef void (APIENTRYP PFNGLSTRINGMARKERGREMEDYPROC) (GLsizei len, const GLvoid *string);\n#endif\n\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n#endif /* NO_SDL_GLEXT */\n/*@}*/\n"
  },
  {
    "path": "other/sdl/include/SDL_platform.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/** @file SDL_platform.h\n *  Try to get a standard set of platform defines\n */\n\n#ifndef _SDL_platform_h\n#define _SDL_platform_h\n\n#if defined(_AIX)\n#undef __AIX__\n#define __AIX__\t\t1\n#endif\n#if defined(__BEOS__)\n#undef __BEOS__\n#define __BEOS__\t1\n#endif\n#if defined(__HAIKU__)\n#undef __HAIKU__\n#define __HAIKU__ 1\n#endif\n#if defined(bsdi) || defined(__bsdi) || defined(__bsdi__)\n#undef __BSDI__\n#define __BSDI__\t1\n#endif\n#if defined(_arch_dreamcast)\n#undef __DREAMCAST__\n#define __DREAMCAST__\t1\n#endif\n#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)\n#undef __FREEBSD__\n#define __FREEBSD__\t1\n#endif\n#if defined(__HAIKU__)\n#undef __HAIKU__\n#define __HAIKU__\t1\n#endif\n#if defined(hpux) || defined(__hpux) || defined(__hpux__)\n#undef __HPUX__\n#define __HPUX__\t1\n#endif\n#if defined(sgi) || defined(__sgi) || defined(__sgi__) || defined(_SGI_SOURCE)\n#undef __IRIX__\n#define __IRIX__\t1\n#endif\n#if defined(linux) || defined(__linux) || defined(__linux__)\n#undef __LINUX__\n#define __LINUX__\t1\n#endif\n#if defined(__APPLE__)\n#undef __MACOSX__\n#define __MACOSX__\t1\n#elif defined(macintosh)\n#undef __MACOS__\n#define __MACOS__\t1\n#endif\n#if defined(__NetBSD__)\n#undef __NETBSD__\n#define __NETBSD__\t1\n#endif\n#if defined(__OpenBSD__)\n#undef __OPENBSD__\n#define __OPENBSD__\t1\n#endif\n#if defined(__OS2__)\n#undef __OS2__\n#define __OS2__\t\t1\n#endif\n#if defined(osf) || defined(__osf) || defined(__osf__) || defined(_OSF_SOURCE)\n#undef __OSF__\n#define __OSF__\t\t1\n#endif\n#if defined(__QNXNTO__)\n#undef __QNXNTO__\n#define __QNXNTO__\t1\n#endif\n#if defined(riscos) || defined(__riscos) || defined(__riscos__)\n#undef __RISCOS__\n#define __RISCOS__\t1\n#endif\n#if defined(__SVR4)\n#undef __SOLARIS__\n#define __SOLARIS__\t1\n#endif\n#if defined(WIN32) || defined(_WIN32)\n#undef __WIN32__\n#define __WIN32__\t1\n#endif\n\n#endif /* _SDL_platform_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_quit.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/** @file SDL_quit.h\n *  Include file for SDL quit event handling\n */\n\n#ifndef _SDL_quit_h\n#define _SDL_quit_h\n\n#include \"SDL_stdinc.h\"\n#include \"SDL_error.h\"\n\n/** @file SDL_quit.h\n *  An SDL_QUITEVENT is generated when the user tries to close the application\n *  window.  If it is ignored or filtered out, the window will remain open.\n *  If it is not ignored or filtered, it is queued normally and the window\n *  is allowed to close.  When the window is closed, screen updates will \n *  complete, but have no effect.\n *\n *  SDL_Init() installs signal handlers for SIGINT (keyboard interrupt)\n *  and SIGTERM (system termination request), if handlers do not already\n *  exist, that generate SDL_QUITEVENT events as well.  There is no way\n *  to determine the cause of an SDL_QUITEVENT, but setting a signal\n *  handler in your application will override the default generation of\n *  quit events for that signal.\n */\n\n/** @file SDL_quit.h\n *  There are no functions directly affecting the quit event \n */\n\n#define SDL_QuitRequested() \\\n        (SDL_PumpEvents(), SDL_PeepEvents(NULL,0,SDL_PEEKEVENT,SDL_QUITMASK))\n\n#endif /* _SDL_quit_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_rwops.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/** @file SDL_rwops.h\n *  This file provides a general interface for SDL to read and write\n *  data sources.  It can easily be extended to files, memory, etc.\n */\n\n#ifndef _SDL_rwops_h\n#define _SDL_rwops_h\n\n#include \"SDL_stdinc.h\"\n#include \"SDL_error.h\"\n\n#include \"begin_code.h\"\n/* Set up for C function definitions, even when using C++ */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/** This is the read/write operation structure -- very basic */\n\ntypedef struct SDL_RWops {\n\t/** Seek to 'offset' relative to whence, one of stdio's whence values:\n\t *\tSEEK_SET, SEEK_CUR, SEEK_END\n\t *  Returns the final offset in the data source.\n\t */\n\tint (SDLCALL *seek)(struct SDL_RWops *context, int offset, int whence);\n\n\t/** Read up to 'maxnum' objects each of size 'size' from the data\n\t *  source to the area pointed at by 'ptr'.\n\t *  Returns the number of objects read, or -1 if the read failed.\n\t */\n\tint (SDLCALL *read)(struct SDL_RWops *context, void *ptr, int size, int maxnum);\n\n\t/** Write exactly 'num' objects each of size 'objsize' from the area\n\t *  pointed at by 'ptr' to data source.\n\t *  Returns 'num', or -1 if the write failed.\n\t */\n\tint (SDLCALL *write)(struct SDL_RWops *context, const void *ptr, int size, int num);\n\n\t/** Close and free an allocated SDL_FSops structure */\n\tint (SDLCALL *close)(struct SDL_RWops *context);\n\n\tUint32 type;\n\tunion {\n#if defined(__WIN32__) && !defined(__SYMBIAN32__)\n\t    struct {\n\t\tint   append;\n\t\tvoid *h;\n\t\tstruct {\n\t\t    void *data;\n\t\t    int size;\n\t\t    int left;\n\t\t} buffer;\n\t    } win32io;\n#endif\n#ifdef HAVE_STDIO_H \n\t    struct {\n\t\tint autoclose;\n\t \tFILE *fp;\n\t    } stdio;\n#endif\n\t    struct {\n\t\tUint8 *base;\n\t \tUint8 *here;\n\t\tUint8 *stop;\n\t    } mem;\n\t    struct {\n\t\tvoid *data1;\n\t    } unknown;\n\t} hidden;\n\n} SDL_RWops;\n\n\n/** @name Functions to create SDL_RWops structures from various data sources */\n/*@{*/\n\nextern DECLSPEC SDL_RWops * SDLCALL SDL_RWFromFile(const char *file, const char *mode);\n\n#ifdef HAVE_STDIO_H\nextern DECLSPEC SDL_RWops * SDLCALL SDL_RWFromFP(FILE *fp, int autoclose);\n#endif\n\nextern DECLSPEC SDL_RWops * SDLCALL SDL_RWFromMem(void *mem, int size);\nextern DECLSPEC SDL_RWops * SDLCALL SDL_RWFromConstMem(const void *mem, int size);\n\nextern DECLSPEC SDL_RWops * SDLCALL SDL_AllocRW(void);\nextern DECLSPEC void SDLCALL SDL_FreeRW(SDL_RWops *area);\n\n/*@}*/\n\n/** @name Seek Reference Points */\n/*@{*/\n#define RW_SEEK_SET\t0\t/**< Seek from the beginning of data */\n#define RW_SEEK_CUR\t1\t/**< Seek relative to current read point */\n#define RW_SEEK_END\t2\t/**< Seek relative to the end of data */\n/*@}*/\n\n/** @name Macros to easily read and write from an SDL_RWops structure */\n/*@{*/\n#define SDL_RWseek(ctx, offset, whence)\t(ctx)->seek(ctx, offset, whence)\n#define SDL_RWtell(ctx)\t\t\t(ctx)->seek(ctx, 0, RW_SEEK_CUR)\n#define SDL_RWread(ctx, ptr, size, n)\t(ctx)->read(ctx, ptr, size, n)\n#define SDL_RWwrite(ctx, ptr, size, n)\t(ctx)->write(ctx, ptr, size, n)\n#define SDL_RWclose(ctx)\t\t(ctx)->close(ctx)\n/*@}*/\n\n/** @name Read an item of the specified endianness and return in native format */\n/*@{*/\nextern DECLSPEC Uint16 SDLCALL SDL_ReadLE16(SDL_RWops *src);\nextern DECLSPEC Uint16 SDLCALL SDL_ReadBE16(SDL_RWops *src);\nextern DECLSPEC Uint32 SDLCALL SDL_ReadLE32(SDL_RWops *src);\nextern DECLSPEC Uint32 SDLCALL SDL_ReadBE32(SDL_RWops *src);\nextern DECLSPEC Uint64 SDLCALL SDL_ReadLE64(SDL_RWops *src);\nextern DECLSPEC Uint64 SDLCALL SDL_ReadBE64(SDL_RWops *src);\n/*@}*/\n\n/** @name Write an item of native format to the specified endianness */\n/*@{*/\nextern DECLSPEC int SDLCALL SDL_WriteLE16(SDL_RWops *dst, Uint16 value);\nextern DECLSPEC int SDLCALL SDL_WriteBE16(SDL_RWops *dst, Uint16 value);\nextern DECLSPEC int SDLCALL SDL_WriteLE32(SDL_RWops *dst, Uint32 value);\nextern DECLSPEC int SDLCALL SDL_WriteBE32(SDL_RWops *dst, Uint32 value);\nextern DECLSPEC int SDLCALL SDL_WriteLE64(SDL_RWops *dst, Uint64 value);\nextern DECLSPEC int SDLCALL SDL_WriteBE64(SDL_RWops *dst, Uint64 value);\n/*@}*/\n\n/* Ends C function definitions when using C++ */\n#ifdef __cplusplus\n}\n#endif\n#include \"close_code.h\"\n\n#endif /* _SDL_rwops_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_stdinc.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/** @file SDL_stdinc.h\n *  This is a general header that includes C language support\n */\n\n#ifndef _SDL_stdinc_h\n#define _SDL_stdinc_h\n\n#include \"SDL_config.h\"\n\n\n#ifdef HAVE_SYS_TYPES_H\n#include <sys/types.h>\n#endif\n#ifdef HAVE_STDIO_H\n#include <stdio.h>\n#endif\n#if defined(STDC_HEADERS)\n# include <stdlib.h>\n# include <stddef.h>\n# include <stdarg.h>\n#else\n# if defined(HAVE_STDLIB_H)\n#  include <stdlib.h>\n# elif defined(HAVE_MALLOC_H)\n#  include <malloc.h>\n# endif\n# if defined(HAVE_STDDEF_H)\n#  include <stddef.h>\n# endif\n# if defined(HAVE_STDARG_H)\n#  include <stdarg.h>\n# endif\n#endif\n#ifdef HAVE_STRING_H\n# if !defined(STDC_HEADERS) && defined(HAVE_MEMORY_H)\n#  include <memory.h>\n# endif\n# include <string.h>\n#endif\n#ifdef HAVE_STRINGS_H\n# include <strings.h>\n#endif\n#if defined(HAVE_INTTYPES_H)\n# include <inttypes.h>\n#elif defined(HAVE_STDINT_H)\n# include <stdint.h>\n#endif\n#ifdef HAVE_CTYPE_H\n# include <ctype.h>\n#endif\n#if defined(HAVE_ICONV) && defined(HAVE_ICONV_H)\n# include <iconv.h>\n#endif\n\n/** The number of elements in an array */\n#define SDL_arraysize(array)\t(sizeof(array)/sizeof(array[0]))\n#define SDL_TABLESIZE(table)\tSDL_arraysize(table)\n\n/* Use proper C++ casts when compiled as C++ to be compatible with the option\n -Wold-style-cast of GCC (and -Werror=old-style-cast in GCC 4.2 and above. */\n#ifdef __cplusplus\n#define SDL_reinterpret_cast(type, expression) reinterpret_cast<type>(expression)\n#define SDL_static_cast(type, expression) static_cast<type>(expression)\n#else\n#define SDL_reinterpret_cast(type, expression) ((type)(expression))\n#define SDL_static_cast(type, expression) ((type)(expression))\n#endif\n\n/** @name Basic data types */\n/*@{*/\ntypedef enum {\n\tSDL_FALSE = 0,\n\tSDL_TRUE  = 1\n} SDL_bool;\n\ntypedef int8_t\t\tSint8;\ntypedef uint8_t\t\tUint8;\ntypedef int16_t\t\tSint16;\ntypedef uint16_t\tUint16;\ntypedef int32_t\t\tSint32;\ntypedef uint32_t\tUint32;\n\n#ifdef SDL_HAS_64BIT_TYPE\ntypedef int64_t\t\tSint64;\n#ifndef SYMBIAN32_GCCE\ntypedef uint64_t\tUint64;\n#endif\n#else\n/* This is really just a hack to prevent the compiler from complaining */\ntypedef struct {\n\tUint32 hi;\n\tUint32 lo;\n} Uint64, Sint64;\n#endif\n\n/*@}*/\n\n/** @name Make sure the types really have the right sizes */\n/*@{*/\n#define SDL_COMPILE_TIME_ASSERT(name, x)               \\\n       typedef int SDL_dummy_ ## name[(x) * 2 - 1]\n\nSDL_COMPILE_TIME_ASSERT(uint8, sizeof(Uint8) == 1);\nSDL_COMPILE_TIME_ASSERT(sint8, sizeof(Sint8) == 1);\nSDL_COMPILE_TIME_ASSERT(uint16, sizeof(Uint16) == 2);\nSDL_COMPILE_TIME_ASSERT(sint16, sizeof(Sint16) == 2);\nSDL_COMPILE_TIME_ASSERT(uint32, sizeof(Uint32) == 4);\nSDL_COMPILE_TIME_ASSERT(sint32, sizeof(Sint32) == 4);\nSDL_COMPILE_TIME_ASSERT(uint64, sizeof(Uint64) == 8);\nSDL_COMPILE_TIME_ASSERT(sint64, sizeof(Sint64) == 8);\n/*@}*/\n\n/** @name Enum Size Check\n *  Check to make sure enums are the size of ints, for structure packing.\n *  For both Watcom C/C++ and Borland C/C++ the compiler option that makes\n *  enums having the size of an int must be enabled.\n *  This is \"-b\" for Borland C/C++ and \"-ei\" for Watcom C/C++ (v11).\n */\n/* Enable enums always int in CodeWarrior (for MPW use \"-enum int\") */\n#ifdef __MWERKS__\n#pragma enumsalwaysint on\n#endif\n\ntypedef enum {\n\tDUMMY_ENUM_VALUE\n} SDL_DUMMY_ENUM;\n\n#ifndef __NDS__\nSDL_COMPILE_TIME_ASSERT(enum, sizeof(SDL_DUMMY_ENUM) == sizeof(int));\n#endif\n/*@}*/\n\n#include \"begin_code.h\"\n/* Set up for C function definitions, even when using C++ */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#ifdef HAVE_MALLOC\n#define SDL_malloc\tmalloc\n#else\nextern DECLSPEC void * SDLCALL SDL_malloc(size_t size);\n#endif\n\n#ifdef HAVE_CALLOC\n#define SDL_calloc\tcalloc\n#else\nextern DECLSPEC void * SDLCALL SDL_calloc(size_t nmemb, size_t size);\n#endif\n\n#ifdef HAVE_REALLOC\n#define SDL_realloc\trealloc\n#else\nextern DECLSPEC void * SDLCALL SDL_realloc(void *mem, size_t size);\n#endif\n\n#ifdef HAVE_FREE\n#define SDL_free\tfree\n#else\nextern DECLSPEC void SDLCALL SDL_free(void *mem);\n#endif\n\n#if defined(HAVE_ALLOCA) && !defined(alloca)\n# if defined(HAVE_ALLOCA_H)\n#  include <alloca.h>\n# elif defined(__GNUC__)\n#  define alloca __builtin_alloca\n# elif defined(_MSC_VER)\n#  include <malloc.h>\n#  define alloca _alloca\n# elif defined(__WATCOMC__)\n#  include <malloc.h>\n# elif defined(__BORLANDC__)\n#  include <malloc.h>\n# elif defined(__DMC__)\n#  include <stdlib.h>\n# elif defined(__AIX__)\n  #pragma alloca\n# elif defined(__MRC__)\n   void *alloca (unsigned);\n# else\n   char *alloca ();\n# endif\n#endif\n#ifdef HAVE_ALLOCA\n#define SDL_stack_alloc(type, count)    (type*)alloca(sizeof(type)*(count))\n#define SDL_stack_free(data)\n#else\n#define SDL_stack_alloc(type, count)    (type*)SDL_malloc(sizeof(type)*(count))\n#define SDL_stack_free(data)            SDL_free(data)\n#endif\n\n#ifdef HAVE_GETENV\n#define SDL_getenv\tgetenv\n#else\nextern DECLSPEC char * SDLCALL SDL_getenv(const char *name);\n#endif\n\n#ifdef HAVE_PUTENV\n#define SDL_putenv\tputenv\n#else\nextern DECLSPEC int SDLCALL SDL_putenv(const char *variable);\n#endif\n\n#ifdef HAVE_QSORT\n#define SDL_qsort\tqsort\n#else\nextern DECLSPEC void SDLCALL SDL_qsort(void *base, size_t nmemb, size_t size,\n           int (*compare)(const void *, const void *));\n#endif\n\n#ifdef HAVE_ABS\n#define SDL_abs\t\tabs\n#else\n#define SDL_abs(X)\t((X) < 0 ? -(X) : (X))\n#endif\n\n#define SDL_min(x, y)\t(((x) < (y)) ? (x) : (y))\n#define SDL_max(x, y)\t(((x) > (y)) ? (x) : (y))\n\n#ifdef HAVE_CTYPE_H\n#define SDL_isdigit(X)  isdigit(X)\n#define SDL_isspace(X)  isspace(X)\n#define SDL_toupper(X)  toupper(X)\n#define SDL_tolower(X)  tolower(X)\n#else\n#define SDL_isdigit(X)  (((X) >= '0') && ((X) <= '9'))\n#define SDL_isspace(X)  (((X) == ' ') || ((X) == '\\t') || ((X) == '\\r') || ((X) == '\\n'))\n#define SDL_toupper(X)  (((X) >= 'a') && ((X) <= 'z') ? ('A'+((X)-'a')) : (X))\n#define SDL_tolower(X)  (((X) >= 'A') && ((X) <= 'Z') ? ('a'+((X)-'A')) : (X))\n#endif\n\n#ifdef HAVE_MEMSET\n#define SDL_memset      memset\n#else\nextern DECLSPEC void * SDLCALL SDL_memset(void *dst, int c, size_t len);\n#endif\n\n#if defined(__GNUC__) && defined(i386)\n#define SDL_memset4(dst, val, len)\t\t\t\t\\\ndo {\t\t\t\t\t\t\t\t\\\n\tint u0, u1, u2;\t\t\t\t\t\t\\\n\t__asm__ __volatile__ (\t\t\t\t\t\\\n\t\t\"cld\\n\\t\"\t\t\t\t\t\\\n\t\t\"rep ; stosl\\n\\t\"\t\t\t\t\\\n\t\t: \"=&D\" (u0), \"=&a\" (u1), \"=&c\" (u2)\t\t\\\n\t\t: \"0\" (dst), \"1\" (val), \"2\" (SDL_static_cast(Uint32, len))\t\\\n\t\t: \"memory\" );\t\t\t\t\t\\\n} while(0)\n#endif\n#ifndef SDL_memset4\n#define SDL_memset4(dst, val, len)\t\t\\\ndo {\t\t\t\t\t\t\\\n\tunsigned _count = (len);\t\t\\\n\tunsigned _n = (_count + 3) / 4;\t\t\\\n\tUint32 *_p = SDL_static_cast(Uint32 *, dst);\t\\\n\tUint32 _val = (val);\t\t\t\\\n\tif (len == 0) break;\t\t\t\\\n        switch (_count % 4) {\t\t\t\\\n        case 0: do {    *_p++ = _val;\t\t\\\n        case 3:         *_p++ = _val;\t\t\\\n        case 2:         *_p++ = _val;\t\t\\\n        case 1:         *_p++ = _val;\t\t\\\n\t\t} while ( --_n );\t\t\\\n\t}\t\t\t\t\t\\\n} while(0)\n#endif\n\n/* We can count on memcpy existing on Mac OS X and being well-tuned. */\n#if defined(__MACH__) && defined(__APPLE__)\n#define SDL_memcpy(dst, src, len) memcpy(dst, src, len)\n#elif defined(__GNUC__) && defined(i386)\n#define SDL_memcpy(dst, src, len)\t\t\t\t\t  \\\ndo {\t\t\t\t\t\t\t\t\t  \\\n\tint u0, u1, u2;\t\t\t\t\t\t  \t  \\\n\t__asm__ __volatile__ (\t\t\t\t\t\t  \\\n\t\t\"cld\\n\\t\"\t\t\t\t\t\t  \\\n\t\t\"rep ; movsl\\n\\t\"\t\t\t\t\t  \\\n\t\t\"testb $2,%b4\\n\\t\"\t\t\t\t\t  \\\n\t\t\"je 1f\\n\\t\"\t\t\t\t\t\t  \\\n\t\t\"movsw\\n\"\t\t\t\t\t\t  \\\n\t\t\"1:\\ttestb $1,%b4\\n\\t\"\t\t\t\t\t  \\\n\t\t\"je 2f\\n\\t\"\t\t\t\t\t\t  \\\n\t\t\"movsb\\n\"\t\t\t\t\t\t  \\\n\t\t\"2:\"\t\t\t\t\t\t\t  \\\n\t\t: \"=&c\" (u0), \"=&D\" (u1), \"=&S\" (u2)\t\t\t  \\\n\t\t: \"0\" (SDL_static_cast(unsigned, len)/4), \"q\" (len), \"1\" (dst),\"2\" (src) \\\n\t\t: \"memory\" );\t\t\t\t\t\t  \\\n} while(0)\n#endif\n#ifndef SDL_memcpy\n#ifdef HAVE_MEMCPY\n#define SDL_memcpy      memcpy\n#elif defined(HAVE_BCOPY)\n#define SDL_memcpy(d, s, n)\tbcopy((s), (d), (n))\n#else\nextern DECLSPEC void * SDLCALL SDL_memcpy(void *dst, const void *src, size_t len);\n#endif\n#endif\n\n/* We can count on memcpy existing on Mac OS X and being well-tuned. */\n#if defined(__MACH__) && defined(__APPLE__)\n#define SDL_memcpy4(dst, src, len) memcpy(dst, src, (len)*4)\n#elif defined(__GNUC__) && defined(i386)\n#define SDL_memcpy4(dst, src, len)\t\t\t\t\\\ndo {\t\t\t\t\t\t\t\t\\\n\tint ecx, edi, esi;\t\t\t\t\t\\\n\t__asm__ __volatile__ (\t\t\t\t\t\\\n\t\t\"cld\\n\\t\"\t\t\t\t\t\\\n\t\t\"rep ; movsl\"\t\t\t\t\t\\\n\t\t: \"=&c\" (ecx), \"=&D\" (edi), \"=&S\" (esi)\t\t\\\n\t\t: \"0\" (SDL_static_cast(unsigned, len)), \"1\" (dst), \"2\" (src)\t\\\n\t\t: \"memory\" );\t\t\t\t\t\\\n} while(0)\n#endif\n#ifndef SDL_memcpy4\n#define SDL_memcpy4(dst, src, len)\tSDL_memcpy(dst, src, (len) << 2)\n#endif\n\n#if defined(__GNUC__) && defined(i386)\n#define SDL_revcpy(dst, src, len)\t\t\t\\\ndo {\t\t\t\t\t\t\t\\\n\tint u0, u1, u2;\t\t\t\t\t\\\n\tchar *dstp = SDL_static_cast(char *, dst);\t\\\n\tchar *srcp = SDL_static_cast(char *, src);\t\\\n\tint n = (len);\t\t\t\t\t\\\n\tif ( n >= 4 ) {\t\t\t\t\t\\\n\t__asm__ __volatile__ (\t\t\t\t\\\n\t\t\"std\\n\\t\"\t\t\t\t\\\n\t\t\"rep ; movsl\\n\\t\"\t\t\t\\\n\t\t\"cld\\n\\t\"\t\t\t\t\\\n\t\t: \"=&c\" (u0), \"=&D\" (u1), \"=&S\" (u2)\t\\\n\t\t: \"0\" (n >> 2),\t\t\t\t\\\n\t\t  \"1\" (dstp+(n-4)), \"2\" (srcp+(n-4))\t\\\n\t\t: \"memory\" );\t\t\t\t\\\n\t}\t\t\t\t\t\t\\\n\tswitch (n & 3) {\t\t\t\t\\\n\t\tcase 3: dstp[2] = srcp[2];\t\t\\\n\t\tcase 2: dstp[1] = srcp[1];\t\t\\\n\t\tcase 1: dstp[0] = srcp[0];\t\t\\\n\t\t\tbreak;\t\t\t\t\\\n\t\tdefault:\t\t\t\t\\\n\t\t\tbreak;\t\t\t\t\\\n\t}\t\t\t\t\t\t\\\n} while(0)\n#endif\n#ifndef SDL_revcpy\nextern DECLSPEC void * SDLCALL SDL_revcpy(void *dst, const void *src, size_t len);\n#endif\n\n#ifdef HAVE_MEMMOVE\n#define SDL_memmove     memmove\n#elif defined(HAVE_BCOPY)\n#define SDL_memmove(d, s, n)\tbcopy((s), (d), (n))\n#else\n#define SDL_memmove(dst, src, len)\t\t\t\\\ndo {\t\t\t\t\t\t\t\\\n\tif ( dst < src ) {\t\t\t\t\\\n\t\tSDL_memcpy(dst, src, len);\t\t\\\n\t} else {\t\t\t\t\t\\\n\t\tSDL_revcpy(dst, src, len);\t\t\\\n\t}\t\t\t\t\t\t\\\n} while(0)\n#endif\n\n#ifdef HAVE_MEMCMP\n#define SDL_memcmp      memcmp\n#else\nextern DECLSPEC int SDLCALL SDL_memcmp(const void *s1, const void *s2, size_t len);\n#endif\n\n#ifdef HAVE_STRLEN\n#define SDL_strlen      strlen\n#else\nextern DECLSPEC size_t SDLCALL SDL_strlen(const char *string);\n#endif\n\n#ifdef HAVE_STRLCPY\n#define SDL_strlcpy     strlcpy\n#else\nextern DECLSPEC size_t SDLCALL SDL_strlcpy(char *dst, const char *src, size_t maxlen);\n#endif\n\n#ifdef HAVE_STRLCAT\n#define SDL_strlcat    strlcat\n#else\nextern DECLSPEC size_t SDLCALL SDL_strlcat(char *dst, const char *src, size_t maxlen);\n#endif\n\n#ifdef HAVE_STRDUP\n#define SDL_strdup     strdup\n#else\nextern DECLSPEC char * SDLCALL SDL_strdup(const char *string);\n#endif\n\n#ifdef HAVE__STRREV\n#define SDL_strrev      _strrev\n#else\nextern DECLSPEC char * SDLCALL SDL_strrev(char *string);\n#endif\n\n#ifdef HAVE__STRUPR\n#define SDL_strupr      _strupr\n#else\nextern DECLSPEC char * SDLCALL SDL_strupr(char *string);\n#endif\n\n#ifdef HAVE__STRLWR\n#define SDL_strlwr      _strlwr\n#else\nextern DECLSPEC char * SDLCALL SDL_strlwr(char *string);\n#endif\n\n#ifdef HAVE_STRCHR\n#define SDL_strchr      strchr\n#elif defined(HAVE_INDEX)\n#define SDL_strchr      index\n#else\nextern DECLSPEC char * SDLCALL SDL_strchr(const char *string, int c);\n#endif\n\n#ifdef HAVE_STRRCHR\n#define SDL_strrchr     strrchr\n#elif defined(HAVE_RINDEX)\n#define SDL_strrchr     rindex\n#else\nextern DECLSPEC char * SDLCALL SDL_strrchr(const char *string, int c);\n#endif\n\n#ifdef HAVE_STRSTR\n#define SDL_strstr      strstr\n#else\nextern DECLSPEC char * SDLCALL SDL_strstr(const char *haystack, const char *needle);\n#endif\n\n#ifdef HAVE_ITOA\n#define SDL_itoa        itoa\n#else\n#define SDL_itoa(value, string, radix)\tSDL_ltoa((long)value, string, radix)\n#endif\n\n#ifdef HAVE__LTOA\n#define SDL_ltoa        _ltoa\n#else\nextern DECLSPEC char * SDLCALL SDL_ltoa(long value, char *string, int radix);\n#endif\n\n#ifdef HAVE__UITOA\n#define SDL_uitoa       _uitoa\n#else\n#define SDL_uitoa(value, string, radix)\tSDL_ultoa((long)value, string, radix)\n#endif\n\n#ifdef HAVE__ULTOA\n#define SDL_ultoa       _ultoa\n#else\nextern DECLSPEC char * SDLCALL SDL_ultoa(unsigned long value, char *string, int radix);\n#endif\n\n#ifdef HAVE_STRTOL\n#define SDL_strtol      strtol\n#else\nextern DECLSPEC long SDLCALL SDL_strtol(const char *string, char **endp, int base);\n#endif\n\n#ifdef HAVE_STRTOUL\n#define SDL_strtoul      strtoul\n#else\nextern DECLSPEC unsigned long SDLCALL SDL_strtoul(const char *string, char **endp, int base);\n#endif\n\n#ifdef SDL_HAS_64BIT_TYPE\n\n#ifdef HAVE__I64TOA\n#define SDL_lltoa       _i64toa\n#else\nextern DECLSPEC char* SDLCALL SDL_lltoa(Sint64 value, char *string, int radix);\n#endif\n\n#ifdef HAVE__UI64TOA\n#define SDL_ulltoa      _ui64toa\n#else\nextern DECLSPEC char* SDLCALL SDL_ulltoa(Uint64 value, char *string, int radix);\n#endif\n\n#ifdef HAVE_STRTOLL\n#define SDL_strtoll     strtoll\n#else\nextern DECLSPEC Sint64 SDLCALL SDL_strtoll(const char *string, char **endp, int base);\n#endif\n\n#ifdef HAVE_STRTOULL\n#define SDL_strtoull     strtoull\n#else\nextern DECLSPEC Uint64 SDLCALL SDL_strtoull(const char *string, char **endp, int base);\n#endif\n\n#endif /* SDL_HAS_64BIT_TYPE */\n\n#ifdef HAVE_STRTOD\n#define SDL_strtod      strtod\n#else\nextern DECLSPEC double SDLCALL SDL_strtod(const char *string, char **endp);\n#endif\n\n#ifdef HAVE_ATOI\n#define SDL_atoi        atoi\n#else\n#define SDL_atoi(X)     SDL_strtol(X, NULL, 0)\n#endif\n\n#ifdef HAVE_ATOF\n#define SDL_atof        atof\n#else\n#define SDL_atof(X)     SDL_strtod(X, NULL)\n#endif\n\n#ifdef HAVE_STRCMP\n#define SDL_strcmp      strcmp\n#else\nextern DECLSPEC int SDLCALL SDL_strcmp(const char *str1, const char *str2);\n#endif\n\n#ifdef HAVE_STRNCMP\n#define SDL_strncmp     strncmp\n#else\nextern DECLSPEC int SDLCALL SDL_strncmp(const char *str1, const char *str2, size_t maxlen);\n#endif\n\n#ifdef HAVE_STRCASECMP\n#define SDL_strcasecmp  strcasecmp\n#elif defined(HAVE__STRICMP)\n#define SDL_strcasecmp  _stricmp\n#else\nextern DECLSPEC int SDLCALL SDL_strcasecmp(const char *str1, const char *str2);\n#endif\n\n#ifdef HAVE_STRNCASECMP\n#define SDL_strncasecmp strncasecmp\n#elif defined(HAVE__STRNICMP)\n#define SDL_strncasecmp _strnicmp\n#else\nextern DECLSPEC int SDLCALL SDL_strncasecmp(const char *str1, const char *str2, size_t maxlen);\n#endif\n\n#ifdef HAVE_SSCANF\n#define SDL_sscanf      sscanf\n#else\nextern DECLSPEC int SDLCALL SDL_sscanf(const char *text, const char *fmt, ...);\n#endif\n\n#ifdef HAVE_SNPRINTF\n#define SDL_snprintf    snprintf\n#else\nextern DECLSPEC int SDLCALL SDL_snprintf(char *text, size_t maxlen, const char *fmt, ...);\n#endif\n\n#ifdef HAVE_VSNPRINTF\n#define SDL_vsnprintf   vsnprintf\n#else\nextern DECLSPEC int SDLCALL SDL_vsnprintf(char *text, size_t maxlen, const char *fmt, va_list ap);\n#endif\n\n/** @name SDL_ICONV Error Codes\n *  The SDL implementation of iconv() returns these error codes \n */\n/*@{*/\n#define SDL_ICONV_ERROR\t\t(size_t)-1\n#define SDL_ICONV_E2BIG\t\t(size_t)-2\n#define SDL_ICONV_EILSEQ\t(size_t)-3\n#define SDL_ICONV_EINVAL\t(size_t)-4\n/*@}*/\n\n#if defined(HAVE_ICONV) && defined(HAVE_ICONV_H)\n#define SDL_iconv_t     iconv_t\n#define SDL_iconv_open  iconv_open\n#define SDL_iconv_close iconv_close\n#else\ntypedef struct _SDL_iconv_t *SDL_iconv_t;\nextern DECLSPEC SDL_iconv_t SDLCALL SDL_iconv_open(const char *tocode, const char *fromcode);\nextern DECLSPEC int SDLCALL SDL_iconv_close(SDL_iconv_t cd);\n#endif\nextern DECLSPEC size_t SDLCALL SDL_iconv(SDL_iconv_t cd, const char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft);\n/** This function converts a string between encodings in one pass, returning a\n *  string that must be freed with SDL_free() or NULL on error.\n */\nextern DECLSPEC char * SDLCALL SDL_iconv_string(const char *tocode, const char *fromcode, const char *inbuf, size_t inbytesleft);\n#define SDL_iconv_utf8_locale(S)\tSDL_iconv_string(\"\", \"UTF-8\", S, SDL_strlen(S)+1)\n#define SDL_iconv_utf8_ucs2(S)\t\t(Uint16 *)SDL_iconv_string(\"UCS-2\", \"UTF-8\", S, SDL_strlen(S)+1)\n#define SDL_iconv_utf8_ucs4(S)\t\t(Uint32 *)SDL_iconv_string(\"UCS-4\", \"UTF-8\", S, SDL_strlen(S)+1)\n\n/* Ends C function definitions when using C++ */\n#ifdef __cplusplus\n}\n#endif\n#include \"close_code.h\"\n\n#endif /* _SDL_stdinc_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_syswm.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/** @file SDL_syswm.h\n *  Include file for SDL custom system window manager hooks\n */\n\n#ifndef _SDL_syswm_h\n#define _SDL_syswm_h\n\n#include \"SDL_stdinc.h\"\n#include \"SDL_error.h\"\n#include \"SDL_version.h\"\n\n#include \"begin_code.h\"\n/* Set up for C function definitions, even when using C++ */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/** @file SDL_syswm.h\n *  Your application has access to a special type of event 'SDL_SYSWMEVENT',\n *  which contains window-manager specific information and arrives whenever\n *  an unhandled window event occurs.  This event is ignored by default, but\n *  you can enable it with SDL_EventState()\n */\n#ifdef SDL_PROTOTYPES_ONLY\nstruct SDL_SysWMinfo;\ntypedef struct SDL_SysWMinfo SDL_SysWMinfo;\n#else\n\n/* This is the structure for custom window manager events */\n#if defined(SDL_VIDEO_DRIVER_X11)\n#if defined(__APPLE__) && defined(__MACH__)\n/* conflicts with Quickdraw.h */\n#define Cursor X11Cursor\n#endif\n\n#include <X11/Xlib.h>\n#include <X11/Xatom.h>\n\n#if defined(__APPLE__) && defined(__MACH__)\n/* matches the re-define above */\n#undef Cursor\n#endif\n\n/** These are the various supported subsystems under UNIX */\ntypedef enum {\n\tSDL_SYSWM_X11\n} SDL_SYSWM_TYPE;\n\n/** The UNIX custom event structure */\nstruct SDL_SysWMmsg {\n\tSDL_version version;\n\tSDL_SYSWM_TYPE subsystem;\n\tunion {\n\t    XEvent xevent;\n\t} event;\n};\n\n/** The UNIX custom window manager information structure.\n *  When this structure is returned, it holds information about which\n *  low level system it is using, and will be one of SDL_SYSWM_TYPE.\n */\ntypedef struct SDL_SysWMinfo {\n\tSDL_version version;\n\tSDL_SYSWM_TYPE subsystem;\n\tunion {\n\t    struct {\n\t    \tDisplay *display;\t/**< The X11 display */\n\t    \tWindow window;\t\t/**< The X11 display window */\n\t\t/** These locking functions should be called around\n                 *  any X11 functions using the display variable, \n                 *  but not the gfxdisplay variable.\n                 *  They lock the event thread, so should not be\n\t\t *  called around event functions or from event filters.\n\t\t */\n                /*@{*/\n\t\tvoid (*lock_func)(void);\n\t\tvoid (*unlock_func)(void);\n                /*@}*/\n\n\t\t/** @name Introduced in SDL 1.0.2 */\n                /*@{*/\n\t    \tWindow fswindow;\t/**< The X11 fullscreen window */\n\t    \tWindow wmwindow;\t/**< The X11 managed input window */\n                /*@}*/\n\n\t\t/** @name Introduced in SDL 1.2.12 */\n                /*@{*/\n\t\tDisplay *gfxdisplay;\t/**< The X11 display to which rendering is done */\n                /*@}*/\n\t    } x11;\n\t} info;\n} SDL_SysWMinfo;\n\n#elif defined(SDL_VIDEO_DRIVER_NANOX)\n#include <microwin/nano-X.h>\n\n/** The generic custom event structure */\nstruct SDL_SysWMmsg {\n\tSDL_version version;\n\tint data;\n};\n\n/** The windows custom window manager information structure */\ntypedef struct SDL_SysWMinfo {\n\tSDL_version version ;\n\tGR_WINDOW_ID window ;\t/* The display window */\n} SDL_SysWMinfo;\n\n#elif defined(SDL_VIDEO_DRIVER_WINDIB) || defined(SDL_VIDEO_DRIVER_DDRAW) || defined(SDL_VIDEO_DRIVER_GAPI)\n#define WIN32_LEAN_AND_MEAN\n#include <windows.h>\n\n/** The windows custom event structure */\nstruct SDL_SysWMmsg {\n\tSDL_version version;\n\tHWND hwnd;\t\t\t/**< The window for the message */\n\tUINT msg;\t\t\t/**< The type of message */\n\tWPARAM wParam;\t\t\t/**< WORD message parameter */\n\tLPARAM lParam;\t\t\t/**< LONG message parameter */\n};\n\n/** The windows custom window manager information structure */\ntypedef struct SDL_SysWMinfo {\n\tSDL_version version;\n\tHWND window;\t\t\t/**< The Win32 display window */\n\tHGLRC hglrc;\t\t\t/**< The OpenGL context, if any */\n} SDL_SysWMinfo;\n\n#elif defined(SDL_VIDEO_DRIVER_RISCOS)\n\n/** RISC OS custom event structure */\nstruct SDL_SysWMmsg {\n\tSDL_version version;\n\tint eventCode;\t\t/**< The window for the message */\n\tint pollBlock[64];\n};\n\n/** The RISC OS custom window manager information structure */\ntypedef struct SDL_SysWMinfo {\n\tSDL_version version;\n\tint wimpVersion;    /**< Wimp version running under */\n\tint taskHandle;     /**< The RISC OS task handle */\n\tint window;\t\t/**< The RISC OS display window */\n} SDL_SysWMinfo;\n\n#elif defined(SDL_VIDEO_DRIVER_PHOTON)\n#include <sys/neutrino.h>\n#include <Ph.h>\n\n/** The QNX custom event structure */\nstruct SDL_SysWMmsg {\n\tSDL_version version;\n\tint data;\n};\n\n/** The QNX custom window manager information structure */\ntypedef struct SDL_SysWMinfo {\n\tSDL_version version;\n\tint data;\n} SDL_SysWMinfo;\n\n#else\n\n/** The generic custom event structure */\nstruct SDL_SysWMmsg {\n\tSDL_version version;\n\tint data;\n};\n\n/** The generic custom window manager information structure */\ntypedef struct SDL_SysWMinfo {\n\tSDL_version version;\n\tint data;\n} SDL_SysWMinfo;\n\n#endif /* video driver type */\n\n#endif /* SDL_PROTOTYPES_ONLY */\n\n/* Function prototypes */\n/**\n * This function gives you custom hooks into the window manager information.\n * It fills the structure pointed to by 'info' with custom information and\n * returns 1 if the function is implemented.  If it's not implemented, or\n * the version member of the 'info' structure is invalid, it returns 0. \n *\n * You typically use this function like this:\n * @code\n * SDL_SysWMInfo info;\n * SDL_VERSION(&info.version);\n * if ( SDL_GetWMInfo(&info) ) { ... }\n * @endcode\n */\nextern DECLSPEC int SDLCALL SDL_GetWMInfo(SDL_SysWMinfo *info);\n\n\n/* Ends C function definitions when using C++ */\n#ifdef __cplusplus\n}\n#endif\n#include \"close_code.h\"\n\n#endif /* _SDL_syswm_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_thread.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n#ifndef _SDL_thread_h\n#define _SDL_thread_h\n\n/** @file SDL_thread.h\n *  Header for the SDL thread management routines \n *\n *  @note These are independent of the other SDL routines.\n */\n\n#include \"SDL_stdinc.h\"\n#include \"SDL_error.h\"\n\n/* Thread synchronization primitives */\n#include \"SDL_mutex.h\"\n\n#include \"begin_code.h\"\n/* Set up for C function definitions, even when using C++ */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/** The SDL thread structure, defined in SDL_thread.c */\nstruct SDL_Thread;\ntypedef struct SDL_Thread SDL_Thread;\n\n/** Create a thread */\n#if ((defined(__WIN32__) && !defined(HAVE_LIBC)) || defined(__OS2__)) &&  !defined(__SYMBIAN32__)\n/**\n *  We compile SDL into a DLL on OS/2. This means, that it's the DLL which\n *  creates a new thread for the calling process with the SDL_CreateThread()\n *  API. There is a problem with this, that only the RTL of the SDL.DLL will\n *  be initialized for those threads, and not the RTL of the calling application!\n *  To solve this, we make a little hack here.\n *  We'll always use the caller's _beginthread() and _endthread() APIs to\n *  start a new thread. This way, if it's the SDL.DLL which uses this API,\n *  then the RTL of SDL.DLL will be used to create the new thread, and if it's\n *  the application, then the RTL of the application will be used.\n *  So, in short:\n *  Always use the _beginthread() and _endthread() of the calling runtime library!\n */\n#define SDL_PASSED_BEGINTHREAD_ENDTHREAD\n#ifndef _WIN32_WCE\n#include <process.h> /* This has _beginthread() and _endthread() defined! */\n#endif\n\n#ifdef __OS2__\ntypedef int (*pfnSDL_CurrentBeginThread)(void (*func)(void *), void *, unsigned, void *arg); \ntypedef void (*pfnSDL_CurrentEndThread)(void);\n#elif __GNUC__\ntypedef unsigned long (__cdecl *pfnSDL_CurrentBeginThread) (void *, unsigned,\n        unsigned (__stdcall *func)(void *), void *arg, \n        unsigned, unsigned *threadID);\ntypedef void (__cdecl *pfnSDL_CurrentEndThread)(unsigned code);\n#else\ntypedef uintptr_t (__cdecl *pfnSDL_CurrentBeginThread) (void *, unsigned,\n        unsigned (__stdcall *func)(void *), void *arg, \n        unsigned, unsigned *threadID);\ntypedef void (__cdecl *pfnSDL_CurrentEndThread)(unsigned code);\n#endif\n\nextern DECLSPEC SDL_Thread * SDLCALL SDL_CreateThread(int (SDLCALL *fn)(void *), void *data, pfnSDL_CurrentBeginThread pfnBeginThread, pfnSDL_CurrentEndThread pfnEndThread);\n\n#ifdef __OS2__\n#define SDL_CreateThread(fn, data) SDL_CreateThread(fn, data, _beginthread, _endthread)\n#elif defined(_WIN32_WCE)\n#define SDL_CreateThread(fn, data) SDL_CreateThread(fn, data, NULL, NULL)\n#else\n#define SDL_CreateThread(fn, data) SDL_CreateThread(fn, data, _beginthreadex, _endthreadex)\n#endif\n#else\nextern DECLSPEC SDL_Thread * SDLCALL SDL_CreateThread(int (SDLCALL *fn)(void *), void *data);\n#endif\n\n/** Get the 32-bit thread identifier for the current thread */\nextern DECLSPEC Uint32 SDLCALL SDL_ThreadID(void);\n\n/** Get the 32-bit thread identifier for the specified thread,\n *  equivalent to SDL_ThreadID() if the specified thread is NULL.\n */\nextern DECLSPEC Uint32 SDLCALL SDL_GetThreadID(SDL_Thread *thread);\n\n/** Wait for a thread to finish.\n *  The return code for the thread function is placed in the area\n *  pointed to by 'status', if 'status' is not NULL.\n */\nextern DECLSPEC void SDLCALL SDL_WaitThread(SDL_Thread *thread, int *status);\n\n/** Forcefully kill a thread without worrying about its state */\nextern DECLSPEC void SDLCALL SDL_KillThread(SDL_Thread *thread);\n\n\n/* Ends C function definitions when using C++ */\n#ifdef __cplusplus\n}\n#endif\n#include \"close_code.h\"\n\n#endif /* _SDL_thread_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_timer.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n#ifndef _SDL_timer_h\n#define _SDL_timer_h\n\n/** @file SDL_timer.h\n *  Header for the SDL time management routines\n */\n\n#include \"SDL_stdinc.h\"\n#include \"SDL_error.h\"\n\n#include \"begin_code.h\"\n/* Set up for C function definitions, even when using C++ */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/** This is the OS scheduler timeslice, in milliseconds */\n#define SDL_TIMESLICE\t\t10\n\n/** This is the maximum resolution of the SDL timer on all platforms */\n#define TIMER_RESOLUTION\t10\t/**< Experimentally determined */\n\n/**\n * Get the number of milliseconds since the SDL library initialization.\n * Note that this value wraps if the program runs for more than ~49 days.\n */ \nextern DECLSPEC Uint32 SDLCALL SDL_GetTicks(void);\n\n/** Wait a specified number of milliseconds before returning */\nextern DECLSPEC void SDLCALL SDL_Delay(Uint32 ms);\n\n/** Function prototype for the timer callback function */\ntypedef Uint32 (SDLCALL *SDL_TimerCallback)(Uint32 interval);\n\n/**\n * Set a callback to run after the specified number of milliseconds has\n * elapsed. The callback function is passed the current timer interval\n * and returns the next timer interval.  If the returned value is the \n * same as the one passed in, the periodic alarm continues, otherwise a\n * new alarm is scheduled.  If the callback returns 0, the periodic alarm\n * is cancelled.\n *\n * To cancel a currently running timer, call SDL_SetTimer(0, NULL);\n *\n * The timer callback function may run in a different thread than your\n * main code, and so shouldn't call any functions from within itself.\n *\n * The maximum resolution of this timer is 10 ms, which means that if\n * you request a 16 ms timer, your callback will run approximately 20 ms\n * later on an unloaded system.  If you wanted to set a flag signaling\n * a frame update at 30 frames per second (every 33 ms), you might set a \n * timer for 30 ms:\n *   @code SDL_SetTimer((33/10)*10, flag_update); @endcode\n *\n * If you use this function, you need to pass SDL_INIT_TIMER to SDL_Init().\n *\n * Under UNIX, you should not use raise or use SIGALRM and this function\n * in the same program, as it is implemented using setitimer().  You also\n * should not use this function in multi-threaded applications as signals\n * to multi-threaded apps have undefined behavior in some implementations.\n *\n * This function returns 0 if successful, or -1 if there was an error.\n */\nextern DECLSPEC int SDLCALL SDL_SetTimer(Uint32 interval, SDL_TimerCallback callback);\n\n/** @name New timer API\n * New timer API, supports multiple timers\n * Written by Stephane Peter <megastep@lokigames.com>\n */\n/*@{*/\n\n/**\n * Function prototype for the new timer callback function.\n * The callback function is passed the current timer interval and returns\n * the next timer interval.  If the returned value is the same as the one\n * passed in, the periodic alarm continues, otherwise a new alarm is\n * scheduled.  If the callback returns 0, the periodic alarm is cancelled.\n */\ntypedef Uint32 (SDLCALL *SDL_NewTimerCallback)(Uint32 interval, void *param);\n\n/** Definition of the timer ID type */\ntypedef struct _SDL_TimerID *SDL_TimerID;\n\n/** Add a new timer to the pool of timers already running.\n *  Returns a timer ID, or NULL when an error occurs.\n */\nextern DECLSPEC SDL_TimerID SDLCALL SDL_AddTimer(Uint32 interval, SDL_NewTimerCallback callback, void *param);\n\n/**\n * Remove one of the multiple timers knowing its ID.\n * Returns a boolean value indicating success.\n */\nextern DECLSPEC SDL_bool SDLCALL SDL_RemoveTimer(SDL_TimerID t);\n\n/*@}*/\n\n/* Ends C function definitions when using C++ */\n#ifdef __cplusplus\n}\n#endif\n#include \"close_code.h\"\n\n#endif /* _SDL_timer_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_types.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/** @file SDL_types.h\n *  @deprecated Use SDL_stdinc.h instead.\n */\n\n/* DEPRECATED */\n#include \"SDL_stdinc.h\"\n"
  },
  {
    "path": "other/sdl/include/SDL_version.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/** @file SDL_version.h\n *  This header defines the current SDL version\n */\n\n#ifndef _SDL_version_h\n#define _SDL_version_h\n\n#include \"SDL_stdinc.h\"\n\n#include \"begin_code.h\"\n/* Set up for C function definitions, even when using C++ */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/** @name Version Number\n *  Printable format: \"%d.%d.%d\", MAJOR, MINOR, PATCHLEVEL\n */\n/*@{*/\n#define SDL_MAJOR_VERSION\t1\n#define SDL_MINOR_VERSION\t2\n#define SDL_PATCHLEVEL\t\t14\n/*@}*/\n\ntypedef struct SDL_version {\n\tUint8 major;\n\tUint8 minor;\n\tUint8 patch;\n} SDL_version;\n\n/**\n * This macro can be used to fill a version structure with the compile-time\n * version of the SDL library.\n */\n#define SDL_VERSION(X)\t\t\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\\\n\t(X)->major = SDL_MAJOR_VERSION;\t\t\t\t\t\\\n\t(X)->minor = SDL_MINOR_VERSION;\t\t\t\t\t\\\n\t(X)->patch = SDL_PATCHLEVEL;\t\t\t\t\t\\\n}\n\n/** This macro turns the version numbers into a numeric value:\n *  (1,2,3) -> (1203)\n *  This assumes that there will never be more than 100 patchlevels\n */\n#define SDL_VERSIONNUM(X, Y, Z)\t\t\t\t\t\t\\\n\t((X)*1000 + (Y)*100 + (Z))\n\n/** This is the version number macro for the current SDL version */\n#define SDL_COMPILEDVERSION \\\n\tSDL_VERSIONNUM(SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL)\n\n/** This macro will evaluate to true if compiled with SDL at least X.Y.Z */\n#define SDL_VERSION_ATLEAST(X, Y, Z) \\\n\t(SDL_COMPILEDVERSION >= SDL_VERSIONNUM(X, Y, Z))\n\n/** This function gets the version of the dynamically linked SDL library.\n *  it should NOT be used to fill a version structure, instead you should\n *  use the SDL_Version() macro.\n */\nextern DECLSPEC const SDL_version * SDLCALL SDL_Linked_Version(void);\n\n/* Ends C function definitions when using C++ */\n#ifdef __cplusplus\n}\n#endif\n#include \"close_code.h\"\n\n#endif /* _SDL_version_h */\n"
  },
  {
    "path": "other/sdl/include/SDL_video.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/** @file SDL_video.h\n *  Header file for access to the SDL raw framebuffer window\n */\n\n#ifndef _SDL_video_h\n#define _SDL_video_h\n\n#include \"SDL_stdinc.h\"\n#include \"SDL_error.h\"\n#include \"SDL_rwops.h\"\n\n#include \"begin_code.h\"\n/* Set up for C function definitions, even when using C++ */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/** @name Transparency definitions\n *  These define alpha as the opacity of a surface\n */\n/*@{*/\n#define SDL_ALPHA_OPAQUE 255\n#define SDL_ALPHA_TRANSPARENT 0\n/*@}*/\n\n/** @name Useful data types */\n/*@{*/\ntypedef struct SDL_Rect {\n\tSint16 x, y;\n\tUint16 w, h;\n} SDL_Rect;\n\ntypedef struct SDL_Color {\n\tUint8 r;\n\tUint8 g;\n\tUint8 b;\n\tUint8 unused;\n} SDL_Color;\n#define SDL_Colour SDL_Color\n\ntypedef struct SDL_Palette {\n\tint       ncolors;\n\tSDL_Color *colors;\n} SDL_Palette;\n/*@}*/\n\n/** Everything in the pixel format structure is read-only */\ntypedef struct SDL_PixelFormat {\n\tSDL_Palette *palette;\n\tUint8  BitsPerPixel;\n\tUint8  BytesPerPixel;\n\tUint8  Rloss;\n\tUint8  Gloss;\n\tUint8  Bloss;\n\tUint8  Aloss;\n\tUint8  Rshift;\n\tUint8  Gshift;\n\tUint8  Bshift;\n\tUint8  Ashift;\n\tUint32 Rmask;\n\tUint32 Gmask;\n\tUint32 Bmask;\n\tUint32 Amask;\n\n\t/** RGB color key information */\n\tUint32 colorkey;\n\t/** Alpha value information (per-surface alpha) */\n\tUint8  alpha;\n} SDL_PixelFormat;\n\n/** This structure should be treated as read-only, except for 'pixels',\n *  which, if not NULL, contains the raw pixel data for the surface.\n */\ntypedef struct SDL_Surface {\n\tUint32 flags;\t\t\t\t/**< Read-only */\n\tSDL_PixelFormat *format;\t\t/**< Read-only */\n\tint w, h;\t\t\t\t/**< Read-only */\n\tUint16 pitch;\t\t\t\t/**< Read-only */\n\tvoid *pixels;\t\t\t\t/**< Read-write */\n\tint offset;\t\t\t\t/**< Private */\n\n\t/** Hardware-specific surface info */\n\tstruct private_hwdata *hwdata;\n\n\t/** clipping information */\n\tSDL_Rect clip_rect;\t\t\t/**< Read-only */\n\tUint32 unused1;\t\t\t\t/**< for binary compatibility */\n\n\t/** Allow recursive locks */\n\tUint32 locked;\t\t\t\t/**< Private */\n\n\t/** info for fast blit mapping to other surfaces */\n\tstruct SDL_BlitMap *map;\t\t/**< Private */\n\n\t/** format version, bumped at every change to invalidate blit maps */\n\tunsigned int format_version;\t\t/**< Private */\n\n\t/** Reference count -- used when freeing surface */\n\tint refcount;\t\t\t\t/**< Read-mostly */\n} SDL_Surface;\n\n/** @name SDL_Surface Flags\n *  These are the currently supported flags for the SDL_surface\n */\n/*@{*/\n\n/** Available for SDL_CreateRGBSurface() or SDL_SetVideoMode() */\n/*@{*/\n#define SDL_SWSURFACE\t0x00000000\t/**< Surface is in system memory */\n#define SDL_HWSURFACE\t0x00000001\t/**< Surface is in video memory */\n#define SDL_ASYNCBLIT\t0x00000004\t/**< Use asynchronous blits if possible */\n/*@}*/\n\n/** Available for SDL_SetVideoMode() */\n/*@{*/\n#define SDL_ANYFORMAT\t0x10000000\t/**< Allow any video depth/pixel-format */\n#define SDL_HWPALETTE\t0x20000000\t/**< Surface has exclusive palette */\n#define SDL_DOUBLEBUF\t0x40000000\t/**< Set up double-buffered video mode */\n#define SDL_FULLSCREEN\t0x80000000\t/**< Surface is a full screen display */\n#define SDL_OPENGL      0x00000002      /**< Create an OpenGL rendering context */\n#define SDL_OPENGLBLIT\t0x0000000A\t/**< Create an OpenGL rendering context and use it for blitting */\n#define SDL_RESIZABLE\t0x00000010\t/**< This video mode may be resized */\n#define SDL_NOFRAME\t0x00000020\t/**< No window caption or edge frame */\n/*@}*/\n\n/** Used internally (read-only) */\n/*@{*/\n#define SDL_HWACCEL\t0x00000100\t/**< Blit uses hardware acceleration */\n#define SDL_SRCCOLORKEY\t0x00001000\t/**< Blit uses a source color key */\n#define SDL_RLEACCELOK\t0x00002000\t/**< Private flag */\n#define SDL_RLEACCEL\t0x00004000\t/**< Surface is RLE encoded */\n#define SDL_SRCALPHA\t0x00010000\t/**< Blit uses source alpha blending */\n#define SDL_PREALLOC\t0x01000000\t/**< Surface uses preallocated memory */\n/*@}*/\n\n/*@}*/\n\n/** Evaluates to true if the surface needs to be locked before access */\n#define SDL_MUSTLOCK(surface)\t\\\n  (surface->offset ||\t\t\\\n  ((surface->flags & (SDL_HWSURFACE|SDL_ASYNCBLIT|SDL_RLEACCEL)) != 0))\n\n/** typedef for private surface blitting functions */\ntypedef int (*SDL_blit)(struct SDL_Surface *src, SDL_Rect *srcrect,\n\t\t\tstruct SDL_Surface *dst, SDL_Rect *dstrect);\n\n\n/** Useful for determining the video hardware capabilities */\ntypedef struct SDL_VideoInfo {\n\tUint32 hw_available :1;\t/**< Flag: Can you create hardware surfaces? */\n\tUint32 wm_available :1;\t/**< Flag: Can you talk to a window manager? */\n\tUint32 UnusedBits1  :6;\n\tUint32 UnusedBits2  :1;\n\tUint32 blit_hw      :1;\t/**< Flag: Accelerated blits HW --> HW */\n\tUint32 blit_hw_CC   :1;\t/**< Flag: Accelerated blits with Colorkey */\n\tUint32 blit_hw_A    :1;\t/**< Flag: Accelerated blits with Alpha */\n\tUint32 blit_sw      :1;\t/**< Flag: Accelerated blits SW --> HW */\n\tUint32 blit_sw_CC   :1;\t/**< Flag: Accelerated blits with Colorkey */\n\tUint32 blit_sw_A    :1;\t/**< Flag: Accelerated blits with Alpha */\n\tUint32 blit_fill    :1;\t/**< Flag: Accelerated color fill */\n\tUint32 UnusedBits3  :16;\n\tUint32 video_mem;\t/**< The total amount of video memory (in K) */\n\tSDL_PixelFormat *vfmt;\t/**< Value: The format of the video surface */\n\tint    current_w;\t/**< Value: The current video mode width */\n\tint    current_h;\t/**< Value: The current video mode height */\n} SDL_VideoInfo;\n\n\n/** @name Overlay Formats\n *  The most common video overlay formats.\n *  For an explanation of these pixel formats, see:\n *\thttp://www.webartz.com/fourcc/indexyuv.htm\n *\n *  For information on the relationship between color spaces, see:\n *  http://www.neuro.sfc.keio.ac.jp/~aly/polygon/info/color-space-faq.html\n */\n/*@{*/\n#define SDL_YV12_OVERLAY  0x32315659\t/**< Planar mode: Y + V + U  (3 planes) */\n#define SDL_IYUV_OVERLAY  0x56555949\t/**< Planar mode: Y + U + V  (3 planes) */\n#define SDL_YUY2_OVERLAY  0x32595559\t/**< Packed mode: Y0+U0+Y1+V0 (1 plane) */\n#define SDL_UYVY_OVERLAY  0x59565955\t/**< Packed mode: U0+Y0+V0+Y1 (1 plane) */\n#define SDL_YVYU_OVERLAY  0x55595659\t/**< Packed mode: Y0+V0+Y1+U0 (1 plane) */\n/*@}*/\n\n/** The YUV hardware video overlay */\ntypedef struct SDL_Overlay {\n\tUint32 format;\t\t\t\t/**< Read-only */\n\tint w, h;\t\t\t\t/**< Read-only */\n\tint planes;\t\t\t\t/**< Read-only */\n\tUint16 *pitches;\t\t\t/**< Read-only */\n\tUint8 **pixels;\t\t\t\t/**< Read-write */\n\n\t/** @name Hardware-specific surface info */\n        /*@{*/\n\tstruct private_yuvhwfuncs *hwfuncs;\n\tstruct private_yuvhwdata *hwdata;\n        /*@{*/\n\n\t/** @name Special flags */\n        /*@{*/\n\tUint32 hw_overlay :1;\t/**< Flag: This overlay hardware accelerated? */\n\tUint32 UnusedBits :31;\n        /*@}*/\n} SDL_Overlay;\n\n\n/** Public enumeration for setting the OpenGL window attributes. */\ntypedef enum {\n    SDL_GL_RED_SIZE,\n    SDL_GL_GREEN_SIZE,\n    SDL_GL_BLUE_SIZE,\n    SDL_GL_ALPHA_SIZE,\n    SDL_GL_BUFFER_SIZE,\n    SDL_GL_DOUBLEBUFFER,\n    SDL_GL_DEPTH_SIZE,\n    SDL_GL_STENCIL_SIZE,\n    SDL_GL_ACCUM_RED_SIZE,\n    SDL_GL_ACCUM_GREEN_SIZE,\n    SDL_GL_ACCUM_BLUE_SIZE,\n    SDL_GL_ACCUM_ALPHA_SIZE,\n    SDL_GL_STEREO,\n    SDL_GL_MULTISAMPLEBUFFERS,\n    SDL_GL_MULTISAMPLESAMPLES,\n    SDL_GL_ACCELERATED_VISUAL,\n    SDL_GL_SWAP_CONTROL\n} SDL_GLattr;\n\n/** @name flags for SDL_SetPalette() */\n/*@{*/\n#define SDL_LOGPAL 0x01\n#define SDL_PHYSPAL 0x02\n/*@}*/\n\n/* Function prototypes */\n\n/**\n * @name Video Init and Quit\n * These functions are used internally, and should not be used unless you\n * have a specific need to specify the video driver you want to use.\n * You should normally use SDL_Init() or SDL_InitSubSystem().\n */\n/*@{*/\n/**\n * Initializes the video subsystem. Sets up a connection\n * to the window manager, etc, and determines the current video mode and\n * pixel format, but does not initialize a window or graphics mode.\n * Note that event handling is activated by this routine.\n *\n * If you use both sound and video in your application, you need to call\n * SDL_Init() before opening the sound device, otherwise under Win32 DirectX,\n * you won't be able to set full-screen display modes.\n */\nextern DECLSPEC int SDLCALL SDL_VideoInit(const char *driver_name, Uint32 flags);\nextern DECLSPEC void SDLCALL SDL_VideoQuit(void);\n/*@}*/\n\n/**\n * This function fills the given character buffer with the name of the\n * video driver, and returns a pointer to it if the video driver has\n * been initialized.  It returns NULL if no driver has been initialized.\n */\nextern DECLSPEC char * SDLCALL SDL_VideoDriverName(char *namebuf, int maxlen);\n\n/**\n * This function returns a pointer to the current display surface.\n * If SDL is doing format conversion on the display surface, this\n * function returns the publicly visible surface, not the real video\n * surface.\n */\nextern DECLSPEC SDL_Surface * SDLCALL SDL_GetVideoSurface(void);\n\n/**\n * This function returns a read-only pointer to information about the\n * video hardware.  If this is called before SDL_SetVideoMode(), the 'vfmt'\n * member of the returned structure will contain the pixel format of the\n * \"best\" video mode.\n */\nextern DECLSPEC const SDL_VideoInfo * SDLCALL SDL_GetVideoInfo(void);\n\n/**\n * Check to see if a particular video mode is supported.\n * It returns 0 if the requested mode is not supported under any bit depth,\n * or returns the bits-per-pixel of the closest available mode with the\n * given width and height.  If this bits-per-pixel is different from the\n * one used when setting the video mode, SDL_SetVideoMode() will succeed,\n * but will emulate the requested bits-per-pixel with a shadow surface.\n *\n * The arguments to SDL_VideoModeOK() are the same ones you would pass to\n * SDL_SetVideoMode()\n */\nextern DECLSPEC int SDLCALL SDL_VideoModeOK(int width, int height, int bpp, Uint32 flags);\n\n/**\n * Return a pointer to an array of available screen dimensions for the\n * given format and video flags, sorted largest to smallest.  Returns \n * NULL if there are no dimensions available for a particular format, \n * or (SDL_Rect **)-1 if any dimension is okay for the given format.\n *\n * If 'format' is NULL, the mode list will be for the format given \n * by SDL_GetVideoInfo()->vfmt\n */\nextern DECLSPEC SDL_Rect ** SDLCALL SDL_ListModes(SDL_PixelFormat *format, Uint32 flags);\n\n/**\n * Set up a video mode with the specified width, height and bits-per-pixel.\n *\n * If 'bpp' is 0, it is treated as the current display bits per pixel.\n *\n * If SDL_ANYFORMAT is set in 'flags', the SDL library will try to set the\n * requested bits-per-pixel, but will return whatever video pixel format is\n * available.  The default is to emulate the requested pixel format if it\n * is not natively available.\n *\n * If SDL_HWSURFACE is set in 'flags', the video surface will be placed in\n * video memory, if possible, and you may have to call SDL_LockSurface()\n * in order to access the raw framebuffer.  Otherwise, the video surface\n * will be created in system memory.\n *\n * If SDL_ASYNCBLIT is set in 'flags', SDL will try to perform rectangle\n * updates asynchronously, but you must always lock before accessing pixels.\n * SDL will wait for updates to complete before returning from the lock.\n *\n * If SDL_HWPALETTE is set in 'flags', the SDL library will guarantee\n * that the colors set by SDL_SetColors() will be the colors you get.\n * Otherwise, in 8-bit mode, SDL_SetColors() may not be able to set all\n * of the colors exactly the way they are requested, and you should look\n * at the video surface structure to determine the actual palette.\n * If SDL cannot guarantee that the colors you request can be set, \n * i.e. if the colormap is shared, then the video surface may be created\n * under emulation in system memory, overriding the SDL_HWSURFACE flag.\n *\n * If SDL_FULLSCREEN is set in 'flags', the SDL library will try to set\n * a fullscreen video mode.  The default is to create a windowed mode\n * if the current graphics system has a window manager.\n * If the SDL library is able to set a fullscreen video mode, this flag \n * will be set in the surface that is returned.\n *\n * If SDL_DOUBLEBUF is set in 'flags', the SDL library will try to set up\n * two surfaces in video memory and swap between them when you call \n * SDL_Flip().  This is usually slower than the normal single-buffering\n * scheme, but prevents \"tearing\" artifacts caused by modifying video \n * memory while the monitor is refreshing.  It should only be used by \n * applications that redraw the entire screen on every update.\n *\n * If SDL_RESIZABLE is set in 'flags', the SDL library will allow the\n * window manager, if any, to resize the window at runtime.  When this\n * occurs, SDL will send a SDL_VIDEORESIZE event to you application,\n * and you must respond to the event by re-calling SDL_SetVideoMode()\n * with the requested size (or another size that suits the application).\n *\n * If SDL_NOFRAME is set in 'flags', the SDL library will create a window\n * without any title bar or frame decoration.  Fullscreen video modes have\n * this flag set automatically.\n *\n * This function returns the video framebuffer surface, or NULL if it fails.\n *\n * If you rely on functionality provided by certain video flags, check the\n * flags of the returned surface to make sure that functionality is available.\n * SDL will fall back to reduced functionality if the exact flags you wanted\n * are not available.\n */\nextern DECLSPEC SDL_Surface * SDLCALL SDL_SetVideoMode\n\t\t\t(int width, int height, int bpp, Uint32 flags);\n\n/** @name SDL_Update Functions\n * These functions should not be called while 'screen' is locked.\n */\n/*@{*/\n/**\n * Makes sure the given list of rectangles is updated on the given screen.\n */\nextern DECLSPEC void SDLCALL SDL_UpdateRects\n\t\t(SDL_Surface *screen, int numrects, SDL_Rect *rects);\n/**\n * If 'x', 'y', 'w' and 'h' are all 0, SDL_UpdateRect will update the entire\n * screen.\n */\nextern DECLSPEC void SDLCALL SDL_UpdateRect\n\t\t(SDL_Surface *screen, Sint32 x, Sint32 y, Uint32 w, Uint32 h);\n/*@}*/\n\n/**\n * On hardware that supports double-buffering, this function sets up a flip\n * and returns.  The hardware will wait for vertical retrace, and then swap\n * video buffers before the next video surface blit or lock will return.\n * On hardware that doesn not support double-buffering, this is equivalent\n * to calling SDL_UpdateRect(screen, 0, 0, 0, 0);\n * The SDL_DOUBLEBUF flag must have been passed to SDL_SetVideoMode() when\n * setting the video mode for this function to perform hardware flipping.\n * This function returns 0 if successful, or -1 if there was an error.\n */\nextern DECLSPEC int SDLCALL SDL_Flip(SDL_Surface *screen);\n\n/**\n * Set the gamma correction for each of the color channels.\n * The gamma values range (approximately) between 0.1 and 10.0\n * \n * If this function isn't supported directly by the hardware, it will\n * be emulated using gamma ramps, if available.  If successful, this\n * function returns 0, otherwise it returns -1.\n */\nextern DECLSPEC int SDLCALL SDL_SetGamma(float red, float green, float blue);\n\n/**\n * Set the gamma translation table for the red, green, and blue channels\n * of the video hardware.  Each table is an array of 256 16-bit quantities,\n * representing a mapping between the input and output for that channel.\n * The input is the index into the array, and the output is the 16-bit\n * gamma value at that index, scaled to the output color precision.\n * \n * You may pass NULL for any of the channels to leave it unchanged.\n * If the call succeeds, it will return 0.  If the display driver or\n * hardware does not support gamma translation, or otherwise fails,\n * this function will return -1.\n */\nextern DECLSPEC int SDLCALL SDL_SetGammaRamp(const Uint16 *red, const Uint16 *green, const Uint16 *blue);\n\n/**\n * Retrieve the current values of the gamma translation tables.\n * \n * You must pass in valid pointers to arrays of 256 16-bit quantities.\n * Any of the pointers may be NULL to ignore that channel.\n * If the call succeeds, it will return 0.  If the display driver or\n * hardware does not support gamma translation, or otherwise fails,\n * this function will return -1.\n */\nextern DECLSPEC int SDLCALL SDL_GetGammaRamp(Uint16 *red, Uint16 *green, Uint16 *blue);\n\n/**\n * Sets a portion of the colormap for the given 8-bit surface.  If 'surface'\n * is not a palettized surface, this function does nothing, returning 0.\n * If all of the colors were set as passed to SDL_SetColors(), it will\n * return 1.  If not all the color entries were set exactly as given,\n * it will return 0, and you should look at the surface palette to\n * determine the actual color palette.\n *\n * When 'surface' is the surface associated with the current display, the\n * display colormap will be updated with the requested colors.  If \n * SDL_HWPALETTE was set in SDL_SetVideoMode() flags, SDL_SetColors()\n * will always return 1, and the palette is guaranteed to be set the way\n * you desire, even if the window colormap has to be warped or run under\n * emulation.\n */\nextern DECLSPEC int SDLCALL SDL_SetColors(SDL_Surface *surface, \n\t\t\tSDL_Color *colors, int firstcolor, int ncolors);\n\n/**\n * Sets a portion of the colormap for a given 8-bit surface.\n * 'flags' is one or both of:\n * SDL_LOGPAL  -- set logical palette, which controls how blits are mapped\n *                to/from the surface,\n * SDL_PHYSPAL -- set physical palette, which controls how pixels look on\n *                the screen\n * Only screens have physical palettes. Separate change of physical/logical\n * palettes is only possible if the screen has SDL_HWPALETTE set.\n *\n * The return value is 1 if all colours could be set as requested, and 0\n * otherwise.\n *\n * SDL_SetColors() is equivalent to calling this function with\n *     flags = (SDL_LOGPAL|SDL_PHYSPAL).\n */\nextern DECLSPEC int SDLCALL SDL_SetPalette(SDL_Surface *surface, int flags,\n\t\t\t\t   SDL_Color *colors, int firstcolor,\n\t\t\t\t   int ncolors);\n\n/**\n * Maps an RGB triple to an opaque pixel value for a given pixel format\n */\nextern DECLSPEC Uint32 SDLCALL SDL_MapRGB\n(const SDL_PixelFormat * const format,\n const Uint8 r, const Uint8 g, const Uint8 b);\n\n/**\n * Maps an RGBA quadruple to a pixel value for a given pixel format\n */\nextern DECLSPEC Uint32 SDLCALL SDL_MapRGBA\n(const SDL_PixelFormat * const format,\n const Uint8 r, const Uint8 g, const Uint8 b, const Uint8 a);\n\n/**\n * Maps a pixel value into the RGB components for a given pixel format\n */\nextern DECLSPEC void SDLCALL SDL_GetRGB(Uint32 pixel,\n\t\t\t\tconst SDL_PixelFormat * const fmt,\n\t\t\t\tUint8 *r, Uint8 *g, Uint8 *b);\n\n/**\n * Maps a pixel value into the RGBA components for a given pixel format\n */\nextern DECLSPEC void SDLCALL SDL_GetRGBA(Uint32 pixel,\n\t\t\t\tconst SDL_PixelFormat * const fmt,\n\t\t\t\tUint8 *r, Uint8 *g, Uint8 *b, Uint8 *a);\n\n/** @sa SDL_CreateRGBSurface */\n#define SDL_AllocSurface    SDL_CreateRGBSurface\n/**\n * Allocate and free an RGB surface (must be called after SDL_SetVideoMode)\n * If the depth is 4 or 8 bits, an empty palette is allocated for the surface.\n * If the depth is greater than 8 bits, the pixel format is set using the\n * flags '[RGB]mask'.\n * If the function runs out of memory, it will return NULL.\n *\n * The 'flags' tell what kind of surface to create.\n * SDL_SWSURFACE means that the surface should be created in system memory.\n * SDL_HWSURFACE means that the surface should be created in video memory,\n * with the same format as the display surface.  This is useful for surfaces\n * that will not change much, to take advantage of hardware acceleration\n * when being blitted to the display surface.\n * SDL_ASYNCBLIT means that SDL will try to perform asynchronous blits with\n * this surface, but you must always lock it before accessing the pixels.\n * SDL will wait for current blits to finish before returning from the lock.\n * SDL_SRCCOLORKEY indicates that the surface will be used for colorkey blits.\n * If the hardware supports acceleration of colorkey blits between\n * two surfaces in video memory, SDL will try to place the surface in\n * video memory. If this isn't possible or if there is no hardware\n * acceleration available, the surface will be placed in system memory.\n * SDL_SRCALPHA means that the surface will be used for alpha blits and \n * if the hardware supports hardware acceleration of alpha blits between\n * two surfaces in video memory, to place the surface in video memory\n * if possible, otherwise it will be placed in system memory.\n * If the surface is created in video memory, blits will be _much_ faster,\n * but the surface format must be identical to the video surface format,\n * and the only way to access the pixels member of the surface is to use\n * the SDL_LockSurface() and SDL_UnlockSurface() calls.\n * If the requested surface actually resides in video memory, SDL_HWSURFACE\n * will be set in the flags member of the returned surface.  If for some\n * reason the surface could not be placed in video memory, it will not have\n * the SDL_HWSURFACE flag set, and will be created in system memory instead.\n */\nextern DECLSPEC SDL_Surface * SDLCALL SDL_CreateRGBSurface\n\t\t\t(Uint32 flags, int width, int height, int depth, \n\t\t\tUint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask);\n/** @sa SDL_CreateRGBSurface */\nextern DECLSPEC SDL_Surface * SDLCALL SDL_CreateRGBSurfaceFrom(void *pixels,\n\t\t\tint width, int height, int depth, int pitch,\n\t\t\tUint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask);\nextern DECLSPEC void SDLCALL SDL_FreeSurface(SDL_Surface *surface);\n\n/**\n * SDL_LockSurface() sets up a surface for directly accessing the pixels.\n * Between calls to SDL_LockSurface()/SDL_UnlockSurface(), you can write\n * to and read from 'surface->pixels', using the pixel format stored in \n * 'surface->format'.  Once you are done accessing the surface, you should \n * use SDL_UnlockSurface() to release it.\n *\n * Not all surfaces require locking.  If SDL_MUSTLOCK(surface) evaluates\n * to 0, then you can read and write to the surface at any time, and the\n * pixel format of the surface will not change.  In particular, if the\n * SDL_HWSURFACE flag is not given when calling SDL_SetVideoMode(), you\n * will not need to lock the display surface before accessing it.\n * \n * No operating system or library calls should be made between lock/unlock\n * pairs, as critical system locks may be held during this time.\n *\n * SDL_LockSurface() returns 0, or -1 if the surface couldn't be locked.\n */\nextern DECLSPEC int SDLCALL SDL_LockSurface(SDL_Surface *surface);\nextern DECLSPEC void SDLCALL SDL_UnlockSurface(SDL_Surface *surface);\n\n/**\n * Load a surface from a seekable SDL data source (memory or file.)\n * If 'freesrc' is non-zero, the source will be closed after being read.\n * Returns the new surface, or NULL if there was an error.\n * The new surface should be freed with SDL_FreeSurface().\n */\nextern DECLSPEC SDL_Surface * SDLCALL SDL_LoadBMP_RW(SDL_RWops *src, int freesrc);\n\n/** Convenience macro -- load a surface from a file */\n#define SDL_LoadBMP(file)\tSDL_LoadBMP_RW(SDL_RWFromFile(file, \"rb\"), 1)\n\n/**\n * Save a surface to a seekable SDL data source (memory or file.)\n * If 'freedst' is non-zero, the source will be closed after being written.\n * Returns 0 if successful or -1 if there was an error.\n */\nextern DECLSPEC int SDLCALL SDL_SaveBMP_RW\n\t\t(SDL_Surface *surface, SDL_RWops *dst, int freedst);\n\n/** Convenience macro -- save a surface to a file */\n#define SDL_SaveBMP(surface, file) \\\n\t\tSDL_SaveBMP_RW(surface, SDL_RWFromFile(file, \"wb\"), 1)\n\n/**\n * Sets the color key (transparent pixel) in a blittable surface.\n * If 'flag' is SDL_SRCCOLORKEY (optionally OR'd with SDL_RLEACCEL), \n * 'key' will be the transparent pixel in the source image of a blit.\n * SDL_RLEACCEL requests RLE acceleration for the surface if present,\n * and removes RLE acceleration if absent.\n * If 'flag' is 0, this function clears any current color key.\n * This function returns 0, or -1 if there was an error.\n */\nextern DECLSPEC int SDLCALL SDL_SetColorKey\n\t\t\t(SDL_Surface *surface, Uint32 flag, Uint32 key);\n\n/**\n * This function sets the alpha value for the entire surface, as opposed to\n * using the alpha component of each pixel. This value measures the range\n * of transparency of the surface, 0 being completely transparent to 255\n * being completely opaque. An 'alpha' value of 255 causes blits to be\n * opaque, the source pixels copied to the destination (the default). Note\n * that per-surface alpha can be combined with colorkey transparency.\n *\n * If 'flag' is 0, alpha blending is disabled for the surface.\n * If 'flag' is SDL_SRCALPHA, alpha blending is enabled for the surface.\n * OR:ing the flag with SDL_RLEACCEL requests RLE acceleration for the\n * surface; if SDL_RLEACCEL is not specified, the RLE accel will be removed.\n *\n * The 'alpha' parameter is ignored for surfaces that have an alpha channel.\n */\nextern DECLSPEC int SDLCALL SDL_SetAlpha(SDL_Surface *surface, Uint32 flag, Uint8 alpha);\n\n/**\n * Sets the clipping rectangle for the destination surface in a blit.\n *\n * If the clip rectangle is NULL, clipping will be disabled.\n * If the clip rectangle doesn't intersect the surface, the function will\n * return SDL_FALSE and blits will be completely clipped.  Otherwise the\n * function returns SDL_TRUE and blits to the surface will be clipped to\n * the intersection of the surface area and the clipping rectangle.\n *\n * Note that blits are automatically clipped to the edges of the source\n * and destination surfaces.\n */\nextern DECLSPEC SDL_bool SDLCALL SDL_SetClipRect(SDL_Surface *surface, const SDL_Rect *rect);\n\n/**\n * Gets the clipping rectangle for the destination surface in a blit.\n * 'rect' must be a pointer to a valid rectangle which will be filled\n * with the correct values.\n */\nextern DECLSPEC void SDLCALL SDL_GetClipRect(SDL_Surface *surface, SDL_Rect *rect);\n\n/**\n * Creates a new surface of the specified format, and then copies and maps \n * the given surface to it so the blit of the converted surface will be as \n * fast as possible.  If this function fails, it returns NULL.\n *\n * The 'flags' parameter is passed to SDL_CreateRGBSurface() and has those \n * semantics.  You can also pass SDL_RLEACCEL in the flags parameter and\n * SDL will try to RLE accelerate colorkey and alpha blits in the resulting\n * surface.\n *\n * This function is used internally by SDL_DisplayFormat().\n */\nextern DECLSPEC SDL_Surface * SDLCALL SDL_ConvertSurface\n\t\t\t(SDL_Surface *src, SDL_PixelFormat *fmt, Uint32 flags);\n\n/**\n * This performs a fast blit from the source surface to the destination\n * surface.  It assumes that the source and destination rectangles are\n * the same size.  If either 'srcrect' or 'dstrect' are NULL, the entire\n * surface (src or dst) is copied.  The final blit rectangles are saved\n * in 'srcrect' and 'dstrect' after all clipping is performed.\n * If the blit is successful, it returns 0, otherwise it returns -1.\n *\n * The blit function should not be called on a locked surface.\n *\n * The blit semantics for surfaces with and without alpha and colorkey\n * are defined as follows:\n *\n * RGBA->RGB:\n *     SDL_SRCALPHA set:\n * \talpha-blend (using alpha-channel).\n * \tSDL_SRCCOLORKEY ignored.\n *     SDL_SRCALPHA not set:\n * \tcopy RGB.\n * \tif SDL_SRCCOLORKEY set, only copy the pixels matching the\n * \tRGB values of the source colour key, ignoring alpha in the\n * \tcomparison.\n * \n * RGB->RGBA:\n *     SDL_SRCALPHA set:\n * \talpha-blend (using the source per-surface alpha value);\n * \tset destination alpha to opaque.\n *     SDL_SRCALPHA not set:\n * \tcopy RGB, set destination alpha to source per-surface alpha value.\n *     both:\n * \tif SDL_SRCCOLORKEY set, only copy the pixels matching the\n * \tsource colour key.\n * \n * RGBA->RGBA:\n *     SDL_SRCALPHA set:\n * \talpha-blend (using the source alpha channel) the RGB values;\n * \tleave destination alpha untouched. [Note: is this correct?]\n * \tSDL_SRCCOLORKEY ignored.\n *     SDL_SRCALPHA not set:\n * \tcopy all of RGBA to the destination.\n * \tif SDL_SRCCOLORKEY set, only copy the pixels matching the\n * \tRGB values of the source colour key, ignoring alpha in the\n * \tcomparison.\n * \n * RGB->RGB: \n *     SDL_SRCALPHA set:\n * \talpha-blend (using the source per-surface alpha value).\n *     SDL_SRCALPHA not set:\n * \tcopy RGB.\n *     both:\n * \tif SDL_SRCCOLORKEY set, only copy the pixels matching the\n * \tsource colour key.\n *\n * If either of the surfaces were in video memory, and the blit returns -2,\n * the video memory was lost, so it should be reloaded with artwork and \n * re-blitted:\n * @code\n *\twhile ( SDL_BlitSurface(image, imgrect, screen, dstrect) == -2 ) {\n *\t\twhile ( SDL_LockSurface(image) < 0 )\n *\t\t\tSleep(10);\n *\t\t-- Write image pixels to image->pixels --\n *\t\tSDL_UnlockSurface(image);\n *\t}\n * @endcode\n *\n * This happens under DirectX 5.0 when the system switches away from your\n * fullscreen application.  The lock will also fail until you have access\n * to the video memory again.\n *\n * You should call SDL_BlitSurface() unless you know exactly how SDL\n * blitting works internally and how to use the other blit functions.\n */\n#define SDL_BlitSurface SDL_UpperBlit\n\n/** This is the public blit function, SDL_BlitSurface(), and it performs\n *  rectangle validation and clipping before passing it to SDL_LowerBlit()\n */\nextern DECLSPEC int SDLCALL SDL_UpperBlit\n\t\t\t(SDL_Surface *src, SDL_Rect *srcrect,\n\t\t\t SDL_Surface *dst, SDL_Rect *dstrect);\n/** This is a semi-private blit function and it performs low-level surface\n *  blitting only.\n */\nextern DECLSPEC int SDLCALL SDL_LowerBlit\n\t\t\t(SDL_Surface *src, SDL_Rect *srcrect,\n\t\t\t SDL_Surface *dst, SDL_Rect *dstrect);\n\n/**\n * This function performs a fast fill of the given rectangle with 'color'\n * The given rectangle is clipped to the destination surface clip area\n * and the final fill rectangle is saved in the passed in pointer.\n * If 'dstrect' is NULL, the whole surface will be filled with 'color'\n * The color should be a pixel of the format used by the surface, and \n * can be generated by the SDL_MapRGB() function.\n * This function returns 0 on success, or -1 on error.\n */\nextern DECLSPEC int SDLCALL SDL_FillRect\n\t\t(SDL_Surface *dst, SDL_Rect *dstrect, Uint32 color);\n\n/**\n * This function takes a surface and copies it to a new surface of the\n * pixel format and colors of the video framebuffer, suitable for fast\n * blitting onto the display surface.  It calls SDL_ConvertSurface()\n *\n * If you want to take advantage of hardware colorkey or alpha blit\n * acceleration, you should set the colorkey and alpha value before\n * calling this function.\n *\n * If the conversion fails or runs out of memory, it returns NULL\n */\nextern DECLSPEC SDL_Surface * SDLCALL SDL_DisplayFormat(SDL_Surface *surface);\n\n/**\n * This function takes a surface and copies it to a new surface of the\n * pixel format and colors of the video framebuffer (if possible),\n * suitable for fast alpha blitting onto the display surface.\n * The new surface will always have an alpha channel.\n *\n * If you want to take advantage of hardware colorkey or alpha blit\n * acceleration, you should set the colorkey and alpha value before\n * calling this function.\n *\n * If the conversion fails or runs out of memory, it returns NULL\n */\nextern DECLSPEC SDL_Surface * SDLCALL SDL_DisplayFormatAlpha(SDL_Surface *surface);\n\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/** @name YUV video surface overlay functions                                */ /*@{*/\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n/** This function creates a video output overlay\n *  Calling the returned surface an overlay is something of a misnomer because\n *  the contents of the display surface underneath the area where the overlay\n *  is shown is undefined - it may be overwritten with the converted YUV data.\n */\nextern DECLSPEC SDL_Overlay * SDLCALL SDL_CreateYUVOverlay(int width, int height,\n\t\t\t\tUint32 format, SDL_Surface *display);\n\n/** Lock an overlay for direct access, and unlock it when you are done */\nextern DECLSPEC int SDLCALL SDL_LockYUVOverlay(SDL_Overlay *overlay);\nextern DECLSPEC void SDLCALL SDL_UnlockYUVOverlay(SDL_Overlay *overlay);\n\n/** Blit a video overlay to the display surface.\n *  The contents of the video surface underneath the blit destination are\n *  not defined.  \n *  The width and height of the destination rectangle may be different from\n *  that of the overlay, but currently only 2x scaling is supported.\n */\nextern DECLSPEC int SDLCALL SDL_DisplayYUVOverlay(SDL_Overlay *overlay, SDL_Rect *dstrect);\n\n/** Free a video overlay */\nextern DECLSPEC void SDLCALL SDL_FreeYUVOverlay(SDL_Overlay *overlay);\n\n/*@}*/\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/** @name OpenGL support functions.                                          */ /*@{*/\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n/**\n * Dynamically load an OpenGL library, or the default one if path is NULL\n *\n * If you do this, you need to retrieve all of the GL functions used in\n * your program from the dynamic library using SDL_GL_GetProcAddress().\n */\nextern DECLSPEC int SDLCALL SDL_GL_LoadLibrary(const char *path);\n\n/**\n * Get the address of a GL function\n */\nextern DECLSPEC void * SDLCALL SDL_GL_GetProcAddress(const char* proc);\n\n/**\n * Set an attribute of the OpenGL subsystem before intialization.\n */\nextern DECLSPEC int SDLCALL SDL_GL_SetAttribute(SDL_GLattr attr, int value);\n\n/**\n * Get an attribute of the OpenGL subsystem from the windowing\n * interface, such as glX. This is of course different from getting\n * the values from SDL's internal OpenGL subsystem, which only\n * stores the values you request before initialization.\n *\n * Developers should track the values they pass into SDL_GL_SetAttribute\n * themselves if they want to retrieve these values.\n */\nextern DECLSPEC int SDLCALL SDL_GL_GetAttribute(SDL_GLattr attr, int* value);\n\n/**\n * Swap the OpenGL buffers, if double-buffering is supported.\n */\nextern DECLSPEC void SDLCALL SDL_GL_SwapBuffers(void);\n\n/** @name OpenGL Internal Functions\n * Internal functions that should not be called unless you have read\n * and understood the source code for these functions.\n */\n/*@{*/\nextern DECLSPEC void SDLCALL SDL_GL_UpdateRects(int numrects, SDL_Rect* rects);\nextern DECLSPEC void SDLCALL SDL_GL_Lock(void);\nextern DECLSPEC void SDLCALL SDL_GL_Unlock(void);\n/*@}*/\n\n/*@}*/\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/** @name Window Manager Functions                                           */\n/** These functions allow interaction with the window manager, if any.       */ /*@{*/\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n/**\n * Sets the title and icon text of the display window (UTF-8 encoded)\n */\nextern DECLSPEC void SDLCALL SDL_WM_SetCaption(const char *title, const char *icon);\n/**\n * Gets the title and icon text of the display window (UTF-8 encoded)\n */\nextern DECLSPEC void SDLCALL SDL_WM_GetCaption(char **title, char **icon);\n\n/**\n * Sets the icon for the display window.\n * This function must be called before the first call to SDL_SetVideoMode().\n * It takes an icon surface, and a mask in MSB format.\n * If 'mask' is NULL, the entire icon surface will be used as the icon.\n */\nextern DECLSPEC void SDLCALL SDL_WM_SetIcon(SDL_Surface *icon, Uint8 *mask);\n\n/**\n * This function iconifies the window, and returns 1 if it succeeded.\n * If the function succeeds, it generates an SDL_APPACTIVE loss event.\n * This function is a noop and returns 0 in non-windowed environments.\n */\nextern DECLSPEC int SDLCALL SDL_WM_IconifyWindow(void);\n\n/**\n * Toggle fullscreen mode without changing the contents of the screen.\n * If the display surface does not require locking before accessing\n * the pixel information, then the memory pointers will not change.\n *\n * If this function was able to toggle fullscreen mode (change from \n * running in a window to fullscreen, or vice-versa), it will return 1.\n * If it is not implemented, or fails, it returns 0.\n *\n * The next call to SDL_SetVideoMode() will set the mode fullscreen\n * attribute based on the flags parameter - if SDL_FULLSCREEN is not\n * set, then the display will be windowed by default where supported.\n *\n * This is currently only implemented in the X11 video driver.\n */\nextern DECLSPEC int SDLCALL SDL_WM_ToggleFullScreen(SDL_Surface *surface);\n\ntypedef enum {\n\tSDL_GRAB_QUERY = -1,\n\tSDL_GRAB_OFF = 0,\n\tSDL_GRAB_ON = 1,\n\tSDL_GRAB_FULLSCREEN\t/**< Used internally */\n} SDL_GrabMode;\n/**\n * This function allows you to set and query the input grab state of\n * the application.  It returns the new input grab state.\n *\n * Grabbing means that the mouse is confined to the application window,\n * and nearly all keyboard input is passed directly to the application,\n * and not interpreted by a window manager, if any.\n */\nextern DECLSPEC SDL_GrabMode SDLCALL SDL_WM_GrabInput(SDL_GrabMode mode);\n\n/*@}*/\n\n/** @internal Not in public API at the moment - do not use! */\nextern DECLSPEC int SDLCALL SDL_SoftStretch(SDL_Surface *src, SDL_Rect *srcrect,\n                                    SDL_Surface *dst, SDL_Rect *dstrect);\n                    \n/* Ends C function definitions when using C++ */\n#ifdef __cplusplus\n}\n#endif\n#include \"close_code.h\"\n\n#endif /* _SDL_video_h */\n"
  },
  {
    "path": "other/sdl/include/begin_code.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Library General Public\n    License as published by the Free Software Foundation; either\n    version 2 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Library General Public License for more details.\n\n    You should have received a copy of the GNU Library General Public\n    License along with this library; if not, write to the Free\n    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/** \n *  @file begin_code.h\n *  This file sets things up for C dynamic library function definitions,\n *  static inlined functions, and structures aligned at 4-byte alignment.\n *  If you don't like ugly C preprocessor code, don't look at this file. :)\n */\n\n/** \n *  @file begin_code.h\n *  This shouldn't be nested -- included it around code only.\n */\n#ifdef _begin_code_h\n#error Nested inclusion of begin_code.h\n#endif\n#define _begin_code_h\n\n/** \n *  @def DECLSPEC\n *  Some compilers use a special export keyword\n */\n#ifndef DECLSPEC\n# if defined(__BEOS__) || defined(__HAIKU__)\n#  if defined(__GNUC__)\n#   define DECLSPEC\t__declspec(dllexport)\n#  else\n#   define DECLSPEC\t__declspec(export)\n#  endif\n# elif defined(__WIN32__)\n#  ifdef __BORLANDC__\n#   ifdef BUILD_SDL\n#    define DECLSPEC \n#   else\n#    define DECLSPEC\t__declspec(dllimport)\n#   endif\n#  else\n#   define DECLSPEC\t__declspec(dllexport)\n#  endif\n# elif defined(__OS2__)\n#  ifdef __WATCOMC__\n#   ifdef BUILD_SDL\n#    define DECLSPEC\t__declspec(dllexport)\n#   else\n#    define DECLSPEC\n#   endif\n#  elif defined (__GNUC__) && __GNUC__ < 4\n#   /* Added support for GCC-EMX <v4.x */\n#   /* this is needed for XFree86/OS2 developement */\n#   /* F. Ambacher(anakor@snafu.de) 05.2008 */\n#   ifdef BUILD_SDL\n#    define DECLSPEC    __declspec(dllexport)\n#   else\n#    define DECLSPEC\n#   endif\n#  else\n#   define DECLSPEC\n#  endif\n# else\n#  if defined(__GNUC__) && __GNUC__ >= 4\n#   define DECLSPEC\t__attribute__ ((visibility(\"default\")))\n#  else\n#   define DECLSPEC\n#  endif\n# endif\n#endif\n\n/** \n *  @def SDLCALL\n *  By default SDL uses the C calling convention\n */\n#ifndef SDLCALL\n# if defined(__WIN32__) && !defined(__GNUC__)\n#  define SDLCALL __cdecl\n# elif defined(__OS2__)\n#  if defined (__GNUC__) && __GNUC__ < 4\n#   /* Added support for GCC-EMX <v4.x */\n#   /* this is needed for XFree86/OS2 developement */\n#   /* F. Ambacher(anakor@snafu.de) 05.2008 */\n#   define SDLCALL _cdecl\n#  else\n#   /* On other compilers on OS/2, we use the _System calling convention */\n#   /* to be compatible with every compiler */\n#   define SDLCALL _System\n#  endif\n# else\n#  define SDLCALL\n# endif\n#endif /* SDLCALL */\n\n#ifdef __SYMBIAN32__ \n#ifndef EKA2 \n#undef DECLSPEC\n#define DECLSPEC\n#elif !defined(__WINS__)\n#undef DECLSPEC\n#define DECLSPEC __declspec(dllexport)\n#endif /* !EKA2 */\n#endif /* __SYMBIAN32__ */\n\n/**\n *  @file begin_code.h\n *  Force structure packing at 4 byte alignment.\n *  This is necessary if the header is included in code which has structure\n *  packing set to an alternate value, say for loading structures from disk.\n *  The packing is reset to the previous value in close_code.h \n */\n#if defined(_MSC_VER) || defined(__MWERKS__) || defined(__BORLANDC__)\n#ifdef _MSC_VER\n#pragma warning(disable: 4103)\n#endif\n#ifdef __BORLANDC__\n#pragma nopackwarning\n#endif\n#pragma pack(push,4)\n#elif (defined(__MWERKS__) && defined(__MACOS__))\n#pragma options align=mac68k4byte\n#pragma enumsalwaysint on\n#endif /* Compiler needs structure packing set */\n\n/**\n *  @def SDL_INLINE_OKAY\n *  Set up compiler-specific options for inlining functions\n */\n#ifndef SDL_INLINE_OKAY\n#ifdef __GNUC__\n#define SDL_INLINE_OKAY\n#else\n/* Add any special compiler-specific cases here */\n#if defined(_MSC_VER) || defined(__BORLANDC__) || \\\n    defined(__DMC__) || defined(__SC__) || \\\n    defined(__WATCOMC__) || defined(__LCC__) || \\\n    defined(__DECC) || defined(__EABI__)\n#ifndef __inline__\n#define __inline__\t__inline\n#endif\n#define SDL_INLINE_OKAY\n#else\n#if !defined(__MRC__) && !defined(_SGI_SOURCE)\n#ifndef __inline__\n#define __inline__ inline\n#endif\n#define SDL_INLINE_OKAY\n#endif /* Not a funky compiler */\n#endif /* Visual C++ */\n#endif /* GNU C */\n#endif /* SDL_INLINE_OKAY */\n\n/**\n *  @def __inline__\n *  If inlining isn't supported, remove \"__inline__\", turning static\n *  inlined functions into static functions (resulting in code bloat\n *  in all files which include the offending header files)\n */\n#ifndef SDL_INLINE_OKAY\n#define __inline__\n#endif\n\n/**\n *  @def NULL\n *  Apparently this is needed by several Windows compilers\n */\n#if !defined(__MACH__)\n#ifndef NULL\n#ifdef __cplusplus\n#define NULL 0\n#else\n#define NULL ((void *)0)\n#endif\n#endif /* NULL */\n#endif /* ! Mac OS X - breaks precompiled headers */\n"
  },
  {
    "path": "other/sdl/include/close_code.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2009 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Library General Public\n    License as published by the Free Software Foundation; either\n    version 2 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Library General Public License for more details.\n\n    You should have received a copy of the GNU Library General Public\n    License along with this library; if not, write to the Free\n    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n/**\n *  @file close_code.h\n *  This file reverses the effects of begin_code.h and should be included\n *  after you finish any function and structure declarations in your headers\n */\n\n#undef _begin_code_h\n\n/**\n *  @file close_code.h\n *  Reset structure packing at previous byte alignment\n */\n#if defined(_MSC_VER) || defined(__MWERKS__) || defined(__WATCOMC__)  || defined(__BORLANDC__)\n#ifdef __BORLANDC__\n#pragma nopackwarning\n#endif\n#if (defined(__MWERKS__) && defined(__MACOS__))\n#pragma options align=reset\n#pragma enumsalwaysint reset\n#else\n#pragma pack(pop)\n#endif\n#endif /* Compiler needs structure packing set */\n\n"
  },
  {
    "path": "other/sdl/sdl.lua",
    "content": "SDL = {\n\tbasepath = PathDir(ModuleFilename()),\n\n\tOptFind = function (name, required)\n\t\tlocal check = function(option, settings)\n\t\t\toption.value = false\n\t\t\toption.use_sdlconfig = false\n\t\t\toption.use_winlib = 0\n\t\t\toption.use_osxframework = false\n\t\t\toption.lib_path = nil\n\t\t\t\n\t\t\tif ExecuteSilent(\"sdl-config\") > 0 and ExecuteSilent(\"sdl-config --cflags\") == 0 then\n\t\t\t\toption.value = true\n\t\t\t\toption.use_sdlconfig = true\n\t\t\tend\n\t\t\t\n\t\t\tif platform == \"win32\" then\n\t\t\t\toption.value = true\n\t\t\t\toption.use_winlib = 32\n\t\t\telseif platform == \"win64\" then\n\t\t\t\toption.value = true\n\t\t\t\toption.use_winlib = 64\n\t\t\tend\n\t\t\t\n\t\t\tif platform == \"macosx\" then\n\t\t\t\toption.value = true\n\t\t\t\toption.use_osxframework = true\n\t\t\t\toption.use_sdlconfig = false\n\t\t\tend\n\t\tend\n\t\t\n\t\tlocal apply = function(option, settings)\n\t\t\tif option.use_sdlconfig == true then\n\t\t\t\tsettings.cc.flags:Add(\"`sdl-config --cflags`\")\n\t\t\t\tsettings.link.flags:Add(\"`sdl-config --libs`\")\n\t\t\tend\n\n\t\t\tif option.use_osxframework == true then\n\t\t\t\tclient_settings.link.frameworks:Add(\"SDL\")\n\t\t\t\tclient_settings.cc.includes:Add(\"/Library/Frameworks/SDL.framework/Headers\")\n\t\t\tend\n\n\t\t\tif option.use_winlib > 0 then\n\t\t\t\tsettings.cc.includes:Add(SDL.basepath .. \"/include\")\n\t\t\t\tif option.use_winlib == 32 then\n\t\t\t\t\tsettings.link.libpath:Add(SDL.basepath .. \"/lib32\")\n\t\t\t\telse\n\t\t\t\t\tsettings.link.libpath:Add(SDL.basepath .. \"/lib64\")\n\t\t\t\tend\n\t\t\t\tsettings.link.libs:Add(\"SDL\")\n\t\t\t\tsettings.link.libs:Add(\"SDLmain\")\n\t\t\tend\n\t\tend\n\t\t\n\t\tlocal save = function(option, output)\n\t\t\toutput:option(option, \"value\")\n\t\t\toutput:option(option, \"use_sdlconfig\")\n\t\t\toutput:option(option, \"use_winlib\")\n\t\t\toutput:option(option, \"use_osxframework\")\n\t\tend\n\t\t\n\t\tlocal display = function(option)\n\t\t\tif option.value == true then\n\t\t\t\tif option.use_sdlconfig == true then return \"using sdl-config\" end\n\t\t\t\tif option.use_winlib == 32 then return \"using supplied win32 libraries\" end\n\t\t\t\tif option.use_winlib == 64 then return \"using supplied win64 libraries\" end\n\t\t\t\tif option.use_osxframework == true then return \"using osx framework\" end\n\t\t\t\treturn \"using unknown method\"\n\t\t\telse\n\t\t\t\tif option.required then\n\t\t\t\t\treturn \"not found (required)\"\n\t\t\t\telse\n\t\t\t\t\treturn \"not found (optional)\"\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t\n\t\tlocal o = MakeOption(name, 0, check, save, display)\n\t\to.Apply = apply\n\t\to.include_path = nil\n\t\to.lib_path = nil\n\t\to.required = required\n\t\treturn o\n\tend\n}\n"
  },
  {
    "path": "other/sdl/sdlnotes.txt",
    "content": "NOTE. This is a really stripped down version of SDL only used\r\nto compile teeworlds for windows. For a complete release of\r\nSDL, please visit their site at http://www.libsdl.org."
  },
  {
    "path": "readme.txt",
    "content": "Copyright (c) 2013 Magnus Auvinen\r\n\r\n\r\nThis software is provided 'as-is', without any express or implied\r\nwarranty. In no event will the authors be held liable for any damages\r\narising from the use of this software.\r\n\r\n\r\nPlease visit http://www.teeworlds.com for up-to-date information about \r\nthe game, including new versions, custom maps and much more.\r\n"
  },
  {
    "path": "scripts/SDL_keysym.h",
    "content": "/*\n    SDL - Simple DirectMedia Layer\n    Copyright (C) 1997-2006 Sam Lantinga\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n    Sam Lantinga\n    slouken@libsdl.org\n*/\n\n#ifndef _SDL_keysym_h\n#define _SDL_keysym_h\n\n/* What we really want is a mapping of every raw key on the keyboard.\n   To support international keyboards, we use the range 0xA1 - 0xFF\n   as international virtual keycodes.  We'll follow in the footsteps of X11...\n   The names of the keys\n */\n \ntypedef enum {\n\t/* The keyboard syms have been cleverly chosen to map to ASCII */\n\tSDLK_UNKNOWN\t\t= 0,\n\tSDLK_FIRST\t\t= 0,\n\tSDLK_BACKSPACE\t\t= 8,\n\tSDLK_TAB\t\t= 9,\n\tSDLK_CLEAR\t\t= 12,\n\tSDLK_RETURN\t\t= 13,\n\tSDLK_PAUSE\t\t= 19,\n\tSDLK_ESCAPE\t\t= 27,\n\tSDLK_SPACE\t\t= 32,\n\tSDLK_EXCLAIM\t\t= 33,\n\tSDLK_QUOTEDBL\t\t= 34,\n\tSDLK_HASH\t\t= 35,\n\tSDLK_DOLLAR\t\t= 36,\n\tSDLK_AMPERSAND\t\t= 38,\n\tSDLK_QUOTE\t\t= 39,\n\tSDLK_LEFTPAREN\t\t= 40,\n\tSDLK_RIGHTPAREN\t\t= 41,\n\tSDLK_ASTERISK\t\t= 42,\n\tSDLK_PLUS\t\t= 43,\n\tSDLK_COMMA\t\t= 44,\n\tSDLK_MINUS\t\t= 45,\n\tSDLK_PERIOD\t\t= 46,\n\tSDLK_SLASH\t\t= 47,\n\tSDLK_0\t\t\t= 48,\n\tSDLK_1\t\t\t= 49,\n\tSDLK_2\t\t\t= 50,\n\tSDLK_3\t\t\t= 51,\n\tSDLK_4\t\t\t= 52,\n\tSDLK_5\t\t\t= 53,\n\tSDLK_6\t\t\t= 54,\n\tSDLK_7\t\t\t= 55,\n\tSDLK_8\t\t\t= 56,\n\tSDLK_9\t\t\t= 57,\n\tSDLK_COLON\t\t= 58,\n\tSDLK_SEMICOLON\t\t= 59,\n\tSDLK_LESS\t\t= 60,\n\tSDLK_EQUALS\t\t= 61,\n\tSDLK_GREATER\t\t= 62,\n\tSDLK_QUESTION\t\t= 63,\n\tSDLK_AT\t\t\t= 64,\n\t/* \n\t   Skip uppercase letters\n\t */\n\tSDLK_LEFTBRACKET\t= 91,\n\tSDLK_BACKSLASH\t\t= 92,\n\tSDLK_RIGHTBRACKET\t= 93,\n\tSDLK_CARET\t\t= 94,\n\tSDLK_UNDERSCORE\t\t= 95,\n\tSDLK_BACKQUOTE\t\t= 96,\n\tSDLK_a\t\t\t= 97,\n\tSDLK_b\t\t\t= 98,\n\tSDLK_c\t\t\t= 99,\n\tSDLK_d\t\t\t= 100,\n\tSDLK_e\t\t\t= 101,\n\tSDLK_f\t\t\t= 102,\n\tSDLK_g\t\t\t= 103,\n\tSDLK_h\t\t\t= 104,\n\tSDLK_i\t\t\t= 105,\n\tSDLK_j\t\t\t= 106,\n\tSDLK_k\t\t\t= 107,\n\tSDLK_l\t\t\t= 108,\n\tSDLK_m\t\t\t= 109,\n\tSDLK_n\t\t\t= 110,\n\tSDLK_o\t\t\t= 111,\n\tSDLK_p\t\t\t= 112,\n\tSDLK_q\t\t\t= 113,\n\tSDLK_r\t\t\t= 114,\n\tSDLK_s\t\t\t= 115,\n\tSDLK_t\t\t\t= 116,\n\tSDLK_u\t\t\t= 117,\n\tSDLK_v\t\t\t= 118,\n\tSDLK_w\t\t\t= 119,\n\tSDLK_x\t\t\t= 120,\n\tSDLK_y\t\t\t= 121,\n\tSDLK_z\t\t\t= 122,\n\tSDLK_DELETE\t\t= 127,\n\t/* End of ASCII mapped keysyms */\n\n\t/* International keyboard syms */\n\tSDLK_WORLD_0\t\t= 160,\t\t/* 0xA0 */\n\tSDLK_WORLD_1\t\t= 161,\n\tSDLK_WORLD_2\t\t= 162,\n\tSDLK_WORLD_3\t\t= 163,\n\tSDLK_WORLD_4\t\t= 164,\n\tSDLK_WORLD_5\t\t= 165,\n\tSDLK_WORLD_6\t\t= 166,\n\tSDLK_WORLD_7\t\t= 167,\n\tSDLK_WORLD_8\t\t= 168,\n\tSDLK_WORLD_9\t\t= 169,\n\tSDLK_WORLD_10\t\t= 170,\n\tSDLK_WORLD_11\t\t= 171,\n\tSDLK_WORLD_12\t\t= 172,\n\tSDLK_WORLD_13\t\t= 173,\n\tSDLK_WORLD_14\t\t= 174,\n\tSDLK_WORLD_15\t\t= 175,\n\tSDLK_WORLD_16\t\t= 176,\n\tSDLK_WORLD_17\t\t= 177,\n\tSDLK_WORLD_18\t\t= 178,\n\tSDLK_WORLD_19\t\t= 179,\n\tSDLK_WORLD_20\t\t= 180,\n\tSDLK_WORLD_21\t\t= 181,\n\tSDLK_WORLD_22\t\t= 182,\n\tSDLK_WORLD_23\t\t= 183,\n\tSDLK_WORLD_24\t\t= 184,\n\tSDLK_WORLD_25\t\t= 185,\n\tSDLK_WORLD_26\t\t= 186,\n\tSDLK_WORLD_27\t\t= 187,\n\tSDLK_WORLD_28\t\t= 188,\n\tSDLK_WORLD_29\t\t= 189,\n\tSDLK_WORLD_30\t\t= 190,\n\tSDLK_WORLD_31\t\t= 191,\n\tSDLK_WORLD_32\t\t= 192,\n\tSDLK_WORLD_33\t\t= 193,\n\tSDLK_WORLD_34\t\t= 194,\n\tSDLK_WORLD_35\t\t= 195,\n\tSDLK_WORLD_36\t\t= 196,\n\tSDLK_WORLD_37\t\t= 197,\n\tSDLK_WORLD_38\t\t= 198,\n\tSDLK_WORLD_39\t\t= 199,\n\tSDLK_WORLD_40\t\t= 200,\n\tSDLK_WORLD_41\t\t= 201,\n\tSDLK_WORLD_42\t\t= 202,\n\tSDLK_WORLD_43\t\t= 203,\n\tSDLK_WORLD_44\t\t= 204,\n\tSDLK_WORLD_45\t\t= 205,\n\tSDLK_WORLD_46\t\t= 206,\n\tSDLK_WORLD_47\t\t= 207,\n\tSDLK_WORLD_48\t\t= 208,\n\tSDLK_WORLD_49\t\t= 209,\n\tSDLK_WORLD_50\t\t= 210,\n\tSDLK_WORLD_51\t\t= 211,\n\tSDLK_WORLD_52\t\t= 212,\n\tSDLK_WORLD_53\t\t= 213,\n\tSDLK_WORLD_54\t\t= 214,\n\tSDLK_WORLD_55\t\t= 215,\n\tSDLK_WORLD_56\t\t= 216,\n\tSDLK_WORLD_57\t\t= 217,\n\tSDLK_WORLD_58\t\t= 218,\n\tSDLK_WORLD_59\t\t= 219,\n\tSDLK_WORLD_60\t\t= 220,\n\tSDLK_WORLD_61\t\t= 221,\n\tSDLK_WORLD_62\t\t= 222,\n\tSDLK_WORLD_63\t\t= 223,\n\tSDLK_WORLD_64\t\t= 224,\n\tSDLK_WORLD_65\t\t= 225,\n\tSDLK_WORLD_66\t\t= 226,\n\tSDLK_WORLD_67\t\t= 227,\n\tSDLK_WORLD_68\t\t= 228,\n\tSDLK_WORLD_69\t\t= 229,\n\tSDLK_WORLD_70\t\t= 230,\n\tSDLK_WORLD_71\t\t= 231,\n\tSDLK_WORLD_72\t\t= 232,\n\tSDLK_WORLD_73\t\t= 233,\n\tSDLK_WORLD_74\t\t= 234,\n\tSDLK_WORLD_75\t\t= 235,\n\tSDLK_WORLD_76\t\t= 236,\n\tSDLK_WORLD_77\t\t= 237,\n\tSDLK_WORLD_78\t\t= 238,\n\tSDLK_WORLD_79\t\t= 239,\n\tSDLK_WORLD_80\t\t= 240,\n\tSDLK_WORLD_81\t\t= 241,\n\tSDLK_WORLD_82\t\t= 242,\n\tSDLK_WORLD_83\t\t= 243,\n\tSDLK_WORLD_84\t\t= 244,\n\tSDLK_WORLD_85\t\t= 245,\n\tSDLK_WORLD_86\t\t= 246,\n\tSDLK_WORLD_87\t\t= 247,\n\tSDLK_WORLD_88\t\t= 248,\n\tSDLK_WORLD_89\t\t= 249,\n\tSDLK_WORLD_90\t\t= 250,\n\tSDLK_WORLD_91\t\t= 251,\n\tSDLK_WORLD_92\t\t= 252,\n\tSDLK_WORLD_93\t\t= 253,\n\tSDLK_WORLD_94\t\t= 254,\n\tSDLK_WORLD_95\t\t= 255,\t\t/* 0xFF */\n\n\t/* Numeric keypad */\n\tSDLK_KP0\t\t= 256,\n\tSDLK_KP1\t\t= 257,\n\tSDLK_KP2\t\t= 258,\n\tSDLK_KP3\t\t= 259,\n\tSDLK_KP4\t\t= 260,\n\tSDLK_KP5\t\t= 261,\n\tSDLK_KP6\t\t= 262,\n\tSDLK_KP7\t\t= 263,\n\tSDLK_KP8\t\t= 264,\n\tSDLK_KP9\t\t= 265,\n\tSDLK_KP_PERIOD\t\t= 266,\n\tSDLK_KP_DIVIDE\t\t= 267,\n\tSDLK_KP_MULTIPLY\t= 268,\n\tSDLK_KP_MINUS\t\t= 269,\n\tSDLK_KP_PLUS\t\t= 270,\n\tSDLK_KP_ENTER\t\t= 271,\n\tSDLK_KP_EQUALS\t\t= 272,\n\n\t/* Arrows + Home/End pad */\n\tSDLK_UP\t\t\t= 273,\n\tSDLK_DOWN\t\t= 274,\n\tSDLK_RIGHT\t\t= 275,\n\tSDLK_LEFT\t\t= 276,\n\tSDLK_INSERT\t\t= 277,\n\tSDLK_HOME\t\t= 278,\n\tSDLK_END\t\t= 279,\n\tSDLK_PAGEUP\t\t= 280,\n\tSDLK_PAGEDOWN\t\t= 281,\n\n\t/* Function keys */\n\tSDLK_F1\t\t\t= 282,\n\tSDLK_F2\t\t\t= 283,\n\tSDLK_F3\t\t\t= 284,\n\tSDLK_F4\t\t\t= 285,\n\tSDLK_F5\t\t\t= 286,\n\tSDLK_F6\t\t\t= 287,\n\tSDLK_F7\t\t\t= 288,\n\tSDLK_F8\t\t\t= 289,\n\tSDLK_F9\t\t\t= 290,\n\tSDLK_F10\t\t= 291,\n\tSDLK_F11\t\t= 292,\n\tSDLK_F12\t\t= 293,\n\tSDLK_F13\t\t= 294,\n\tSDLK_F14\t\t= 295,\n\tSDLK_F15\t\t= 296,\n\n\t/* Key state modifier keys */\n\tSDLK_NUMLOCK\t\t= 300,\n\tSDLK_CAPSLOCK\t\t= 301,\n\tSDLK_SCROLLOCK\t\t= 302,\n\tSDLK_RSHIFT\t\t= 303,\n\tSDLK_LSHIFT\t\t= 304,\n\tSDLK_RCTRL\t\t= 305,\n\tSDLK_LCTRL\t\t= 306,\n\tSDLK_RALT\t\t= 307,\n\tSDLK_LALT\t\t= 308,\n\tSDLK_RMETA\t\t= 309,\n\tSDLK_LMETA\t\t= 310,\n\tSDLK_LSUPER\t\t= 311,\t\t/* Left \"Windows\" key */\n\tSDLK_RSUPER\t\t= 312,\t\t/* Right \"Windows\" key */\n\tSDLK_MODE\t\t= 313,\t\t/* \"Alt Gr\" key */\n\tSDLK_COMPOSE\t\t= 314,\t\t/* Multi-key compose key */\n\n\t/* Miscellaneous function keys */\n\tSDLK_HELP\t\t= 315,\n\tSDLK_PRINT\t\t= 316,\n\tSDLK_SYSREQ\t\t= 317,\n\tSDLK_BREAK\t\t= 318,\n\tSDLK_MENU\t\t= 319,\n\tSDLK_POWER\t\t= 320,\t\t/* Power Macintosh power key */\n\tSDLK_EURO\t\t= 321,\t\t/* Some european keyboards */\n\tSDLK_UNDO\t\t= 322,\t\t/* Atari keyboard has Undo */\n\n\t/* Add any other keys here */\n\n\tSDLK_LAST\n} SDLKey;\n\n/* Enumeration of valid key mods (possibly OR'd together) */\ntypedef enum {\n\tKMOD_NONE  = 0x0000,\n\tKMOD_LSHIFT= 0x0001,\n\tKMOD_RSHIFT= 0x0002,\n\tKMOD_LCTRL = 0x0040,\n\tKMOD_RCTRL = 0x0080,\n\tKMOD_LALT  = 0x0100,\n\tKMOD_RALT  = 0x0200,\n\tKMOD_LMETA = 0x0400,\n\tKMOD_RMETA = 0x0800,\n\tKMOD_NUM   = 0x1000,\n\tKMOD_CAPS  = 0x2000,\n\tKMOD_MODE  = 0x4000,\n\tKMOD_RESERVED = 0x8000\n} SDLMod;\n\n#define KMOD_CTRL\t(KMOD_LCTRL|KMOD_RCTRL)\n#define KMOD_SHIFT\t(KMOD_LSHIFT|KMOD_RSHIFT)\n#define KMOD_ALT\t(KMOD_LALT|KMOD_RALT)\n#define KMOD_META\t(KMOD_LMETA|KMOD_RMETA)\n\n#endif /* _SDL_keysym_h */\n"
  },
  {
    "path": "scripts/build.py",
    "content": "import imp, optparse, os, re, shutil, sys, zipfile\nos.chdir(os.path.dirname(os.path.realpath(sys.argv[0])) + \"/..\")\nimport twlib\n\narguments = optparse.OptionParser()\narguments.add_option(\"-b\", \"--url-bam\", default = \"http://github.com/matricks/bam/archive/master.zip\", help = \"URL from which the bam source code will be downloaded\")\narguments.add_option(\"-t\", \"--url-teeworlds\", default = \"http://github.com/teeworlds/teeworlds/archive/master.zip\", help = \"URL from which the teeworlds source code will be downloaded\")\narguments.add_option(\"-r\", \"--release-type\", default = \"server_release client_release\", help = \"Parts of the game which should be builded (for example client_release, debug, server_release or a combination of any of them)\")\n(options, arguments) = arguments.parse_args()\n\nbam = options.url_bam[7:].split(\"/\")\nversion_bam = re.search(r\"\\d\\.\\d\\.\\d\", bam[len(bam)-1])\nif version_bam:\n\tversion_bam = version_bam.group(0)\nelse:\n\tversion_bam = \"trunk\"\nteeworlds = options.url_teeworlds[7:].split(\"/\")\nversion_teeworlds = re.search(r\"\\d\\.\\d\\.\\d\", teeworlds[len(teeworlds)-1])\nif version_teeworlds:\n\tversion_teeworlds = version_teeworlds.group(0)\nelse:\n\tversion_teeworlds = \"trunk\"\n\nbam_execution_path = \"\"\nif version_bam < \"0.3.0\":\n\tbam_execution_path = \"src%s\" % os.sep\n\nname = \"teeworlds\"\n\nflag_clean = True\nflag_download = True\nflag_unpack = True\nflag_build_bam = True\nflag_build_teeworlds = True\nflag_make_release = True\n\nif os.name == \"nt\":\n\tplatform = \"win32\"\nelse:\n\t# get name\n\tosname = os.popen(\"uname\").readline().strip().lower()\n\tif osname == \"darwin\":\n\t\tosname = \"osx\"\n\n\t# get arch\n\tmachine = os.popen(\"uname -m\").readline().strip().lower()\n\tarch = \"unknown\"\n\n\tif machine[0] == \"i\" and machine[2:] == \"86\":\n\t\tarch = \"x86\"\n\telif machine == \"x86_64\":\n\t\tarch = \"x86_64\"\n\telif \"power\" in machine.lower():\n\t\tarch = \"ppc\"\n\n\tplatform = osname + \"_\" + arch\n\nprint(\"%s-%s-%s\" % (name, version_teeworlds, platform))\n\nroot_dir = os.getcwd() + os.sep\nwork_dir = root_dir + \"scripts/work\"\n\ndef unzip(filename, where):\n\ttry:\n\t\tz = zipfile.ZipFile(filename, \"r\")\n\texcept:\n\t\treturn False\n\tlist = \"\\n\"\n\tfor name in z.namelist():\n\t\tlist += \"%s\\n\" % name\n\t\ttry: os.makedirs(where+\"/\"+os.path.dirname(name))\n\t\texcept: pass\n\n\t\ttry:\n\t\t\tf = open(where+\"/\"+name, \"wb\")\n\t\t\tf.write(z.read(name))\n\t\t\tf.close()\n\t\texcept: pass\n\n\tz.close()\n\n\tdirectory = \"[^/\\n]*?/\"\n\tpart_1 = \"(?<=\\n)\"\n\tpart_2 = \"[^/\\n]+(?=\\n)\"\n\tregular_expression = r\"%s%s\" % (part_1, part_2)\n\tmain_directory = re.search(regular_expression, list)\n\twhile main_directory == None:\n\t\tpart_1 += directory\n\t\tregular_expression = r\"%s%s\" % (part_1, part_2)\n\t\tmain_directory = re.search(regular_expression, list)\n\tmain_directory = re.search(r\".*/\", \"./%s\" % main_directory.group(0))\n\treturn main_directory.group(0)\n\ndef bail(reason):\n\tprint(reason)\n\tos.chdir(work_dir)\n\tsys.exit(-1)\n\ndef clean():\n\tprint(\"*** cleaning ***\")\n\ttry: shutil.rmtree(work_dir)\n\texcept: pass\n\ndef file_exists(file):\n\ttry:\n\t\topen(file).close()\n\t\treturn True\n\texcept:\n\t\treturn False;\n\ndef search_object(directory, object):\n\tdirectory = os.listdir(directory)\n\tfor entry in directory:\n\t\tmatch = re.search(object, entry)\n\t\tif match != None:\n\t\t\treturn entry\n\n# clean\nif flag_clean:\n\tclean()\n\n# make dir\ntry: os.mkdir(work_dir)\nexcept: pass\n\n# change dir\nos.chdir(work_dir)\n\n# download\nif flag_download:\n\tprint(\"*** downloading bam source package ***\")\n\tsrc_package_bam = twlib.fetch_file(options.url_bam)\n\tif src_package_bam:\n\t\tif version_bam == 'trunk':\n\t\t\tversion = re.search(r\"-[^-]*?([^-]*?)\\.[^.]*$\", src_package_bam)\n\t\t\tif version:\n\t\t\t\tversion_bam = version.group(1)\n\telse:\n\t\tbail(\"couldn't find bam source package and couldn't download it\")\n\n\tprint(\"*** downloading %s source package ***\" % name)\n\tsrc_package_teeworlds = twlib.fetch_file(options.url_teeworlds)\n\tif src_package_teeworlds:\n\t\tif version_teeworlds == 'trunk':\n\t\t\tversion = re.search(r\"-[^-]*?([^-]*?)\\.[^.]*$\", src_package_teeworlds)\n\t\t\tif version:\n\t\t\t\tversion_teeworlds = version.group(1)\n\telse:\n\t\tbail(\"couldn't find %s source package and couldn't download it\" % name)\n\n# unpack\nif flag_unpack:\n\tprint(\"*** unpacking source ***\")\n\tif hasattr(locals(), 'src_package_bam') == False:\n\t\tsrc_package_bam = search_object(work_dir, r\"bam.*?\\.\")\n\t\tif not src_package_bam:\n\t\t\tbail(\"couldn't find bam source package\")\n\tsrc_dir_bam = unzip(src_package_bam, \".\")\n\tif not src_dir_bam:\n\t\tbail(\"couldn't unpack bam source package\")\n\n\tif hasattr(locals(), 'src_package_teeworlds') == False:\n\t\tsrc_package_teeworlds = search_object(work_dir, r\"teeworlds.*?\\.\")\n\t\tif not src_package_bam:\n\t\t\tbail(\"couldn't find %s source package\" % name)\n\tsrc_dir_teeworlds = unzip(src_package_teeworlds, \".\")\n\tif not src_dir_teeworlds:\n\t\tbail(\"couldn't unpack %s source package\" % name)\n\n# build bam\nif flag_build_bam:\n\tprint(\"*** building bam ***\")\n\tos.chdir(\"%s/%s\" % (work_dir, src_dir_bam))\n\tif os.name == \"nt\":\n\t\tif os.system(\"g++ -v >nul 2>&1\") == 0:\n\t\t\tprint(\"using gcc\")\n\t\t\tos.system(\"make_win32_mingw.bat\")\n\t\telse:\n\t\t\tprint(\"using cl\")\n\t\t\tos.system(\"make_win32_msvc.bat\")\n\t\tif file_exists(\"%sbam.exe\" % bam_execution_path) == False:\n\t\t\tbail(\"failed to build bam\")\n\telse:\n\t\tos.system(\"sh make_unix.sh\")\n\t\tif file_exists(\"%sbam\" % bam_execution_path) == False:\n\t\t\tbail(\"failed to build bam\")\n\tos.chdir(work_dir)\n\n# build the game\nif flag_build_teeworlds:\n\tprint(\"*** building %s ***\" % name)\n\tif hasattr(locals(), 'src_dir_bam') == False:\n\t\tsrc_dir_bam = search_object(work_dir, r\"bam[^\\.]*$\") + os.sep\n\t\tif src_dir_bam:\n\t\t\tdirectory = src_dir_bam + bam_execution_path\n\t\t\tfile = r\"bam\"\n\t\t\tif os.name == \"nt\":\n\t\t\t\tfile += r\"\\.exe\"\n\t\t\tif not search_object(directory, file):\n\t\t\t\tbail(\"couldn't find bam\")\n\t\telse:\n\t\t\tbail(\"couldn't find bam\")\n\tif hasattr(locals(), 'src_dir_teeworlds') == False:\n\t\tsrc_dir_teeworlds = search_object(work_dir, r\"teeworlds[^\\.]*$\")\n\t\tif not src_dir_teeworlds:\n\t\t\tbail(\"couldn't find %s source\" % name)\n\tcommand = 1\n\tif os.name == \"nt\":\n\t\tif os.system(\"g++ -v >nul 2>&1\") == 0:\n\t\t\tprint(\"using gcc\")\n\t\t\tos.chdir(src_dir_teeworlds)\n\t\t\tcommand = os.system('\"%s\\\\%s%sbam\" %s' % (work_dir, src_dir_bam, bam_execution_path, options.release_type))\n\t\telse:\n\t\t\tprint(\"using cl\")\n\t\t\tfile = open(\"build.bat\", \"wb\")\n\t\t\tcontent = \"@echo off\\n\"\n\t\t\tcontent += \"@REM check if we already have the tools in the environment\\n\"\n\t\t\tcontent += \"if exist \\\"%VCINSTALLDIR%\\\" (\\ngoto compile\\n)\\n\"\n\t\t\tcontent += \"@REM Check for Visual Studio\\n\"\n\t\t\tcontent += \"if exist \\\"%VS100COMNTOOLS%\\\" (\\nset VSPATH=\\\"%VS100COMNTOOLS%\\\"\\ngoto set_env\\n)\\n\"\n\t\t\tcontent += \"if exist \\\"%VS90COMNTOOLS%\\\" (\\nset VSPATH=\\\"%VS90COMNTOOLS%\\\"\\ngoto set_env\\n)\\n\"\n\t\t\tcontent += \"if exist \\\"%VS80COMNTOOLS%\\\" (\\nset VSPATH=\\\"%VS80COMNTOOLS%\\\"\\ngoto set_env\\n)\\n\\n\"\n\t\t\tcontent += \"echo You need Microsoft Visual Studio 8, 9 or 10 installed\\n\"\n\t\t\tcontent += \"exit\\n\"\n\t\t\tcontent += \"@ setup the environment\\n\"\n\t\t\tcontent += \":set_env\\n\"\n\t\t\tcontent += \"call %VSPATH%vsvars32.bat\\n\\n\"\n\t\t\tcontent += \":compile\\n\"\n\t\t\tcontent += 'cd %s\\n\"%s\\\\%s%sbam\" config\\n\"%s\\\\%s%sbam\" %s' % (src_dir_teeworlds, work_dir, src_dir_bam, bam_execution_path, work_dir, src_dir_bam, bam_execution_path, options.release_type)\n\t\t\tfile.write(content.encode())\n\t\t\tfile.close()\n\t\t\tcommand = os.system(\"build.bat\")\n\telse:\n\t\tos.chdir(src_dir_teeworlds)\n\t\tcommand = os.system(\"%s/%s%sbam %s\" % (work_dir, src_dir_bam, bam_execution_path, options.release_type))\n\tif command != 0:\n\t\tbail(\"failed to build %s\" % name)\n\tos.chdir(work_dir)\n\n# make release\nif flag_make_release:\n\tprint(\"*** making release ***\")\n\tif hasattr(locals(), 'src_dir_teeworlds') == False:\n\t\tsrc_dir_teeworlds = search_object(work_dir, r\"teeworlds[^\\.]*$\")\n\t\tif not src_dir_teeworlds:\n\t\t\tbail(\"couldn't find %s source\" % name)\n\tos.chdir(src_dir_teeworlds)\n\tcommand = '\"%s/%s/scripts/make_release.py\" %s %s' % (work_dir, src_dir_teeworlds, version_teeworlds, platform)\n\tif os.name != \"nt\":\n\t\tcommand = \"python %s\" % command\n\tif os.system(command) != 0:\n\t\tbail(\"failed to make a relase of %s\" % name)\n\tfinal_output = \"FAIL\"\n\tfor f in os.listdir(\".\"):\n\t\tif version_teeworlds in f and platform in f and name in f and (\".zip\" in f or \".tar.gz\" in f):\n\t\t\tfinal_output = f\n\tos.chdir(work_dir)\n\tshutil.copy(\"%s/%s\" % (src_dir_teeworlds, final_output), \"../\"+final_output)\n\tos.chdir(root_dir)\n\tclean()\n\nprint(\"*** all done ***\")\n"
  },
  {
    "path": "scripts/check_header_guards.py",
    "content": "import os\n\n\nPATH = \"../src/\"\n\n\ndef check_file(filename):\n\tfile = open(filename)\n\twhile 1:\n\t\tline = file.readline()\n\t\tif len(line) == 0:\n\t\t\tbreak\n\t\tif line[0] == \"/\" or line[0] == \"*\" or line[0] == \"\\r\" or line[0] == \"\\n\" or line[0] == \"\\t\":\n\t\t\tcontinue\n\t\tif line[:7] == \"#ifndef\":\n\t\t\thg = \"#ifndef \" + (\"_\".join(filename.split(PATH)[1].split(\"/\"))[:-2]).upper() + \"_H\"\n\t\t\tif line[:-1] != hg:\n\t\t\t\tprint \"Wrong header guard in \" + filename\n\t\telse:\n\t\t\tprint \"Missing header guard in \" + filename\n\t\tbreak\n\tfile.close()\n\n\n\ndef check_dir(dir):\n\tlist = os.listdir(dir)\n\tfor file in list:\n\t\tif os.path.isdir(dir+file):\n\t\t\tif file != \"external\" and file != \"generated\":\n\t\t\t\tcheck_dir(dir+file+\"/\")\n\t\telif file[-2:] == \".h\" and file != \"keynames.h\":\n\t\t\tcheck_file(dir+file)\n\ncheck_dir(PATH)\n"
  },
  {
    "path": "scripts/cmd5.py",
    "content": "import hashlib, sys, re\n\nalphanum = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_\".encode()\n\ndef cstrip(lines):\n\td = \"\".encode()\n\tfor l in lines:\n\t\tl = re.sub(\"#.*\".encode(), \"\".encode(), l)\n\t\tl = re.sub(\"//.*\".encode(), \"\".encode(), l)\n\t\td += l + \" \".encode()\n\td = re.sub(\"\\/\\*.*?\\*/\".encode(), \"\".encode(), d) # remove /* */ comments\n\td = d.replace(\"\\t\".encode(), \" \".encode()) # tab to space\n\td = re.sub(\"  *\".encode(), \" \".encode(), d) # remove double spaces\n\td = re.sub(\"\".encode(), \"\".encode(), d) # remove /* */ comments\n\n\td = d.strip()\n\n\t# this eats up cases like 'n {'\n\ti = 1\n\twhile i < len(d)-2:\n\t\tif d[i:i + 1] == \" \".encode():\n\t\t\tif not (d[i - 1:i] in alphanum and d[i+1:i + 2] in alphanum):\n\t\t\t\td = d[:i] + d[i + 1:]\n\t\ti += 1\n\treturn d\n\nf = \"\".encode()\nfor filename in sys.argv[1:]:\n\tf += cstrip([l.strip() for l in open(filename, \"rb\")])\n\nhash = hashlib.md5(f).hexdigest().lower()[16:]\n#TODO 0.7: improve nethash creation\nprint('#define GAME_NETVERSION_HASH \"%s\"' % hash)\n"
  },
  {
    "path": "scripts/compiler.py",
    "content": "#!/usr/bin/python\n\nimport sys\nimport struct\nimport os\n\noption_ptrsize = struct.calcsize(\"P\")\noption_intsize = struct.calcsize(\"l\")\noption_floatsize = struct.calcsize(\"f\")\noption_inttype = \"long\"\noption_floattype = \"float\"\n\nclass node:\n\tdef __init__(self):\n\t\tself.values = []\n\t\tself.children = []\n\t\tself.parent = 0\n\t\t\n\tdef name(self):\n\t\tif len(self.values):\n\t\t\treturn self.values[0]\n\t\treturn \"\"\n\n\tdef debug_print(self, level):\n\t\tprint (\"  \"*level) + \" \".join(self.values),\n\t\tif len(self.children):\n\t\t\tprint \"{\"\n\t\t\tfor c in self.children:\n\t\t\t\tc.debug_print(level+1)\n\t\t\tprint (\"  \"*level)+\"}\"\n\t\telse:\n\t\t\tprint \"\"\n\t\t\n\tdef debug_root(self):\n\t\tfor c in self.children:\n\t\t\tc.debug_print(0)\n\n\t# TODO: should return list of items in the tree,\n\tdef gather(self, str):\n\t\tdef recurse(parts, path, node):\n\t\t\tif not len(parts):\n\t\t\t\tr = {}\n\t\t\t\tpath = path + \".\" + node.values[0]\n\t\t\t\tr = [node]\n\t\t\t\t#print \"found\", path\n\t\t\t\treturn r\n\t\t\t\t\n\t\t\tl = []\n\t\t\tfor c in node.children:\n\t\t\t\tif parts[0] == \"*\" or c.values[0] == parts[0]:\n\t\t\t\t\tif len(node.values):\n\t\t\t\t\t\tif len(path):\n\t\t\t\t\t\t\tl += recurse(parts[1:], path+\".\"+node.values[0], c)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tl += recurse(parts[1:], node.values[0], c)\n\t\t\t\t\telse:\n\t\t\t\t\t\tl += recurse(parts[1:], path, c)\n\t\t\treturn l\n\t\t\n\t\tparts = str.split(\".\")\n\t\treturn recurse(parts, \"\", self)\t\n\t\t\n\tdef find_node(self, str):\n\t\tparts = str.split(\".\")\n\t\tnode = self\n\t\tfor part in parts:\n\t\t\tif len(part) == 0:\n\t\t\t\tcontinue\n\t\t\tif part == \"parent\":\n\t\t\t\tnode = node.parent\n\t\t\telse:\n\t\t\t\tfound = 0\n\t\t\t\tfor c in node.children:\n\t\t\t\t\tif part == c.values[0]:\n\t\t\t\t\t\tnode = c\n\t\t\t\t\t\tfound = 1\n\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\n\t\tif node == self:\n\t\t\treturn\n\t\treturn node\n\t\t\n\tdef get_single(self, str):\n\t\tparts = str.split(\"@\")\n\t\tindex = -1\n\t\tif len(parts) == 2:\n\t\t\tindex = int(parts[1])\n\t\t\n\t\tnode = self\n\t\tif len(parts[0]):\n\t\t\tnode = self.find_node(parts[0])\n\t\t\n\t\tif not node:\n\t\t\tprint \"failed to get\", str\n\t\t\treturn Null\n\t\t\n\t\tif index == -1:\n\t\t\treturn node.get_path()[1:]\n\t\treturn node.values[index]\n\n\tdef get_path(self):\n\t\tif self.parent == 0:\n\t\t\treturn \"\"\n\t\treturn self.parent.get_path() + \".\" + self.values[0]\n\n\tdef get_single_name(self, str):\n\t\treturn self.get_path()[1:] + \".\" + str\n\nclass parser:\n\tlines = []\n\t\t\n\tdef parse_node(self, this_node):\n\t\twhile len(self.lines):\n\t\t\tline = self.lines.pop(0)\t\t# grab line\n\t\t\t\t\n\t\t\tfields = line.strip().split() # TODO: improve this to handle strings with spaces\n\t\t\tif not len(fields):\n\t\t\t\tcontinue\n\t\t\t\n\t\t\tif fields[-1] == '{':\n\t\t\t\tnew_node = node()\n\t\t\t\tnew_node.parent = this_node\n\t\t\t\tnew_node.values = fields[:-1]\n\t\t\t\tthis_node.children += [new_node]\n\t\t\t\tself.parse_node(new_node)\n\t\t\telif fields[-1] == '}':\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tnew_node = node()\n\t\t\t\tnew_node.parent = this_node\n\t\t\t\tnew_node.values = fields\n\t\t\t\tthis_node.children += [new_node]\n\n\tdef parse_file(self, filename):\n\t\tself.lines = file(filename).readlines()\n\t\tn = node()\n\t\tself.parse_node(n)\n\t\treturn n\n\t\ndef parse_file(filename):\n\treturn parser().parse_file(filename)\n\nclass pointer:\n\tdef __init__(self, index, target):\n\t\tself.index = index\n\t\tself.target = target\n\nclass data_constructor:\n\tdef __init__(self):\n\t\tself.data = \"\"\n\t\tself.trans = 0\n\t\tself.pointers = []\n\t\tself.targets = {}\n\t\tself.enums = {}\n\n\tdef get_type(self, s):\n\t\treturn self.trans.types[s]\n\n\tdef allocate(self, size):\n\t\tindex = len(self.data)\n\t\tself.data += \"\\0\"*size\n\t\treturn index\n\n\tdef add_pointer(self, index, target):\n\t\tself.pointers += [pointer(index, target)]\n\n\tdef add_enum(self, name, value):\n\t\tself.enums[name] = value\n\t\t\n\tdef get_enum_value(self, name):\n\t\tif not name in self.enums:\n\t\t\tprint \"ERROR: couldn't find enum '%s'\" % (name)\n\t\treturn self.enums[name]\n\t\t\n\tdef add_target(self, target, index):\n\t\t# TODO: warn about duplicates\n\t\t#print \"add_target(target='%s' index=%d)\" % (target, index)\n\t\tself.targets[target] = index\n\t\n\tdef write(self, index, size, data):\n\t\ttry:\n\t\t\tself.data = self.data[:index] + data + self.data[index+size:]\n\t\texcept:\n\t\t\tprint \"write error:\"\n\t\t\tprint \"\\tself.data =\", self.data\n\t\t\tprint \"\\tdata =\", data\n\t\t\t\n\tdef patch_pointers(self):\n\t\tfor p in self.pointers:\n\t\t\tif p.target in self.targets:\n\t\t\t\ti = self.targets[p.target]\n\t\t\t\t#print \"ptr @ %d -> %s -> %d\" % (p.index, p.target, i)\n\t\t\t\tdata = struct.pack(\"P\", i)\n\t\t\t\tself.write(p.index, len(data), data)\n\t\t\telse:\n\t\t\t\tprint \"ERROR: couldn't find target '%s' for pointer at %d\" % (p.target, p.index)\n\nclass type:\n\tdef __init__(self):\n\t\tself.name = \"\"\n\t\t\n\tdef size(self):\n\t\tpass\n\nclass structure:\n\tdef __init__(self):\n\t\tself.name = \"\"\n\t\tself.members = []\n\n\tdef size(self):\n\t\ts = 0\n\t\tfor m in self.members:\n\t\t\ts += m.size()\n\t\treturn s\n\t\n\tdef emit_header_code(self, out):\n\t\tprint >>out, \"struct\", self.name\n\t\tprint >>out, \"{\"\n\t\tfor m in self.members:\n\t\t\tfor l in m.get_code():\n\t\t\t\tprint >>out, \"\\t\" + l\n\t\tprint >>out, \"};\"\n\t\tprint >>out, \"\"\n\n\tdef emit_source_code(self, out):\n\t\tprint >>out, \"static void patch_ptr_%s(%s *self, char *base)\" % (self.name, self.name)\n\t\tprint >>out, \"{\"\n\t\tfor m in self.members:\n\t\t\tfor l in m.get_patch_code(\"self\", \"base\"):\n\t\t\t\tprint >>out, \"\\t\" + l\n\t\tprint >>out, \"}\"\n\t\tprint >>out, \"\"\n\n\tdef emit_data(self, cons, index, src_data):\n\t\t#print self.name+\":\"\n\t\tmember_index = index\n\t\tfor m in self.members:\n\t\t\t#print \"\\t\" + m.name\n\t\t\tm.emit_data(cons, member_index, src_data)\n\t\t\tmember_index += m.size()\n\nclass variable:\n\tdef __init__(self):\n\t\tself.expr = \"\"\n\t\tself.type = \"\"\n\t\tself.subtype = \"\"\n\t\n\tdef get_code(self):\n\t\treturn []\n\n\tdef get_patch_code(self, ptrname, basename):\n\t\treturn []\n\t\n\tdef emit_data(self, cons, index, src_data):\n\t\tpass\n\nclass variable_int(variable):\n\tdef get_code(self):\n\t\treturn [\"%s %s;\" % (option_inttype, self.name)]\n\tdef size(self):\n\t\treturn option_intsize\n\tdef emit_data(self, cons, index, src_data):\n\t\ttry:\n\t\t\tvalue = int(self.expr)\n\t\texcept:\n\t\t\tvalue = int(src_data.get_single(self.expr))\n\t\t#print \"int\", self.name, \"=\", value, \"@\", index\n\t\tdata = struct.pack(\"l\", value)\n\t\tcons.write(index, len(data), data)\n\nclass variable_float(variable):\n\tdef get_code(self):\n\t\treturn [\"%s %s;\" % (option_floattype, self.name)]\n\tdef size(self):\n\t\treturn option_floatsize\n\tdef emit_data(self, cons, index, src_data):\n\t\ttry:\n\t\t\tvalue = float(self.expr)\n\t\texcept:\n\t\t\tvalue = float(src_data.get_single(self.expr))\n\t\t#print \"int\", self.name, \"=\", value, \"@\", index\n\t\tdata = struct.pack(\"f\", value)\n\t\tcons.write(index, len(data), data)\n\t\t\nclass variable_string(variable):\n\tdef get_code(self):\n\t\treturn [\"char *%s;\" % (self.name)]\n\tdef get_patch_code(self, ptrname, basename):\n\t\treturn [\"patch_ptr((char **)&(%s->%s), %s);\" % (ptrname, self.name, basename)]\n\tdef size(self):\n\t\treturn option_ptrsize\n\tdef emit_data(self, cons, index, src_data):\n\t\tstring = src_data.get_single(self.expr)\n\t\tstring = string.strip()[1:-1] # skip \" and \"\n\n\t\tstring_index = cons.allocate(len(string)+1)\n\t\tcons.write(string_index, len(string), string)\n\n\t\tdata = struct.pack(\"P\", string_index) # TODO: solve this\n\t\tcons.write(index, len(data), data)\n\nclass variable_ptr(variable):\n\tdef get_code(self):\n\t\treturn [\"%s *%s;\" % (self.subtype, self.name)]\n\tdef get_patch_code(self, ptrname, basename):\n\t\treturn [\"patch_ptr((char**)&(%s->%s), %s);\" % (ptrname, self.name, basename)]\n\tdef size(self):\n\t\treturn option_ptrsize\n\tdef emit_data(self, cons, index, src_data):\n\t\ttarget = src_data.get_single(self.expr)\n\t\tcons.add_pointer(index, target)\n\nclass variable_enum(variable):\n\tdef get_code(self):\n\t\treturn [\"long *%s;\" % (self.name)]\n\tdef size(self):\n\t\treturn option_intsize\n\tdef emit_data(self, cons, index, src_data):\n\t\ttarget = src_data.get_single(self.expr)\n\t\tdata = struct.pack(\"l\", cons.get_enum_value(target))\n\t\tcons.write(index, len(data), data)\n\nclass variable_instance(variable):\n\tdef get_code(self):\n\t\treturn [\"%s %s;\" % (self.subtype, self.name)]\n\tdef get_patch_code(self, ptrname, basename):\n\t\treturn [\"patch_ptr_%s(&(%s->%s), %s);\" % (self.subtype, ptrname, self.name, basename)]\n\tdef size(self):\n\t\treturn self.translator.types[self.subtype].size()\n\tdef emit_data(self, cons, index, src_data):\n\t\ttarget = src_data.find_node(self.expr)\n\t\ttranslator.types[self.subtype].emit_data(cons, index, target)\n\t\t#target = \n\t\t#cons.add_pointer(index, target)\n\nclass variable_array(variable):\n\tdef get_code(self):\n\t\treturn [\"long num_%s;\" % self.name,\n\t\t\t\"%s *%s;\" % (self.subtype, self.name)]\n\tdef get_patch_code(self, ptrname, baseptr):\n\t\tcode = []\n\t\tcode += [\"patch_ptr((char**)&(%s->%s), %s);\" % (ptrname, self.name, baseptr)]\n\t\tcode += [\"for(int i = 0; i < %s->num_%s; i++)\" % (ptrname, self.name)]\n\t\tcode += [\"\\tpatch_ptr_%s(%s->%s+i, %s);\" % (self.subtype, ptrname, self.name, baseptr)]\n\t\treturn code\n\tdef emit_data(self, cons, index, src_data):\n\t\tarray_data = src_data.gather(self.expr)\n\t\tarray_type = cons.get_type(self.subtype)\n\t\tsize = array_type.size()*len(array_data)\n\n\t\t#print \"packing array\", self.name\n\t\t#print \"\\ttype =\", array_type.name\n\t\t#print \"\\tsize =\", array_type.size()\n\t\tarray_index = cons.allocate(size)\n\t\tdata = struct.pack(\"lP\", len(array_data), array_index) # TODO: solve this\n\t\tcons.write(index, len(data), data)\n\n\t\tmember_index = array_index\n\t\tfor node in array_data:\n\t\t\tcons.add_target(node.get_path()[1:], member_index)\n\t\t\tarray_type.emit_data(cons, member_index, node)\n\t\t\tmember_index += array_type.size()\n\t\t\t#print \"array\", member_index\n\n\tdef size(self):\n\t\treturn option_ptrsize+option_intsize\n\nclass const_arrayint:\n\tdef __init__(self):\n\t\tself.name = \"\"\n\t\tself.values = []\n\t\t\n\tdef emit_header_code(self, out):\n\t\tprint >>out, \"enum\"\n\t\tprint >>out, \"{\"\n\t\tfor i in xrange(0, len(self.values)):\n\t\t\tprint >>out, \"\\t%s_%s = %d,\" % (self.name.upper(), self.values[i].upper(), i)\n\t\t\n\t\tprint >>out, \"\\tNUM_%sS = %d\" % (self.name.upper(), len(self.values))\n\t\tprint >>out, \"};\"\n\t\tprint >>out, \"\"\n\t\t\nclass translator:\n\tdef __init__(self):\n\t\tself.types = {}\n\t\tself.structs = []\n\t\tself.constants = []\n\t\tself.data = 0\n\t\tself.srcdata = 0\n\n\t\tself.types[\"int\"] = variable_int()\n\t\tself.types[\"float\"] = variable_float()\n\t\tself.types[\"string\"] = variable_string()\n\t\tself.types[\"ptr\"] = variable_ptr()\n\t\tself.types[\"array\"] = variable_array()\n\n\tdef parse_variable(self, node):\n\t\tif len(node.values) != 4:\n\t\t\tprint node.values\n\t\t\traise \"error parsing variable\"\n\t\t\t\n\t\ttype = node.values[0]\n\t\tsubtype = \"\"\n\t\tif type == \"int\":\n\t\t\tv = variable_int()\n\t\telif type == \"enum\":\n\t\t\tv = variable_enum()\n\t\telif type == \"float\":\n\t\t\tv = variable_float()\n\t\telif type == \"string\":\n\t\t\tv = variable_string()\n\t\telse:\n\t\t\t# complex type\n\t\t\tparts = type.split(\":\")\n\t\t\tif len(parts) != 2:\n\t\t\t\traise \"can't emit code for variable %s of type %s\" % (self.name, self.type)\n\t\t\telif parts[0] == \"ptr\":\n\t\t\t\tsubtype = parts[1]\n\t\t\t\tv = variable_ptr()\n\t\t\telif parts[0] == \"instance\":\n\t\t\t\tsubtype = parts[1]\n\t\t\t\tv = variable_instance()\n\t\t\telif parts[0] == \"array\":\n\t\t\t\tsubtype = parts[1]\n\t\t\t\tv = variable_array()\n\t\t\telse:\n\t\t\t\traise \"can't emit code for variable %s of type %s\" % (self.name, self.type)\n\n\t\tv.translator = self\n\t\tv.type = node.values[0]\n\t\tv.subtype = subtype\n\t\tv.name = node.values[1]\n\t\tassignment = node.values[2]\n\t\tv.expr = node.values[3]\n\t\tif assignment != \"=\":\n\t\t\traise \"error parsing variable. expected =\"\n\t\treturn v\n\n\tdef parse_struct(self, node):\n\t\tif len(node.values) != 2:\n\t\t\traise \"error parsing struct\"\n\t\ts = structure()\n\t\ts.name = node.values[1]\n\t\t\n\t\tfor statement in node.children:\n\t\t\ts.members += [self.parse_variable(statement)]\n\t\treturn s\n\t\n\tdef parse_constant(self, node):\n\t\tif len(node.values) != 5:\n\t\t\tprint node.values\n\t\t\traise \"error parsing constant\"\n\t\t\n\t\ttype = node.values[1]\n\t\tname = node.values[2]\n\t\tassignment = node.values[3]\n\t\texpression = node.values[4]\n\t\t\n\t\tif assignment != \"=\":\n\t\t\tprint node.values\n\t\t\traise \"error parsing constant\"\n\t\t\t\n\t\tints = const_arrayint()\n\t\tints.name = name\n\t\t\n\t\titems = self.srcdata.gather(expression)\n\t\tfor c in items:\n\t\t\tints.values += [c.name()]\n\t\tself.constants += [ints]\n\t\t\n\tdef parse(self, script, srcdata):\n\t\tself.srcdata = srcdata\n\t\tfor statement in script.children:\n\t\t\tif statement.values[0] == \"struct\":\n\t\t\t\ts = self.parse_struct(statement)\n\t\t\t\tself.structs += [s]\n\t\t\t\tself.types[s.name] = s\n\t\t\telif statement.values[0] == \"const\":\n\t\t\t\tself.parse_constant(statement)\n\t\t\telse:\n\t\t\t\traise \"unknown statement:\" + statement\n\t\t\t\t\n\tdef emit_header_code(self, out):\n\t\tfor c in self.constants:\n\t\t\tc.emit_header_code(out)\n\t\t\n\t\tfor s in self.structs:\n\t\t\ts.emit_header_code(out)\n\t\tprint >>out, \"\"\n\t\tprint >>out, \"struct data_container *load_data_from_file(const char *filename);\"\n\t\tprint >>out, \"struct data_container *load_data_from_memory(unsigned char *filename);\"\n\t\tprint >>out, \"\"\n\t\t\n\n\tdef emit_source_code(self, out, header_filename):\n\t\tprint >>out, '''\n\n#include \"%s\"\n#include <stdio.h>\n#include <stdlib.h>\n\nstatic void patch_ptr(char **ptr, char *base)\n{\n\t*ptr = base+(size_t)(*ptr);\n}\n''' % header_filename\n\n\t\tfor s in self.structs:\n\t\t\ts.emit_source_code(out)\n\t\tprint >>out, '''\n\ndata_container *load_data_from_memory(unsigned char *mem)\n{\n\tif(mem[0] != sizeof(void*))\n\t\treturn 0;\n\tif(mem[1] != sizeof(long))\n\t\treturn 0;\n\tif(mem[2] != sizeof(float))\n\t\treturn 0;\n\n\t/* patch all pointers */\n\tdata_container *con = (data_container*)(mem + 4);\n\tpatch_ptr_data_container(con, (char *)con);\n\treturn con;\n}\n\ndata_container *load_data_from_file(const char *filename)\n{\n\tunsigned char *data = 0;\n\tint size;\n\n\t/* open file */\n\tFILE *f = fopen(filename, \"rb\");\n\n\t/* get size */\n\tfseek(f, 0, SEEK_END);\n\tsize = ftell(f);\n\tfseek(f, 0, SEEK_SET);\n\n\t/* allocate, read data and close file */\n\tdata = (unsigned char *)malloc(size);\n\tfread(data, 1, size, f);\n\tfclose(f);\n\n\treturn load_data_from_memory(data);\n}\n\n'''\n\n\tdef emit_data(self):\n\t\tfor s in self.structs:\n\t\t\tif s.name == \"data_container\":\n\t\t\t\t#print \"found data_container\"\n\t\t\t\tcons = data_constructor()\n\t\t\t\tcons.trans = self\n\t\t\t\ti = cons.allocate(s.size())\n\t\t\t\ts.emit_data(cons, i, self.srcdata)\n\t\t\t\tcons.patch_pointers()\n\t\t\t\theader = struct.pack(\"bbbb\", option_ptrsize, option_intsize, option_floatsize, 0)\n\t\t\t\treturn header + cons.data\n\t\t\t\ndef create_translator(script, srcdata):\n\tt = translator()\n\tt.parse(script, srcdata)\n\treturn t\n\t\ndef validate(script, validator):\n\tdef validate_values(values, check):\n\t\tif not len(check) or check[0] == \"*\":\n\t\t\tprint \"too many values\"\n\t\t\treturn\n\t\tp = check[0].split(\":\")\n\t\ttype = p[0]\n\t\tname = p[1]\n\t\t\n\t\t# TODO: check type and stuff\n\t\n\t\t# recurse\n\t\tif len(values) > 1:\n\t\t\tif not len(check):\n\t\t\t\tprint \"unexpected value\"\n\t\t\tvalidate_values(values[1:], check[1:])\n\t\telse:\n\t\t\tif len(check) > 1 and check[1] != \"*\":\n\t\t\t\tprint \"to few values\"\n\t\n\tif len(script.values):\n\t\tvalidate_values(script.values, validator.values)\n\t\n\tfor child in script.children:\n\t\ttag = child.values[0]\n\t\tn = validator.find_node(\"tag:\"+tag)\n\t\tif not n:\n\t\t\tfound = 0\n\t\t\tfor vc in validator.children:\n\t\t\t\tif \"ident:\" in vc.values[0]:\n\t\t\t\t\tvalidate(child, vc)\n\t\t\t\t\tprint vc.values[0]\n\t\t\t\t\tfound = 1\n\t\t\t\t\tbreak\n\t\t\t\t\t\n\t\t\tif not found:\n\t\t\t\tprint \"error:\", tag, \"not found\"\n\t\telse:\n\t\t\tprint \"tag:\"+tag\n\t\t\tvalidate(child, n)\n\ninput_filename = sys.argv[1]\nscript_filename = sys.argv[2]\n\noutput_filename = 0\ncoutput_filename = 0\nheader_filename = 0\nsource_filename = 0\nsheader_filename = 0\n\nif sys.argv[3] == '-h':\n\theader_filename = sys.argv[4]\nelif sys.argv[3] == '-s':\n\tsource_filename = sys.argv[4]\n\tsheader_filename = sys.argv[5]\nelif sys.argv[3] == '-d':\n\toutput_filename = sys.argv[4]\nelif sys.argv[3] == '-c':\n\tcoutput_filename = sys.argv[4]\n\nsrcdata = parse_file(input_filename)\nscript = parse_file(script_filename)\n\ntranslator = create_translator(script, srcdata)\n\nif header_filename:\n\ttranslator.emit_header_code(file(header_filename, \"w\"))\nif source_filename:\n\ttranslator.emit_source_code(file(source_filename, \"w\"), os.path.basename(sheader_filename))\n\nif output_filename:\n\trawdata = translator.emit_data()\n\tfile(output_filename, \"wb\").write(rawdata)\nif coutput_filename:\n\ti = 0\n\trawdata = translator.emit_data()\n\tf = file(coutput_filename, \"w\")\n\n\tprint >>f,\"unsigned char internal_data[] = {\"\n\tprint >>f,str(ord(rawdata[0])),\n\tfor d in rawdata[1:]:\n\t    s = \",\"+str(ord(d))\n\t    print >>f,s,\n\t    i += len(s)+1\n\t\n\t    if i >= 70:\n\t        print >>f,\"\"\n\t        i = 0\n\tprint >>f,\"\"\n\tprint >>f,\"};\"\n\tprint >>f,\"\"\n\tf.close()\n"
  },
  {
    "path": "scripts/copyright.py",
    "content": "import os, sys\nos.chdir(os.path.dirname(os.path.realpath(sys.argv[0])) + \"/..\")\n\nnotice = [b\"/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\\n\", b\"/* If you are missing that file, acquire a complete release at teeworlds.com.                */\\n\"]\nexclude = [\"src%sengine%sexternal\" % (os.sep, os.sep), \"src%sosxlaunch\" % os.sep]\nupdated_files = 0\n\ndef fix_copyright_notice(filename):\n\tglobal updated_files\n\tf = open(filename, \"rb\")\n\tlines = f.readlines()\n\tf.close()\n\n\ti = 0\n\tlength_lines = len(lines)\n\tif length_lines > 0:\n\t\twhile i <= length_lines and (lines[i].decode(\"utf-8\").lstrip()[:2] == \"//\" or lines[i].decode(\"utf-8\").lstrip()[:2] == \"/*\" and lines[i].decode(\"utf-8\").rstrip()[-2:] == \"*/\") and (\"Magnus\" in lines[i].decode(\"utf-8\") or \"magnus\" in lines[i].decode(\"utf-8\") or \"Auvinen\" in lines[i].decode(\"utf-8\") or \"auvinen\" in lines[i].decode(\"utf-8\") or \"license\" in lines[i].decode(\"utf-8\") or \"teeworlds\" in lines[i].decode(\"utf-8\")):\n\t\t\ti += 1\n\tlength_notice = len(notice)\n\tif i > 0:\n\t\tj = 0\n\t\twhile lines[j] == notice[j]:\n\t\t\tj += 1\n\t\t\tif j == length_notice:\n\t\t\t\treturn\n\t\tk = j\n\t\tj = 0\n\t\twhile j < length_notice -1 - k:\n\t\t\tlines = [notice[j]] + lines\n\t\t\tj += 1\n\t\twhile j < length_notice:\n\t\t\tlines[j] = notice[j]\n\t\t\tj += 1\n\tif length_lines == 0 or i == 0:\n\t\tj = length_notice - 1\n\t\twhile j >= 0:\n\t\t\tlines = [notice[j]] + lines\n\t\t\tj -= 1\n\topen(filename, \"wb\").writelines(lines)\n\tupdated_files += 1\n\nskip = False\nfor root, dirs, files in os.walk(\"src\"):\n\tfor excluding in exclude:\n\t\tif root[:len(excluding)] == excluding:\n\t\t\tskip = True\n\t\t\tbreak\n\tif skip == True:\n\t\tskip = False\n\t\tcontinue\n\tfor name in files:\n\t\tfilename = os.path.join(root, name)\n\n\t\tif filename[-2:] != \".c\" and filename[-4:] != \".cpp\" and filename[-2:] != \".h\":\n\t\t\tcontinue\n\n\t\tfix_copyright_notice(filename)\n\noutput = \"file\"\nif updated_files != 1:\n\toutput += \"s\"\nprint(\"*** updated %d %s ***\" % (updated_files, output))\n"
  },
  {
    "path": "scripts/count_source.sh",
    "content": "svn blame `svn -R ls | grep ^src | grep -v external | grep -v /$ | grep -v \\.txt` | python scripts/process_blame.py\n"
  },
  {
    "path": "scripts/dat2c.py",
    "content": "import sys\n\ndata = file(sys.argv[1], \"rb\").read()\n\ni = 0\nprint \"unsigned char\", sys.argv[2], \"[] = {\"\nprint str(ord(data[0])),\nfor d in data[1:]:\n\ts = \",\"+str(ord(d))\n\tprint s,\n\ti += len(s)+1\n\n\tif i >= 70:\n\t\tprint \"\"\n\t\ti = 0\nprint \"\"\nprint \"};\"\n"
  },
  {
    "path": "scripts/font_converter.py",
    "content": "from __future__ import with_statement\nimport struct\nimport sys\nimport re\n\ndef convert(input, output):\n    with open(input, \"r\") as in_file:\n        with open(output, \"w\") as out_file:\n            def build_dic(parts):\n                dic = {}\n\n                for part in parts:\n                    key, value = part.split('=')\n\n                    try:\n                        dic[key] = int(value)\n                    except:\n                        dic[key] = value\n\n                return dic\n\n            def get_entry(line):\n                while line[-1] == \"\\r\" or line[-1] == \"\\n\":\n                    line = line[0:-1]\n                parts = []\n\n                quote = 0\n                part = \"\"\n\n                for c in line:\n                    if c == \"\\\"\":\n                        quote = 1-quote\n                    elif c == \" \" and not quote:\n                        if part:\n                            parts.append(part)\n                            part = \"\"\n                    else:\n                        part += c\n\n                if part:\n                    parts.append(part)\n\n                type = parts[0]\n\n                dic = build_dic(parts[1:])\n\n                return type, dic\n\n            def write_int16(val):\n                out_file.write(struct.pack('<h', val))\n\n            def write_info(dic):\n                write_int16(dic[\"size\"])\n\n            def write_common(dic):\n                write_int16(dic[\"scaleW\"])\n                write_int16(dic[\"scaleH\"])\n                write_int16(dic[\"lineHeight\"])\n                write_int16(dic[\"base\"])\n\n            def write_page(dic):\n                pass\n\n            def write_chars(dic):\n                pass\n\n            def write_char(dic):\n                write_int16(dic[\"x\"])\n                write_int16(dic[\"y\"])\n                write_int16(dic[\"width\"])\n                write_int16(dic[\"height\"])\n                write_int16(dic[\"xoffset\"])\n                write_int16(dic[\"yoffset\"])\n                write_int16(dic[\"xadvance\"])\n\n            def write_default_char():\n                write_int16(0)\n                write_int16(0)\n                write_int16(0)\n                write_int16(0)\n                write_int16(0)\n                write_int16(0)\n                write_int16(0)\n\n            def write_kernings(dic):\n                pass\n\n            def write_kerning(dic):\n                write_int16(dic[\"amount\"])\n\n            def write_default_kerning():\n                write_int16(0)\n\n            chars = []\n            kernings = []\n            for i in range(256):\n                chars.append(None)\n            for i in range(256*256):\n                kernings.append(None)\n\n            def save_char(dic):\n                if dic[\"id\"] < 256:\n                    chars[dic[\"id\"]] = dic\n\n            def save_kerning(dic):\n                kernings[dic[\"first\"] + dic[\"second\"]*256] = dic\n\n            write_table = {\n                \"info\": write_info,\n                \"common\": write_common,\n                \"page\": write_page,\n                \"chars\": write_chars,\n                \"char\": save_char,\n                \"kernings\": write_kernings,\n                \"kerning\": save_kerning\n            }\n\n            for line in in_file:\n                type, dic = get_entry(line)\n                \n                write_table[type](dic)\n\n            for i in range(256):\n                if chars[i]:\n                    write_char(chars[i])\n                else:\n                    write_default_char()\n\n            for i in range(256*256):\n                if kernings[i]:\n                    write_kerning(kernings[i])\n                else:\n                    write_default_kerning()\n\nif len(sys.argv) >= 2:\n    print \"converting...\"\n\n    filenames = sys.argv[1:]\n    for filename in filenames:\n        input = filename\n        output = re.sub(\"fnt$\", \"tfnt\", input)\n            \n        print \"input: %s, output: %s\" % (input, output)\n        convert(input, output)\n    print \"done!\"\nelse:\n    print \"font converter! converts .fnt files to teeworlds .tfnt\"\n    print \"usage: font_converter <input>\"\n"
  },
  {
    "path": "scripts/font_installer.sh",
    "content": "echo Generating .fnts...\n../../font_generator/a.out\npython ../scripts/font_converter.py default*.fnt\n"
  },
  {
    "path": "scripts/gen_keys.py",
    "content": "import sys, os\n\n# genereate keys.h file\nf = file(\"src/engine/keys.h\", \"w\")\n\nkeynames = []\nfor i in range(0, 512):\n\tkeynames += [\"&%d\"%i]\n\nprint >>f, \"#ifndef ENGINE_KEYS_H\"\nprint >>f, \"#define ENGINE_KEYS_H\"\nprint >>f, '/* AUTO GENERATED! DO NOT EDIT MANUALLY! */'\nprint >>f, \"enum\"\nprint >>f, \"{\"\n\nhighestid = 0\nfor line in open(\"scripts/SDL_keysym.h\"):\n\tl = line.strip().split(\"=\")\n\tif len(l) == 2 and \"SDLK_\" in line:\n\t\tkey = l[0].strip().replace(\"SDLK_\", \"KEY_\")\n\t\tvalue = int(l[1].split(\",\")[0].strip())\n\t\tprint >>f, \"\\t%s = %d,\"%(key, value)\n\t\t\n\t\tkeynames[value] = key.replace(\"KEY_\", \"\").lower()\n\t\t\n\t\tif value > highestid:\n\t\t\thighestid =value\n\nprint >>f, \"\\tKEY_MOUSE_1 = %d,\"%(highestid+1); keynames[highestid+1] = \"mouse1\"\nprint >>f, \"\\tKEY_MOUSE_2 = %d,\"%(highestid+2); keynames[highestid+2] = \"mouse2\"\nprint >>f, \"\\tKEY_MOUSE_3 = %d,\"%(highestid+3); keynames[highestid+3] = \"mouse3\"\nprint >>f, \"\\tKEY_MOUSE_4 = %d,\"%(highestid+4); keynames[highestid+4] = \"mouse4\"\nprint >>f, \"\\tKEY_MOUSE_5 = %d,\"%(highestid+5); keynames[highestid+5] = \"mouse5\"\nprint >>f, \"\\tKEY_MOUSE_6 = %d,\"%(highestid+6); keynames[highestid+6] = \"mouse6\"\nprint >>f, \"\\tKEY_MOUSE_7 = %d,\"%(highestid+7); keynames[highestid+7] = \"mouse7\"\nprint >>f, \"\\tKEY_MOUSE_8 = %d,\"%(highestid+8); keynames[highestid+8] = \"mouse8\"\nprint >>f, \"\\tKEY_MOUSE_WHEEL_UP = %d,\"%(highestid+9); keynames[highestid+9] = \"mousewheelup\"\nprint >>f, \"\\tKEY_MOUSE_WHEEL_DOWN = %d,\"%(highestid+10); keynames[highestid+10] = \"mousewheeldown\"\nprint >>f, \"\\tKEY_LAST,\"\n\nprint >>f, \"};\"\nprint >>f, \"\"\nprint >>f, \"#endif\"\n\n# generate keynames.c file\nf = file(\"src/engine/client/keynames.h\", \"w\")\nprint >>f, '/* AUTO GENERATED! DO NOT EDIT MANUALLY! */'\nprint >>f, ''\nprint >>f, '#ifndef KEYS_INCLUDE'\nprint >>f, '#error do not include this header!'\nprint >>f, '#endif'\nprint >>f, ''\nprint >>f, \"#include <string.h>\"\nprint >>f, \"\"\nprint >>f, \"const char g_aaKeyStrings[512][16] =\"\nprint >>f, \"{\"\nfor n in keynames:\n\tprint >>f, '\\t\"%s\",'%n\n\nprint >>f, \"};\"\nprint >>f, \"\"\n\nf.close()\n\n"
  },
  {
    "path": "scripts/linecount.sh",
    "content": "#!/bin/sh\nwc `find . -iname *.cpp` `find . -iname *.h` `find . -iname *.c`\n"
  },
  {
    "path": "scripts/make_docs.sh",
    "content": "perl docs/tool/NaturalDocs -i src/game -i src/engine -xi src/engine/external -p docs/conf -o html docs/output\n"
  },
  {
    "path": "scripts/make_release.py",
    "content": "import shutil, optparse, os, re, sys, zipfile\nos.chdir(os.path.dirname(os.path.realpath(sys.argv[0])) + \"/..\")\nimport twlib\n\narguments = optparse.OptionParser(usage=\"usage: %prog VERSION PLATFORM [options]\\n\\nVERSION  - Version number\\nPLATFORM - Target platform (f.e. linux86, linux86_64, osx, src, win32)\")\narguments.add_option(\"-l\", \"--url-languages\", default = \"http://github.com/teeworlds/teeworlds-translation/archive/master.zip\", help = \"URL from which the teeworlds language files will be downloaded\")\narguments.add_option(\"-m\", \"--url-maps\", default = \"http://github.com/teeworlds/teeworlds-maps/archive/master.zip\", help = \"URL from which the teeworlds maps files will be downloaded\")\narguments.add_option(\"-s\", \"--source-dir\", help = \"Source directory which is used for building the package\")\n(options, arguments) = arguments.parse_args()\nif len(sys.argv) != 3:\n\tprint(\"wrong number of arguments\")\n\tprint(sys.argv[0], \"VERSION PLATFORM\")\n\tsys.exit(-1)\nif options.source_dir != None:\n\tif os.path.exists(options.source_dir) == False:\n\t\tprint(\"Source directory \" + options.source_dir + \" doesn't exist\")\n\t\texit(1)\n\tos.chdir(options.source_dir)\n\n#valid_platforms = [\"win32\", \"osx\", \"linux86\", \"linux86_64\", \"src\"]\n\nname = \"teeworlds\"\nversion = sys.argv[1]\nplatform = sys.argv[2]\nexe_ext = \"\"\nuse_zip = 0\nuse_gz = 1\nuse_dmg = 0\nuse_bundle = 0\ninclude_data = True\ninclude_exe = True\ninclude_src = False\n\n#if not options.platform in valid_platforms:\n#\tprint(\"not a valid platform\")\n#\tprint(valid_platforms)\n#\tsys.exit(-1)\n\nif platform == \"src\":\n\tinclude_exe = False\n\tinclude_src = True\n\tuse_zip = 1\nelif platform == 'win32':\n\texe_ext = \".exe\"\n\tuse_zip = 1\n\tuse_gz = 0\nelif platform == 'osx':\n\tuse_dmg = 1\n\tuse_gz = 0\n\tuse_bundle = 1\n\ndef unzip(filename, where):\n\ttry:\n\t\tz = zipfile.ZipFile(filename, \"r\")\n\texcept:\n\t\treturn False\n\tfor name in z.namelist():\n\t\tz.extract(name, where)\n\tz.close()\n\treturn z.namelist()[0]\n\ndef copydir(src, dst, excl=[]):\n\tfor root, dirs, files in os.walk(src, topdown=True):\n\t\tif \"/.\" in root or \"\\\\.\" in root:\n\t\t\tcontinue\n\t\tfor name in dirs:\n\t\t\tif name[0] != '.':\n\t\t\t\tos.mkdir(os.path.join(dst, root, name))\n\t\tfor name in files:\n\t\t\tif name[0] != '.':\n\t\t\t\tshutil.copy(os.path.join(root, name), os.path.join(dst, root, name))\n\ndef copyfiles(src, dst):\n\tdir = os.listdir(src)\n\tfor files in dir:\n\t\tshutil.copy(os.path.join(src, files), os.path.join(dst, files))\n\ndef clean():\n\tprint(\"*** cleaning ***\")\n\ttry:\n\t\tshutil.rmtree(package_dir)\n\t\tshutil.rmtree(languages_dir)\n\t\tshutil.rmtree(maps_dir)\n\t\tos.remove(src_package_languages)\n\t\tos.remove(src_package_maps)\n\texcept: pass\n\t\npackage = \"%s-%s-%s\" %(name, version, platform)\npackage_dir = package\n\nprint(\"cleaning target\")\nshutil.rmtree(package_dir, True)\nos.mkdir(package_dir)\n\nprint(\"download and extract languages\")\nsrc_package_languages = twlib.fetch_file(options.url_languages)\nif not src_package_languages:\n\tprint(\"couldn't download languages\")\n\tsys.exit(-1)\nlanguages_dir = unzip(src_package_languages, \".\")\nif not languages_dir:\n\tprint(\"couldn't unzip languages\")\n\tsys.exit(-1)\n\nprint(\"download and extract maps\")\nsrc_package_maps = twlib.fetch_file(options.url_maps)\nif not src_package_maps:\n\tprint(\"couldn't download maps\")\n\tsys.exit(-1)\nmaps_dir = unzip(src_package_maps, \".\")\nif not maps_dir:\n\tprint(\"couldn't unzip maps\")\n\tsys.exit(-1)\n\nprint(\"adding files\")\nshutil.copy(\"readme.txt\", package_dir)\nshutil.copy(\"license.txt\", package_dir)\nshutil.copy(\"storage.cfg\", package_dir)\n\nif include_data and not use_bundle:\n\tos.mkdir(os.path.join(package_dir, \"data\"))\n\tcopydir(\"data\", package_dir)\n\tcopyfiles(languages_dir, package_dir+\"/data/languages\")\n\tcopyfiles(maps_dir, package_dir+\"/data/maps\")\n\tif platform[:3] == \"win\":\n\t\tshutil.copy(\"other/config_directory.bat\", package_dir)\n\t\tshutil.copy(\"SDL.dll\", package_dir)\n\t\tshutil.copy(\"freetype.dll\", package_dir)\n\nif include_exe and not use_bundle:\n\tshutil.copy(name+exe_ext, package_dir)\n\tshutil.copy(name+\"_srv\"+exe_ext, package_dir)\n\t\nif include_src:\n\tfor p in [\"src\", \"scripts\", \"datasrc\", \"other\", \"objs\"]:\n\t\tos.mkdir(os.path.join(package_dir, p))\n\t\tcopydir(p, package_dir)\n\tshutil.copy(\"bam.lua\", package_dir)\n\tshutil.copy(\"configure.lua\", package_dir)\n\nif use_bundle:\n\tbins = [name, name+'_srv', 'serverlaunch']\n\tplatforms = ('x86', 'x86_64', 'ppc')\n\tfor bin in bins:\n\t\tto_lipo = []\n\t\tfor p in platforms:\n\t\t\tfname = bin+'_'+p\n\t\t\tif os.path.isfile(fname):\n\t\t\t\tto_lipo.append(fname)\n\t\tif to_lipo:\n\t\t\tos.system(\"lipo -create -output \"+bin+\" \"+\" \".join(to_lipo))\n\n\t# create Teeworlds appfolder\n\tclientbundle_content_dir = os.path.join(package_dir, \"Teeworlds.app/Contents\")\n\tclientbundle_bin_dir = os.path.join(clientbundle_content_dir, \"MacOS\")\n\tclientbundle_resource_dir = os.path.join(clientbundle_content_dir, \"Resources\")\n\tclientbundle_framework_dir = os.path.join(clientbundle_content_dir, \"Frameworks\")\n\tos.mkdir(os.path.join(package_dir, \"Teeworlds.app\"))\n\tos.mkdir(clientbundle_content_dir)\n\tos.mkdir(clientbundle_bin_dir)\n\tos.mkdir(clientbundle_resource_dir)\n\tos.mkdir(clientbundle_framework_dir)\n\tos.mkdir(os.path.join(clientbundle_resource_dir, \"data\"))\n\tcopydir(\"data\", clientbundle_resource_dir)\n\tos.chdir(languages_dir)\n\tcopydir(\"data\", \"../\"+clientbundle_resource_dir)\n\tos.chdir(\"..\")\n\tshutil.copy(\"other/icons/Teeworlds.icns\", clientbundle_resource_dir)\n\tshutil.copy(name+exe_ext, clientbundle_bin_dir)\n\tos.system(\"cp -R /Library/Frameworks/SDL.framework \" + clientbundle_framework_dir)\n\tfile(os.path.join(clientbundle_content_dir, \"Info.plist\"), \"w\").write(\"\"\"\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleDevelopmentRegion</key>\n\t<string>English</string>\n\t<key>CFBundleExecutable</key>\n\t<string>teeworlds</string>\n\t<key>CFBundleIconFile</key>\n\t<string>Teeworlds</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundlePackageType</key>\n\t<string>APPL</string>\n\t<key>CFBundleSignature</key>\n\t<string>????</string>\n\t<key>CFBundleVersion</key>\n\t<string>%s</string>\n</dict>\n</plist>\n\t\"\"\" % (version))\n\tfile(os.path.join(clientbundle_content_dir, \"PkgInfo\"), \"w\").write(\"APPL????\")\n\n\t# create Teeworlds Server appfolder\n\tserverbundle_content_dir = os.path.join(package_dir, \"Teeworlds Server.app/Contents\")\n\tserverbundle_bin_dir = os.path.join(serverbundle_content_dir, \"MacOS\")\n\tserverbundle_resource_dir = os.path.join(serverbundle_content_dir, \"Resources\")\n\tos.mkdir(os.path.join(package_dir, \"Teeworlds Server.app\"))\n\tos.mkdir(serverbundle_content_dir)\n\tos.mkdir(serverbundle_bin_dir)\n\tos.mkdir(serverbundle_resource_dir)\n\tos.mkdir(os.path.join(serverbundle_resource_dir, \"data\"))\n\tos.mkdir(os.path.join(serverbundle_resource_dir, \"data/maps\"))\n\tos.mkdir(os.path.join(serverbundle_resource_dir, \"data/mapres\"))\n\tcopydir(\"data/maps\", serverbundle_resource_dir)\n\tshutil.copy(\"other/icons/Teeworlds_srv.icns\", serverbundle_resource_dir)\n\tshutil.copy(name+\"_srv\"+exe_ext, serverbundle_bin_dir)\n\tshutil.copy(\"serverlaunch\"+exe_ext, serverbundle_bin_dir + \"/\"+name+\"_server\")\n\tfile(os.path.join(serverbundle_content_dir, \"Info.plist\"), \"w\").write(\"\"\"\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleDevelopmentRegion</key>\n\t<string>English</string>\n\t<key>CFBundleExecutable</key>\n\t<string>teeworlds_server</string>\n\t<key>CFBundleIconFile</key>\n\t<string>Teeworlds_srv</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundlePackageType</key>\n\t<string>APPL</string>\n\t<key>CFBundleSignature</key>\n\t<string>????</string>\n\t<key>CFBundleVersion</key>\n\t<string>%s</string>\n</dict>\n</plist>\n\t\"\"\" % (version))\n\tfile(os.path.join(serverbundle_content_dir, \"PkgInfo\"), \"w\").write(\"APPL????\")\n\nif use_zip:\n\tprint(\"making zip archive\")\n\tzf = zipfile.ZipFile(\"%s.zip\" % package, 'w', zipfile.ZIP_DEFLATED)\n\t\n\tfor root, dirs, files in os.walk(package_dir, topdown=True):\n\t\tfor name in files:\n\t\t\tn = os.path.join(root, name)\n\t\t\tzf.write(n, n)\n\t#zf.printdir()\n\tzf.close()\n\t\nif use_gz:\n\tprint(\"making tar.gz archive\")\n\tos.system(\"tar czf %s.tar.gz %s\" % (package, package_dir))\n\nif use_dmg:\n\tprint(\"making disk image\")\n\tos.system(\"rm -f %s.dmg %s_temp.dmg\" % (package, package))\n\tos.system(\"hdiutil create -srcfolder %s -volname Teeworlds -quiet %s_temp\" % (package_dir, package))\n\tos.system(\"hdiutil convert %s_temp.dmg -format UDBZ -o %s.dmg -quiet\" % (package, package))\n\tos.system(\"rm -f %s_temp.dmg\" % package)\n\nclean()\n\t\nprint(\"done\")\n"
  },
  {
    "path": "scripts/make_src.py",
    "content": "import os, shutil, zipfile, sys\n\nif len(sys.argv) <= 1:\n\tprint \"%s VERSION [SVN TREE]\" % sys.argv[0]\n\tsys.exit(-1)\n\nversion = sys.argv[1]\nsvn_tree = \"tags/release-%s\" % version\n\nif len(sys.argv) > 2:\n\tsvn_tree = sys.argv[2]\n\n# make clean\nif 1:\n\ttry: shutil.rmtree(\"srcwork\")\n\texcept: pass\n\ttry: os.mkdir(\"srcwork\")\n\texcept: pass\n\nroot_dir = os.getcwd() + \"/srcwork\"\n\n# change dir\nos.chdir(root_dir)\n\n# fix bam\n#if 1:\n#\tos.system(\"svn export http://stalverk80.se/svn/bam bam\")\n#\tz = zipfile.ZipFile(\"../bam.zip\", \"w\")\n#\tfor root, dirs, files in os.walk(\"bam\"):\n#\t\tfor f in files:\n#\t\t\tz.write(root+\"/\"+ f)\n#\tz.close()\n\nif 1:\n\tos.system(\"svn export svn://svn.teeworlds.com/teeworlds/%s teeworlds\" % svn_tree)\n\tos.chdir(\"teeworlds\")\n\tos.system(\"python scripts/make_release.py %s src\" % version)\n\tos.chdir(root_dir)\n\tfor f in os.listdir(\"teeworlds\"):\n\t\tif \"teeworlds\" in f and \"src\" in f and (\".zip\" in f or \".tar.gz\" in f):\n\t\t\tshutil.copy(\"teeworlds/\"+f, \"../\" + f)\n"
  },
  {
    "path": "scripts/mass_server.py",
    "content": "#from random import choice\n\nimport random\nimport os\n\nmasterservers = [\"localhost 8300\"]\n\nmaps = [\n\t[\"dm1\", \"dm2\", \"dm6\"],\n\t[\"dm1\", \"dm2\", \"dm6\"],\n\t[\"ctf1\", \"ctf2\", \"ctf3\"],\n]\n\nservernames = [\n\t\"%s playhouse\",\n\t\"%s own server\",\n]\n\nnicks = []\nfor l in file(\"scripts/nicks.txt\"):\n\tnicks += l.replace(\":port80c.se.quakenet.org 353 matricks_ = #pcw :\", \"\").strip().split()\ninick = 0\n\ndef get_nick():\n\tglobal inick, nicks\n\tinick = (inick+1)%len(nicks)\n\treturn nicks[inick].replace(\"`\", \"\\`\")\n\t\nfor s in xrange(0, 350):\n\tcmd = \"./fake_server_d_d \"\n\tcmd += '-n \"%s\" ' % (random.choice(servernames) % get_nick())\n\tfor m in masterservers:\n\t\tcmd += '-m %s '%m\n\t\n\tmax = random.randint(2, 16)\n\tcmd += \"-x %d \" % max\n\t\n\tt = random.randint(0, 2)\n\t\n\tcmd += '-a \"%s\" ' % random.choice(maps[t])\n\tcmd += '-g %d ' % random.randint(0, 100)\n\tcmd += '-t %d ' % t # dm, tdm, ctf\n\tcmd += \"-f %d \" % random.randint(0, 1) # password protected\n\t\t\n\tfor p in xrange(0, random.randint(0, max)):\n\t\tcmd += '-p \"%s\" %d ' % (get_nick(), random.randint(0, 20))\n\t\n\tprint cmd\n\tos.popen2(cmd)\n\n"
  },
  {
    "path": "scripts/netobj.py",
    "content": "import sys, os\n\nline_count = 0\n\nclass variable:\n\tname = \"unknown\"\n\tdef __init__(self, args, name):\n\t\tglobal line_count\n\t\tself.name = name\n\t\tself.line = line_count\n\tdef emit_declaration(self):\n\t\treturn [\"\\tint %s;\" % self.name]\n\tdef linedef(self):\n\t\treturn \"#line %d\" % self.line\n\tdef emit_secure(self, parent):\n\t\treturn []\n\tdef emit_unpack(self):\n\t\treturn [\"msg.%s = msg_unpack_int();\" % self.name]\n\tdef emit_unpack_check(self):\n\t\treturn []\n\tdef emit_pack(self):\n\t\treturn [\"\\t\\tmsg_pack_int(%s);\" % self.name]\n\nclass var_any(variable):\n\tdef __init__(self, args, name):\n\t\tvariable.__init__(self, args, name)\n\nclass var_range(variable):\n\tdef __init__(self, args, name):\n\t\tvariable.__init__(self, args, name)\n\t\tself.min = args[0]\n\t\tself.max = args[1]\n\tdef emit_unpack_check(self):\n\t\treturn [\"if(msg.%s < %s || msg.%s > %s) { msg_failed_on = \\\"%s\\\"; return 0; }\" % (self.name, self.min, self.name, self.max, self.name)]\n\tdef emit_secure(self, parent):\n\t\treturn [self.linedef(), \"obj->%s = netobj_clamp_int(\\\"%s.%s\\\", obj->%s, %s, %s);\" % (self.name, parent.name, self.name, self.name, self.min, self.max)]\n\nclass var_string(variable):\n\tdef __init__(self, args, name):\n\t\tvariable.__init__(self, args, name)\n\nclass var_string(variable):\n\tdef __init__(self, args, name):\n\t\tvariable.__init__(self, args, name)\n\tdef emit_declaration(self):\n\t\treturn [\"\\tconst char *%s;\" % self.name]\n\tdef emit_unpack(self):\n\t\treturn [\"msg.%s = msg_unpack_string();\" % self.name]\n\tdef emit_pack(self):\n\t\treturn [\"\\t\\tmsg_pack_string(%s, -1);\" % self.name]\n\nclass object:\n\tdef __init__(self, line):\n\t\tfields = line.split()\n\t\tself.name = fields[1]\n\t\tself.extends = None\n\t\tif len(fields) == 4 and fields[2] == \"extends\":\n\t\t\tself.extends = fields[3]\n\t\tself.enum_name = \"NETOBJTYPE_%s\" % self.name.upper()\n\t\tself.struct_name = \"NETOBJ_%s\" % self.name.upper()\n\t\tself.members = []\n\t\t\n\tdef parse(self, lines):\n\t\tglobal line_count\n\t\tfor index in xrange(0, len(lines)):\n\t\t\tline_count += 1\n\t\t\tline = lines[index]\n\t\t\tif not len(line):\n\t\t\t\tcontinue\n\t\t\t\t\n\t\t\tif line == \"end\":\n\t\t\t\treturn lines[index+1:]\n\t\t\telse:\n\t\t\t\t# check for argument\n\t\t\t\tfields = line.split(\")\", 1)\n\t\t\t\tif len(fields) == 2:\n\t\t\t\t\tnames = [line.strip() for line in fields[1].split(\",\")]\n\t\t\t\t\tl = fields[0].split(\"(\", 1)\n\t\t\t\t\ttype = l[0]\n\t\t\t\t\targs = [line.strip() for line in l[1].split(\",\")]\n\t\t\t\telse:\n\t\t\t\t\tl = fields[0].split(None, 1)\n\t\t\t\t\ttype = l[0]\n\t\t\t\t\targs = []\n\t\t\t\t\tnames = [line.strip() for line in l[1].split(\",\")]\n\t\t\t\t\t\n\t\t\t\tfor name in names:\n\t\t\t\t\tcreate_string = 'var_%s(%s, \"%s\")' % (type, args, name)\n\t\t\t\t\tnew_member = eval(create_string)\n\t\t\t\t\tself.members += [new_member]\n\t\t\t\t\n\t\traise BaseException(\"Parse error\")\n\t\n\tdef emit_declaration(self):\n\t\tlines = []\n\t\tif self.extends:\n\t\t\tlines += [\"struct %s : public NETOBJ_%s\\n {\" % (self.struct_name, self.extends.upper())]\n\t\telse:\n\t\t\tlines += [\"struct %s\\n {\" % self.struct_name]\n\t\tfor m in self.members:\n\t\t\tlines += m.emit_declaration()\n\t\tlines += [\"};\"]\n\t\treturn lines\n\n\tdef emit_secure(self):\n\t\tlines = []\n\t\tfor m in self.members:\n\t\t\tlines += m.emit_secure(self)\n\t\treturn lines\n\nclass message:\n\tdef __init__(self, line):\n\t\tfields = line.split()\n\t\tself.name = fields[1]\n\t\tself.enum_name = \"NETMSGTYPE_%s\" % self.name.upper()\n\t\tself.struct_name = \"NETMSG_%s\" % self.name.upper()\n\t\tself.members = []\n\t\t\n\tdef parse(self, lines):\n\t\tglobal line_count\n\t\tfor index in xrange(0, len(lines)):\n\t\t\tline_count += 1\n\t\t\tline = lines[index]\n\t\t\tif not len(line):\n\t\t\t\tcontinue\n\t\t\t\t\n\t\t\tif line == \"end\":\n\t\t\t\treturn lines[index+1:]\n\t\t\telse:\n\t\t\t\t# check for argument\n\t\t\t\tfields = line.split(\")\", 1)\n\t\t\t\tif len(fields) == 2:\n\t\t\t\t\tnames = [line.strip() for line in fields[1].split(\",\")]\n\t\t\t\t\tl = fields[0].split(\"(\", 1)\n\t\t\t\t\ttype = l[0]\n\t\t\t\t\targs = [line.strip() for line in l[1].split(\",\")]\n\t\t\t\telse:\n\t\t\t\t\tl = fields[0].split(None, 1)\n\t\t\t\t\ttype = l[0]\n\t\t\t\t\targs = []\n\t\t\t\t\tnames = [line.strip() for line in l[1].split(\",\")]\n\t\t\t\t\t\n\t\t\t\tfor name in names:\n\t\t\t\t\tcreate_string = 'var_%s(%s, \"%s\")' % (type, args, name)\n\t\t\t\t\tnew_member = eval(create_string)\n\t\t\t\t\tself.members += [new_member]\n\t\t\t\t\n\t\traise BaseException(\"Parse error\")\n\t\n\tdef emit_declaration(self):\n\t\tlines = []\n\t\tlines += [\"struct %s\\n {\" % self.struct_name]\n\t\tfor m in self.members:\n\t\t\tlines += m.emit_declaration()\n\t\tlines += [\"\\tvoid pack(int flags)\"]\n\t\tlines += [\"\\t{\"]\n\t\tlines += [\"\\t\\tmsg_pack_start(%s, flags);\" % self.enum_name]\n\t\tfor m in self.members:\n\t\t\tlines += m.emit_pack()\n\t\tlines += [\"\\t\\tmsg_pack_end();\"]\n\t\tlines += [\"\\t}\"]\n\t\tlines += [\"};\"]\n\t\treturn lines\n\n\tdef emit_unpack(self):\n\t\tlines = []\n\t\tfor m in self.members:\n\t\t\tlines += m.emit_unpack()\n\t\tfor m in self.members:\n\t\t\tlines += m.emit_unpack_check()\n\t\treturn lines\n\n\tdef emit_pack(self):\n\t\tlines = []\n\t\tfor m in self.members:\n\t\t\tlines += m.emit_pack()\n\t\treturn lines\n\t\t\n\nclass event(object):\n\tdef __init__(self, line):\n\t\tobject.__init__(self, line)\n\t\tself.enum_name = \"NETEVENTTYPE_%s\" % self.name.upper()\n\t\tself.struct_name = \"NETEVENT_%s\" % self.name.upper()\n\nclass raw_reader:\n\tdef __init__(self):\n\t\tself.raw_lines = []\n\tdef parse(self, lines):\n\t\tglobal line_count\n\t\tfor index in xrange(0, len(lines)):\n\t\t\tline_count += 1\n\t\t\tline = lines[index]\n\t\t\tif not len(line):\n\t\t\t\tcontinue\n\t\t\t\t\n\t\t\tif line == \"end\":\n\t\t\t\treturn lines[index+1:]\n\t\t\telse:\n\t\t\t\tself.raw_lines += [line]\n\t\t\t\t\n\t\traise BaseException(\"Parse error\")\t\t\n\nclass proto:\n\tdef __init__(self):\n\t\tself.objects = []\n\t\tself.messages = []\n\t\tself.source_raw = []\n\t\tself.header_raw = []\n\ndef load(filename):\n\t# read the file\n\tglobal line_count\n\tline_count = 0\n\tlines = [line.split(\"//\", 2)[0].strip() for line in file(filename).readlines()]\n\t\n\tp = proto()\n\n\twhile len(lines):\n\t\tline_count += 1\n\t\tline = lines[0]\n\t\t\n\t\tif not len(line):\n\t\t\tdel lines[0]\n\t\t\tcontinue\n\t\t\t\n\t\tfields = line.split(None, 1)\n\t\t\n\t\tdel lines[0]\n\t\t\n\t\tif fields[0] == \"object\":\n\t\t\tnew_obj = object(line)\n\t\t\tlines = new_obj.parse(lines)\n\t\t\tp.objects += [new_obj]\n\t\telif fields[0] == \"message\":\n\t\t\tnew_msg = message(line)\n\t\t\tlines = new_msg.parse(lines)\n\t\t\tp.messages += [new_msg]\n\t\telif fields[0] == \"event\":\n\t\t\tnew_obj = event(line)\n\t\t\tlines = new_obj.parse(lines)\n\t\t\tp.objects += [new_obj]\n\t\telif fields[0] == \"raw_source\":\n\t\t\traw = raw_reader()\n\t\t\tlines = raw.parse(lines)\n\t\t\tp.source_raw += raw.raw_lines\n\t\telif fields[0] == \"raw_header\":\n\t\t\traw = raw_reader()\n\t\t\tlines = raw.parse(lines)\n\t\t\tp.header_raw += raw.raw_lines\n\t\telse:\n\t\t\tprint \"error, strange line:\", line\n\t\t\t\n\treturn p\n\t\ndef emit_header_file(f, p):\n\tfor l in p.header_raw:\n\t\tprint >>f, l\n\t\t\n\tif 1: # emit the enum table for objects\n\t\tprint >>f, \"enum {\"\n\t\tprint >>f, \"\\tNETOBJTYPE_INVALID=0,\"\n\t\tfor obj in p.objects:\n\t\t\tprint >>f, \"\\t%s,\" % obj.enum_name\n\t\tprint >>f, \"\\tNUM_NETOBJTYPES\"\n\t\tprint >>f, \"};\"\n\t\tprint >>f, \"\"\n\n\tif 1: # emit the enum table for messages\n\t\tprint >>f, \"enum {\"\n\t\tprint >>f, \"\\tNETMSGTYPE_INVALID=0,\"\n\t\tfor msg in p.messages:\n\t\t\tprint >>f, \"\\t%s,\" % msg.enum_name\n\t\tprint >>f, \"\\tNUM_NETMSGTYPES\"\n\t\tprint >>f, \"};\"\n\t\tprint >>f, \"\"\n\n\tprint >>f, \"int netobj_secure(int type, void *data, int size);\"\n\tprint >>f, \"const char *netobj_get_name(int type);\"\n\tprint >>f, \"int netobj_num_corrections();\"\n\tprint >>f, \"const char *netobj_corrected_on();\"\n\tprint >>f, \"\"\n\tprint >>f, \"void *netmsg_secure_unpack(int type);\"\n\tprint >>f, \"const char *netmsg_get_name(int type);\"\n\tprint >>f, \"const char *netmsg_failed_on();\"\n\tprint >>f, \"\"\n\n\tfor obj in p.objects:\n\t\tfor l in obj.emit_declaration():\n\t\t\tprint >>f, l\n\t\tprint >>f, \"\"\n\n\tfor msg in p.messages:\n\t\tfor l in msg.emit_declaration():\n\t\t\tprint >>f, l\n\t\tprint >>f, \"\"\n\t\t\t\ndef emit_source_file(f, p, protofilename):\n\tprint >>f, \"#line 1 \\\"%s\\\"\" % os.path.abspath(protofilename).replace(\"\\\\\", \"\\\\\\\\\")\n\t\n\tfor l in p.source_raw:\n\t\tprint >>f, l\n\n\tprint >>f, \"const char *msg_failed_on = \\\"\\\";\"\n\tprint >>f, \"const char *obj_corrected_on = \\\"\\\";\"\n\tprint >>f, \"static int num_corrections = 0;\"\n\tprint >>f, \"int netobj_num_corrections() { return num_corrections; }\"\n\tprint >>f, \"const char *netobj_corrected_on() { return obj_corrected_on; }\"\n\tprint >>f, \"const char *netmsg_failed_on() { return msg_failed_on; }\"\n\tprint >>f, \"\"\n\tprint >>f, \"static int netobj_clamp_int(const char *error_msg, int v, int min, int max)\"\n\tprint >>f, \"{\"\n\tprint >>f, \"\\tif(v<min) { obj_corrected_on = error_msg; num_corrections++; return min; }\"\n\tprint >>f, \"\\tif(v>max) { obj_corrected_on = error_msg; num_corrections++; return max; }\"\n\tprint >>f, \"\\treturn v;\"\n\tprint >>f, \"}\"\n\tprint >>f, \"\"\n\t\n\tif 1: # names\n\t\tprint >>f, \"static const char *object_names[] = {\"\n\t\tprint >>f, \"\\t\" + '\"invalid\",'\n\t\tfor obj in p.objects:\n\t\t\tprint >>f, '\\t\"%s\",' % obj.name\n\t\tprint >>f, '\\t\"\"'\n\t\tprint >>f, \"};\"\n\t\tprint >>f, \"\"\n\t\t\n\tif 1: # secure functions\n\t\tprint >>f, \"static int secure_object_invalid(void *data, int size) { return 0; }\"\n\t\tfor obj in p.objects:\n\t\t\tprint >>f, \"static int secure_%s(void *data, int size)\" % obj.name\n\t\t\tprint >>f, \"{\"\n\t\t\tprint >>f, \"\\t%s *obj = (%s *)data;\" % (obj.struct_name, obj.struct_name)\n\t\t\tprint >>f, \"\\t(void)obj;\" # to get rid of \"unused variable\" warning\n\t\t\tprint >>f, \"\\tif(size != sizeof(%s)) return -1;\" % obj.struct_name\n\t\t\tif obj.extends:\n\t\t\t\tprint >>f, \"\\tif(secure_%s(data, sizeof(NETOBJ_%s)) != 0) return -1;\" % (obj.extends, obj.extends.upper())\n\t\t\t\t\n\t\t\tfor l in obj.emit_secure():\n\t\t\t\tprint >>f, \"\\t\" + l\n\t\t\tprint >>f, \"\\treturn 0;\";\n\t\t\tprint >>f, \"}\"\n\t\t\tprint >>f, \"\"\n\n\tif 1: # secure function table\n\t\tprint >>f, \"typedef int(*SECUREFUNC)(void *data, int size);\"\n\t\tprint >>f, \"static SECUREFUNC secure_funcs[] = {\"\n\t\tprint >>f, \"\\t\" + 'secure_object_invalid,'\n\t\tfor obj in p.objects:\n\t\t\tprint >>f, \"\\tsecure_%s,\" % obj.name\n\t\tprint >>f, \"\\t\" + '0x0'\n\t\tprint >>f, \"};\"\n\t\tprint >>f, \"\"\n\n\tif 1:\n\t\tprint >>f, \"int netobj_secure(int type, void *data, int size)\"\n\t\tprint >>f, \"{\"\n\t\tprint >>f, \"\\tif(type < 0 || type >= NUM_NETOBJTYPES) return -1;\"\n\t\tprint >>f, \"\\treturn secure_funcs[type](data, size);\"\n\t\tprint >>f, \"};\"\n\t\tprint >>f, \"\"\n\n\tif 1:\n\t\tprint >>f, \"const char *netobj_get_name(int type)\"\n\t\tprint >>f, \"{\"\n\t\tprint >>f, \"\\tif(type < 0 || type >= NUM_NETOBJTYPES) return \\\"(invalid)\\\";\"\n\t\tprint >>f, \"\\treturn object_names[type];\"\n\t\tprint >>f, \"};\"\n\t\tprint >>f, \"\"\n\t\t\n\tif 1: # names\n\t\tprint >>f, \"static const char *message_names[] = {\"\n\t\tprint >>f, \"\\t\" + '\"invalid\",'\n\t\tfor msg in p.messages:\n\t\t\tprint >>f, '\\t\"%s\",' % msg.name\n\t\tprint >>f, '\\t\"\"'\n\t\tprint >>f, \"};\"\n\t\tprint >>f, \"\"\t\t\n\n\tif 1: # secure functions\n\t\tprint >>f, \"static void *secure_unpack_invalid() { return 0; }\"\n\t\tfor msg in p.messages:\n\t\t\tprint >>f, \"static void *secure_unpack_%s()\" % msg.name\n\t\t\tprint >>f, \"{\"\n\t\t\tprint >>f, \"\\tstatic %s msg;\" % msg.struct_name\n\t\t\tfor l in msg.emit_unpack():\n\t\t\t\tprint >>f, \"\\t\" + l\n\t\t\tprint >>f, \"\\treturn &msg;\";\n\t\t\tprint >>f, \"}\"\n\t\t\tprint >>f, \"\"\t\t\n\n\tif 1: # secure function table\n\t\tprint >>f, \"typedef void *(*SECUREUNPACKFUNC)();\"\n\t\tprint >>f, \"static SECUREUNPACKFUNC secure_unpack_funcs[] = {\"\n\t\tprint >>f, \"\\t\" + 'secure_unpack_invalid,'\n\t\tfor msg in p.messages:\n\t\t\tprint >>f, \"\\tsecure_unpack_%s,\" % msg.name\n\t\tprint >>f, \"\\t\" + '0x0'\n\t\tprint >>f, \"};\"\n\t\tprint >>f, \"\"\n\t\t\n\tif 1:\n\t\tprint >>f, \"void *netmsg_secure_unpack(int type)\"\n\t\tprint >>f, \"{\"\n\t\tprint >>f, \"\\tvoid *msg;\"\n\t\tprint >>f, \"\\tmsg_failed_on = \\\"\\\";\"\n\t\tprint >>f, \"\\tif(type < 0 || type >= NUM_NETMSGTYPES) return 0;\"\n\t\tprint >>f, \"\\tmsg = secure_unpack_funcs[type]();\"\n\t\tprint >>f, \"\\tif(msg_unpack_error()) return 0;\"\n\t\tprint >>f, \"\\treturn msg;\"\n\t\tprint >>f, \"};\"\n\t\tprint >>f, \"\"\n\n\tif 1:\n\t\tprint >>f, \"const char *netmsg_get_name(int type)\"\n\t\tprint >>f, \"{\"\n\t\tprint >>f, \"\\tif(type < 0 || type >= NUM_NETMSGTYPES) return \\\"(invalid)\\\";\"\n\t\tprint >>f, \"\\treturn message_names[type];\"\n\t\tprint >>f, \"};\"\n\t\tprint >>f, \"\"\t\t\n\t\t\nif sys.argv[1] == \"header\":\n\tp = load(sys.argv[2])\n\temit_header_file(file(sys.argv[3], \"w\"), p)\nelif sys.argv[1] == \"source\":\n\tp = load(sys.argv[2])\n\temit_source_file(file(sys.argv[3], \"w\"), p, sys.argv[2])\nelse:\n\tprint \"invalid command\"\n\tsys.exit(-1)\n"
  },
  {
    "path": "scripts/nicks.txt",
    "content": ":port80c.se.quakenet.org 353 matricks_ = #pcw :SPQR|Snapshot em0k1d n1sse iTouch|HedaN Hyeen Mattzki i9`Nilzon matricks_ WCG|Johan format` |ceMan PREGE lololollalalal kishe|Pookie polisen Rambo-ohsite firre15 ais-nax Obbmaster diskoturk SR|KinG gone-andytheman [FG]AkO cfg-gunnar proshit|Benis raaEW bengan-- Loser^ zNEKS Fokka Ping28|kwnztahh Palo^ partyZAH NillePillopio discover J-N ios Cajanen Bsite`oZe haxxcoto Hell[v]SOVA rabies Lampard2k7 DeFuN Linkan bjorniss Soet-DgR-_-[A] BridgeMill|Mod1\n:port80c.se.quakenet.org 353 matricks_ = #pcw :Mutt Hofvits [G][L][H][f] dahlgren Zervantes ben_dover fanfanfanfan ibersklan-ruyrl Grismusen Ploxzish Ejwin^mp Poontuus sintr0z hbfs___dSq Bombastic sasdd ErNoI TaizK UnLess Astan SwS-Garcia WyH|spliffstar lololololol Simixiz SD|barkeN MOOE keekz Centern Xzide^^ N43-HYPER LeaW`3D hotnils Lectra`MAEKTIG fnytt frtyschoooooooo insanity|DavidO dr-tom MIM wayu n9ef dinmammaamamam eppel Fess1g wardh hzapRingMeisteR kidneb xplayn Lajgarn flaxe HEJJADANNE\n:port80c.se.quakenet.org 353 matricks_ = #pcw :Big^F Bsite`layd hejehjhk hsd1rrruffe AroooooN lexx_ lucchi AriGold DeDDu maflip eMO-aboOoOo Ramos6 ruub bjuse Chawn r3t _ogg kAerhu AIE|malle KimIO-SWE LooOOLiiiZ333eN kullersten Poke_- DryNox KoSmurfen ExakTT Gs|T1AO vtine|MAAAUNS heroX Twind [wc3]-Chiwi[CL] chilirec|raimat SeeWaR erdussel TROPP- exay franky540 ActionBarbie mHz\\ZTK`sleep RRP^Jaffa cookiemonstAH WarL|thiDe Oskar^ qK-iMaz Nacka VILLIG-Booyah Beltdjur SoX-cOUPE kund|playz BCS|Winter\n:port80c.se.quakenet.org 353 matricks_ = #pcw :Pajsarn svamp tfs\\a TruqN babben hr-gil mapD|endoZz gnomie bostrom kA-WANGA kNNas Abxtract|pilshe vogga koolaid-krille DeVixx jwn rdl-- Kee FjuNe koolaid-iskn Pr0`Z10d3y snowsky vibes Nikjou vtine|zlivero OmGaAA mAJ|Britt hekla [0]apa kEy [F]Kaela bananskalFTW|da jeb` vampyren H0JT4R0LJ4 SheVa^ mAxXI Lectro FtN bajajajajajajja mZ`WIGGE dAMI^ moll3 GitfaN boisan [cs]-sNT Ex`Novag[jb] PPB|everest[wa] xiver- KulaN N43-xhady pluffenFOSHO wilho\n:port80c.se.quakenet.org 353 matricks_ = #pcw :Nilsson^Arvika nRe`SmitH Ice`Lie[jb] sukki elgenkek drt0FF TaZ- Caesarion Limonaatipoika robf[S] DNAtive broder lolipop jollsy Genander Ballo_Ong Musikant|musicu ToY|Machine nerf|dupl0x gopy` fn\\EXESSION FreZZ joharn _Folz [D]KvasteN daeeawewasdfadf CamelRyttArn Xabian HinzeL qRoN _dARUUF CUC|MiniMe^Away hewnk ASTRA|ove xideR Krigarn^ nIw|PlixxaN nMe|| Plumpen S0DA|BorrE teddis daboomb Bongo` Unknownperson TTA`BAdh SefuTzu`AWAY QRLGRIM neraz\n:port80c.se.quakenet.org 353 matricks_ = #pcw :Xipho|Fudge Guggztah etojk Lindgrene [V]ZAIKON BmF^Off Wf`jeager\\aw Havsmanet-ehn krisa hojhoj alfonz RoBBY faB|mHk Cheeser Admin1337 DoFFrR Caution- mZ`NoKaas HR|bramhultz`` mxyzptlk luder^myfish i`pikoL ZhenjkEe^^-777 Mansvalp sajje1996 v4de Redical`quexOFF n^sdadasJo eXITD`aw teknikvm-jaoel FLIPP-Shapen ALEJKO cliz^ acequeen Ferato Shudde sinsKal`ply frittlol Deadlier Farbrorspurk FizaH` \\Azash sWingY fb\\ekN xtreck addeadam KneKk azkiN rinxzor\n:port80c.se.quakenet.org 353 matricks_ = #pcw :ArneH asdn brunte GeN|HollywoodHu bL\\ZuND UNNEBERZ Synthetic|Xorci portoni saxparty|imso Inti |RnE oFFily Sp|DiamaNt Rhombus Nebrek kelamies Thingg BFB|incedeNt TAZzen whinan J0nte p12|wiggie okaJ mZ`Raztad FABF R3|sNELL blaupunkt2 Norrland-WaHoO maccan Ben---- aimD aLTOR EVIG|Falken nilsso bamstAr aGona`scalper reign[m4]n inzejN|ZoneX imag1ne a^meda|EYIE conejito puhaaa clime dsp123 mario_o bRRRA litextra|wezy TG|SaTaN Mando Weiche- wezzan\n:port80c.se.quakenet.org 353 matricks_ = #pcw :Labe mp`serve soulK [V]Gudiikzt4r XampeD fs\\dcube TrolleRovarN Emptyy SG-daskep0t Byssan Bernts1 SG|YAhoo KOKKA rL`SnowZen^ hIGHTECH__ aPPeLk4k4n otto^_ backs`wouL DeaGJIa mONGOLOJD|kree xekafutuwu uris vagrant ^a^cklet neaK-spiN nozter Arve S0oker GotticH pr0n^ traff`mElissA BC|Kebab2000 CipRi andor-- barbara- traff`lizze harserver3on3 RalleTruss EAES EKEMAN Cowafuckingdogk superlime LokY Hockey-Syvve Gigi qk-WyverN Larsito spendex eiviN und`feelme\n:port80c.se.quakenet.org 353 matricks_ = #pcw :aderblasu yHYSS Cmore WaskE lodiz NachiMux Bodde kiiM Claddy TTAgital soker2on2plz mixzxz TmY- KrabbateN HAKKAKDGK VarsKo^aW Fuzak GZ`Kirra^^ mhaji Full|Hytra saxy0z0z0z Akapulka|urban CaZzpeR DarkLink FALLE- AmoZ mADSEN inetpro asd1 [100fps]elgit0 loltih GOLIATH`JONKAN sn1tch_4qs ischi87 Wazee LLLgHOST Derotti flw mandis daskdkad BlixteN_OFF Mjada-Hickdead Eazy-game|pAjk DulleN Sp3karn aimstar^mWd voffsi asdas Keo-muAz Liviu^^ vLaNskyldig\n:port80c.se.quakenet.org 353 matricks_ = #pcw :sdfgdfg [4]bappo polackn [42]xeelol basseeee LuppaN eSport|RoxoR Heat2 Helgon`KEXITAN vaxxus|kY kaarel_ i-Link`Slobbo DazOFF Lectra`VolveR [51N19E]Mdr NFTS_aptand pd\\cilleh wirram Ag- kn1^ROSA Nixt0n @Josi berrtill mikl ut|brbr LoLiz3N Ishootudie HaGa1 Tetrispro|Veloc Stilig firin Local`Bhz goodR N-Bot GangstA^Niise CLOCKK MaGeN churru` tB-SidW playm8|DjwaNdz PenisPasta sbd-phuntanN Sh4cky vED kimpann mylvis ville_12345678 MeLL^-Q sio\\chaez\n:port80c.se.quakenet.org 353 matricks_ = #pcw :PLAYER|ZOMG KappeZ^ pennpenn FatzoooO Snark^ Laakko FreddaN zure fiSKen vaccA[cx] Beart FD|Phoenix latrviabaatvik saffu tveka`StiKo HubbaBubbaBoyz q5^n3imad RETARDED pLym|Muffe GYG|RagnarssoN rF|neddemIRC HydrOO ollee sliff Eaten_Alive bollih\\away fisarn Fanboyz\\qcube Oish Da5|Poppo brottare mHz\\xAantic [blueprint|Sn] SneZ WarQ|TriZ^ webcore|R3D95 rubeiiin`1st elius j0mppe- Zwoltex hebbe lallala vAH_ cp^traxzzlol Kung-Fonz Sprattelvatten inzejn[M]\n:port80c.se.quakenet.org 353 matricks_ = #pcw :IR|psN backs`Fester Linus CreEckDeztrox _hillztaah IrLo bissen jonjonjon giant^da princip-xtinct smaakskcake [P]use ZerOSh00TS WarQ|Mathilda [P]nikkz sEasiun N43-PuNKy PuttEE Sp|SaLo^| zErios Klerburgare Silikon|Laxen e`zejN hejkanin Zien volvers promizer yewlar HeJ_hEj`aw jeakk rilleh x1ofdewm Swift^ Infinit3 RattiSorsa Ludvika|keken `m1r0n robbagg PillaD-Goss3N Apa`MAx |1g|LegoBilen Ainish [EN]Xanti aviad- puFFFin hejbabuirabakal Hodja WildHead\n:port80c.se.quakenet.org 353 matricks_ = #pcw :Lo2P VadeHs|FortFarN Bollhuvve ebayer BEckzOFF Gonzo9014 DarkmindTheGrea trwon nena_ skillbill TpN-Rille^OFF Apl- zune[N] matsinyyyy spyyr stkiih MOSSEN Mathiaz dot222222222 MUFFINN DIMMamxxx xtinct BANZAI|Unders siCKO^^ ALEXMAN GM95 PinkDeagle Chlebo WiNk0 NITR0 Mykos Immortal-King Brodda inzejN|TiGeR Jaaanpoo GZ`SneLF |Ahoehoe R4mzi sadasda FoSho zOOM^ HEHEO2 princip-HermiN^ SUPERFASTTEC yohanseN n23|folieN-_- muffins crakkiz tmd-vdF Ello^\n:port80c.se.quakenet.org 353 matricks_ = #pcw :WOTS|christian |F|6|F|Volle Sp4rv3N Nibbler|LAN BVG|Anonim HENNING Local`sNl ifektO whipee\\ vaxxus|gtv cL\\\\ninjaaraben r4jz_- vaxxus|nIc vaxxus|aVd Beastie^ Meier bjarne-_-12 Kalhygge|aBc inspet nuLLifY zlF BLAN|sUPERJAK biggy flon-sebbe fjurtis-otrolig Kalhygge|naXo Playgr0und Bamsar^Bwhl Kalhygge|meXA Kindow sylta pZi paraL^Deja BlasTmaN-tB deeh` [5b]CW|maxii AceDude_- LG^Panik GoA-Het^y|OFF sTr1nG^AFK zxn^off denbette^BNC ZoniX^Off LG^bruzken\n:port80c.se.quakenet.org 353 matricks_ = #pcw :Zip^BNC ANONZOFF c`FoOjegerOff Ordspil^afk zanoJ-off bakhoj^off VeLuX^BNC p-zkarp Error404 Nivius^^ DP^OFF|SILENTY VICKY SkytteNOFF nAz JC|RedeTeZ^BNC hooligan`away Splutt|BNC svennjeavlnOFF aNTWAn CB|knubbiz-`AWA bliztr NB|freq[N] kOllEH deML|StoLeN\\OFF DOED|EnRIz erN^BNC^AW jompa Cha0tix^OFF Pinstrup-off wolves-munkaway skoogan airhead^OFF Jeffie D5|Lindahl^OFF onaqui skinK aNders|BNC KadaveR^ valtsu_ sledz[aw] Cryptztahh`off FleexOFF stycket\n:port80c.se.quakenet.org 353 matricks_ = #pcw :xGx_kmn^off WC anto_o GAndroo^aw schmaCk|icko lyngordon wUULF tX|Dzenan dERG0 chansurf HW|eriksson SG|Hornet xTz`ReXor^off_ syn4psE catsie skize Hezxy tomater HildaOFF nEXIN-tirre [NeutroN] ^sne WoA|dfish xTz`xNitroX^off exero koiz drastic`aVoid Checky_OFF Graxor LinusOFF_ nesc|Meibi` crezz eLiaZ unrea CharlieE eco`nejked tompA^ exp3rt Moejoe FloraCs|Aora Kalhygge|z1 iksO fake[n]ick FloraCsAora inzejN|Jonse ZoRoXo FD|tVEKA XMG\\Gngs brrave^Borta\n:port80c.se.quakenet.org 353 matricks_ = #pcw :aLpi-AtroOFF mustafakrister PEWPEW MiRRE`OFFLiNE Mixxarna-WejK^ gP|Deex cAD-BNC1 tomh BnCinzejn henka snacjsar EnE|vilsN TixoNBnc shifty|ossi WSOP|fredada MortenSoccer kiimpan [E]Polle^ doke muuuie Androoz SIXO wtai|tryckveard [sc]-falle Tele\\weRRe`OFF Martin_- annette-away iGwtRealT3cH gUsk smekarn Onttu xVera`kreeeeee Somppiaeae LasseMan [SS]BoZo inzejn[A] HR|WINESY ^^juh0^^ BYS`vojnik nejmzah Sh1ft-_- Thunder-str R22du sankan DDark MtM PlayN-ziNk^Aw\n:port80c.se.quakenet.org 353 matricks_ = #pcw :pd|firren GROSSER LIMEDNULKE HellkaN Mattan tzeron`g0ne Mr-Zorky HoD-Espen BAdhBNC ahlt ramoneur roxon_ dOFF`bth WcG|memphis Jules_ Hye Toot Justicia hajpad-Ante Fia`T8im e5g-Re\\FILM hjort iNet\\fjollabero Jeespoks SH|Thonk ztar`oFF Widow[away] mj\\away CheatoN^BNC LAPPHOREoff dO`esn paal`aw Prayon emFFF zeLo FluBBa dalleBNC aTer waah|off kdo^ C_OFFE Dynis|AWAY miniwolbc BpN^away ReF^Zzz kyAx-OFF therazorsedge vT-viggolito CaLm[mC] Fredde^ acuBNC\n:port80c.se.quakenet.org 353 matricks_ = #pcw :Xipho|HollyWood _ArvedssoN^BNC Rayan Mastodonten kempa Blizo`bnc SnIpa Suspected`Bnc1 Neftus dO`RadeoN Madicken daniel123 D-Line|m00jsi osbnc2 AWskian quality`BNC2 inzite`chad CHiLLiPiLl^bnc swaftan QlintoN iTouch|LundiN vandalizm Qslig[FM] makke Tele\\wHomp^bnc steamacc4sale Playbackvxo asiQ^BNC Cash-Flow deniiX ITFYTD olssonn nehyd [421]Bihaz- CrilleeOFF elicious`wE111A sndOFF`Ass_slac kusn Myscobnc shade`nu [1Ramlosa] j1m1bnc TPI-piggerN\n:port80c.se.quakenet.org 353 matricks_ = #pcw :gedis`AFK mX|Ximer3`BNC Rofel Std samhOFF tG`JeBuu roxz peace`zwa _jacce dRELL tetta bubbenBNC`[GA] __viktor ture frell newbcake k00HOOHO-- makkan Bihaz_- joacim _simon sajje1995 emf|zupppiyoyoy elixyr forfam|bOFF elitasson _sockan Gulle der-Andy RexorN NER|M0wz`aw n0pL_OFF AdamBNC kRIIL falCoOFF ajz antein splexan DNX Team-Unic_bnc2 Team-Unic_bnc1 Team-dH^Jacki3 |F|6|F|Penelo SCUMMY-OFF goL|GustiS^away koppar MartinsBNC xANIZ\\bnc chilLboY\n:port80c.se.quakenet.org 353 matricks_ = #pcw :Erik2son powerbnc2 Nizer Qeamer tobiasmatss swsBNC `Tobb Pyret Gv\\MortiOFF aTschi xamber123 _borre boeka`kankeOFF reaction-bnc1 wiggan Zenhto TUX|ximmy hariiss HS|JagaleX^Offl ohm-bnc4 Iam hawkztr wibbaan Stamina\\Proteus rME st4rl\\heawen cursed-^^ _LarssoN_ Empis KnaspeR freez Deja-OFF QseBNC ninjaFREDDE ReTrez^Bnc^Away Divid0 mosklubba XnoW MozzyOFF mZ`Freddy Kladden^bnc alkh`aw Prood nIIICKOOOOO CR^SquierBNC H9jE^ b`hoffenOFF grikko sevonOFF\n:port80c.se.quakenet.org 353 matricks_ = #pcw :Vexey avdunkad Rizley razzz BJARTMAR PlayHardGoFat Bubstah Gaffel [imbaOFF]sajkez mooaern emric Znap Hyso[csP] Kvasten^-off @Fabi Ind`laaKen amsrOFF Stamina\\Achtung aceit\\MorianA- c^KNDOO DAJMEN`AW runpuff Drunke fisken10 Let_It_Whip Poxi boeka`zeppOFF bodil avlid^bnc markisen`bnc qurry oBiee PZ|FiC-Aw Jonirl_gone luttman _micro Cr33d^Away Anderss^OFF rasmus11 axl0n17 pAjk Vibban\\OFF zAt-off `tyrantBNC HB`off|djnatnat mP`off|Redfir3 TS|kolben_afk\n:port80c.se.quakenet.org 353 matricks_ = #pcw :Manual\\AFK mP`off|Redbot RetardacE ewh`FL1NK\\away TaeferN`aw Divan^KaLa^BNC Divan^myRan^BNC DUMBASS`BNC sudden21 Cyber`Mnisaway [BFF]-REeLexX AEEEEEEEEEEEEEE ZMLB-Odis deaf-cs|Lille Ninjan` bojer^off freaKKKy_BNC Replay` GuFFe D3nim smn-_- jerry[bnc] D`timex a5\\eqiNawaY inviz maRkN_ Brodda^SKOLAN zG|CBB^Off TisPik_off AFK^[TC]pvp chiva0FF hughi-off amokz^BNC SteelpliX^BNC Bioonic nIELSENoFF OFF|fZoe OliverL2`AWAY babb Chuck_N SNOEN^OFF [CYBER]niijaz\n:port80c.se.quakenet.org 353 matricks_ = #pcw :LilleGris^BnC zG|Flod__ \\lEGO`OFF LinusOFF SaX`Gubbi`OFF kolmio m|Smith Mitt3 iluen haMp gDesigns Reb_6ff blank|tox^off Unf[BNC]JLS SYNTEK|bArk FJERLEND PerSpelmann toXq` ieS|make`away pwang12 wajk\\aw InV^Raccoon-OFF ComsyS ElakSomFan^^ @m3z @pimpo @MYM|Muesli`off ADAMeh^zzzz DLM^b1ue^Off Hootarn croz kylan_off ing\\\\tsabNC Offson n1mez`off spanier^off dieNasty`brb [D]Bamb DKB|Night[oFF] Basket-off xS|HeliuM Hardcorehilda attixoff thorr_ minib\n:port80c.se.quakenet.org 353 matricks_ = #pcw :rwn ironic|Haunted khalannz PCW-Poker spitz Hiippari- iMrClean C5|Jakobervaek Casa`berssaBNC gamer`away myNKOFF Tjalfeen^off_ ^cooling noisi-a-way JennaDD mySKi-[a]ngeh mav0FF sanoj\\ dicti KLADDIS`AWAY OFF|ShAmOnE dollface WoC^RuFi selo|elloAFK LnC-Kezse kn1^Mole__ haVec- BorgareN^ steddan Verga PawP SAAAID onemind`xent dyfu`viciouz Ice`OFF_ kEbAbMaNnEn gamax|luN_ guragoa`off xorTon Kirka bruikki SkarvaNOFF empton nessaia|noHn-OF iNet\\xerp\n:port80c.se.quakenet.org 353 matricks_ = #pcw :]5[kbz tjaeder sulaN^OFFLAJN Relayish mr-o oxido drulen CR1M3Z^off_ ziNx` Local`MickeMann deaf-cs|Brajen cL\\\\ninjaBNC tomh^soet eriik^ Carn4tioN`away Rapt0r KAAAALLLEE`BNC raY^^ aNnaa` ^apan LpY|p0sh[kol] dempAWAY zuxen\\OFF aztro ToggeN [A1]No_52 [A1]etuxia Jusa Playm|DjToppi- Bodoom BCS^OFF|mkiss skau ThumbSucker^BNC tOFF-FuSe fnpOFF|aes ^SlappFisa^ Bhz`OFF Unf[BNC]Lion b00z\\away Raised|ProBlem [A]fittb extinct`zake blike|AplE`oFF eNtiC MeLLKeR\n:port80c.se.quakenet.org 353 matricks_ = #pcw :SNELHEST Nexo rkO`aw zG|Numse_ Maff n9way|mIkLo bEnz SpiderA _cgx GZ`cAD RICK1DAH fun|Skippsen INFAME|eRIKa\\aw SS|xtinqt _mys|da HolySmoke Rq hoorai\\naolein qutip mYth|schnaLz_M rengo`off aRa|Voilala^Off skilleAWAY BCS^OFF|dexer @FSHost-com aeom`away tvekaOFF`haMME Smog^ PartyPoker Sp|SpeTLighT^OF [Fixx]Olle sIMMe`offline panik_herman avu\\partz0r rekyL^_- BCS^OFF|AMPARI Fluen^BNC Wkd^off eXm-SunnY^ ^hej Kniks DiXeR`off rfwdm_ TPI_piggerN_ Mataza|off\n:port80c.se.quakenet.org 353 matricks_ = #pcw :epzBNC Ampro @hardstep goL|craJpAW WwG-Muste E|Evil^off MADREFLEX`rhZ adde` Crazy^SpexXI Jerker alq-andreA H1Xer aGILITY`POLYMOX Joker^BNC Mohkis [LEGE]HeJLeN^ Caprice Intgen`BAERB{J} VILLIG-7thAWAY Neehajd`BNC Batti LewfeN^Off Ravnn sky\\bangz0ff`` SkenaN^bnc GladPanda fausti pittins^BNC SaX|f|Gubbi^ rM|pIx^^ Rms- RANGERBOY`aw FixxeR^ Edvnz uga BoSS|Benal`BNC sjonasm8k PND\\s humpyskump SKOVDE|Snasi @HighTech @spam-scan @S @Q @[-hoorai-] STEN11\n:port80c.se.quakenet.org 353 matricks_ = #pcw :Voteski xP|Puhbaer^off Yoshi_ CWE`Flippen CeveRR [ShaKa]CoOoL`AW h3h3 LnC-iNZANEoff_ Wu-djaoff Zerooo Pieper_ chica`SanziLOFF BB4FRAGS|XTM`A limespOFF`malle oPS|JBbnc staphe G`Quix NItron\\bnc c55-feros hejx HighG`wdE_OFF eco`zN Myt willybob`bnc Rh-G^TippeR^ JUHP-BNC|Jumert mthz Moldskred MxG\\\\MailBoX MeejtAWAY [c]eKipz dkz`xfx zaped`off ptrNo_OFF Jeamu c`Crelle-R^off rew`away Ak-87^ TOOOMMY\\off L2D_-_Rappi Ghost^BNC _AraCi SKytteN^ ^StoKer^\n:port80c.se.quakenet.org 353 matricks_ = #pcw :zNei mYth|LucK3r n-N|TarriC poohi hamasbnc Coutz1 Char|ieBoY AZ^LEVING-BNC plike^HuliaN___ uR`saniOFF Gtrip|Hebo`OFF Redical`Score IceBlu EvilEye_bnc maaxi`off [AWAY]Darkling Noobet|StajOFF bjarne-_- zG|Eriksen^Off venom^off mHuen utini_off eveni\\OFF Xqe MefistoFX`oFF bas-off|f4me TRiCK`iDfye MAAUNS CamiK^ GrQnaerten blike|amns`oFF sandersan Lt`HipPus Mossepo siOFF \\zimze`BNC R33t Gs\\BaZe^OFF zaney drateR^OFF Free1337 off|Hunter ifrit apfelmus\n:port80c.se.quakenet.org 353 matricks_ = #pcw :eu-off|Blade jfl-oFF`miD Uniline charlie` painkiller`kool OFF|ShOcK telk0^BNC gh|jack^off EX-adrin^bnc w\\Hairboi osfa|puddy^off CruisE-OFF- [A1]EnGud kungeeN^^ CMAX|[m]addilo Sk-off|MichYs9N NTL-Sentinal Tjalfuglen^off KapteWN`BNC cichlide^AWAY ChomP`away paltieBNC^[cz] WGV|PwnZ^Off pidde-_- TELETUBBIE Ecka fazer|NoxtrnOFF Lolad-net^ diRectAWAY evil|parasite xultRoNaw genics^BNC steri`off RaliAWAY oxid`zsiltsoff xazury`bnc IRLHELTEN r0ntti\n:port80c.se.quakenet.org 353 matricks_ = #pcw :searon_ Saturn` Nimra jOHNSONN KegleN^AFK JC|PlaNke d4NNY`0fflajn MuGGe^Bnc _4P|StyLish^bnc s8`swinnnk Jackkis F`off`NickyH F5_rakkeeee Thuriaz inzym Moriz edom z1ax^0FFL1NE eXm-nex0r|bNc unstuck|L- aimstyle`vzn\\a Gaylorden WrD ShadowOfAMaN gh|8Ball^off Retard-- SAGG-Lipton backyard\\KoWORK awaylen BCS^OFF|Pipe TPI`Ferro fredde` xeet_ BlaZe180 Macan_ biblas^BNC Cyeclone Vali[away] BK|awayman armoryh oKend _cB-Us3-Bnc_ Kefir [nerd]Kurr3\n"
  },
  {
    "path": "scripts/png.py",
    "content": "import struct, zlib, sys\n\nclass image:\n\tw = 0\n\th = 0\n\tdata = []\n\ndef read_tga(f):\n\timage = f.read()\n\timg_type = struct.unpack(\"<B\", image[2:3])[0]\n\timg_bpp = struct.unpack(\"<B\", image[16:17])[0]\n\timg_width = struct.unpack(\"<H\", image[12:14])[0]\n\timg_height = struct.unpack(\"<H\", image[14:16])[0]\n\n\tif img_type != 2 or img_bpp != 32:\n\t\tprint \"image must be a RGBA\"\n\n\tstart = 18+struct.unpack(\"B\", image[0])[0]\n\tend = start + img_width*img_height*4\n\timage_data = image[start:end] # fetch raw data\n\treturn image_data\n\ndef write_tga(f, w, h, bpp, data):\n\tf.write(struct.pack(\"<BBBHHBHHHHBB\", 0, 0, 2, 0, 0, 0, 0, 0, w, h, bpp, 0) + data)\n\n\n\n\n\ndef load_png(f):\n\tdef read(fmt): return struct.unpack(\"!\"+fmt, f.read(struct.calcsize(\"!\"+fmt)))\n\tdef skip(count): f.read(count)\n\n\t# read signature\n\tif read(\"cccccccc\") != ('\\x89', 'P', 'N', 'G', '\\r', '\\n', '\\x1a', '\\n'):\n\t\treturn 0\n\n\t# read chunks\n\twidth = -1\n\theight = -1\n\timagedata = \"\"\n\twhile 1:\n\t\tsize, id = read(\"I4s\")\n\t\tif id == \"IHDR\": # read header\n\t\t\twidth, height, bpp, colortype, compression, filter, interlace = read(\"IIBBBBB\")\n\t\t\tif bpp != 8 or compression != 0 or filter != 0 or interlace != 0 or (colortype != 2 and colortype != 6):\n\t\t\t\tprint \"can't handle png of this type\"\n\t\t\t\tprint width, height, bpp, colortype, compression, filter, interlace\n\t\t\t\treturn 0\n\t\t\tskip(4)\n\t\telif id == \"IDAT\":\n\t\t\timagedata += f.read(size)\n\t\t\tskip(4) # read data\n\t\telif id == \"IEND\":\n\t\t\tbreak # we are done! \\o/\n\t\telse:\n\t\t\tskip(size+4) # skip unknown chunks\n\n\t# decompress image data\n\trawdata = map(ord, zlib.decompress(imagedata))\n\t\n\t# apply per scanline filters\n\tpitch = width*4+1\n\tbpp = 4\n\timgdata = []\n\tprevline = [0 for x in xrange(0, (width+1)*bpp)]\n\tfor y in xrange(0,height):\n\t\tfilter = rawdata[pitch*y]\n\t\tpixeldata = rawdata[pitch*y+1:pitch*y+pitch]\n\t\tthisline = [0 for x in xrange(0,bpp)]\n\t\tdef paeth(a, b, c):\n\t\t\tp = a + b - c\n\t\t\tpa = abs(p - a)\n\t\t\tpb = abs(p - b)\n\t\t\tpc = abs(p - c)\n\t\t\tif pa <= pb and pa <= pc:\n\t\t\t\treturn a\n\t\t\tif pb <= pc:\n\t\t\t\treturn b\n\t\t\treturn c\n\t\t\n\t\tif filter == 0: f = lambda a,b,c: 0\n\t\telif filter == 1: f = lambda a,b,c: a\n\t\telif filter == 2: f = lambda a,b,c: b\n\t\telif filter == 3: f = lambda a,b,c: (a+b)/2\n\t\telif filter == 4: f = paeth\n\t\t\t\n\t\tfor x in xrange(0, width*bpp):\n\t\t\tthisline += [(pixeldata[x] + f(thisline[x], prevline[x+bpp], prevline[x])) % 256]\t\t\t\n\t\t\t\n\t\tprevline = thisline\n\t\timgdata += thisline[4:]\n\t\n\traw = \"\"\n\tfor x in imgdata:\n\t\traw += struct.pack(\"B\", x)\n\t\t\n\t#print len(raw), width*height*4\n\twrite_tga(file(\"test2.tga\", \"w\"), width, height, 32, raw)\n\treturn 0\n\t\nload_png(file(\"butterfly2.png\", \"rb\"))"
  },
  {
    "path": "scripts/process_blame.py",
    "content": "import sys\nuser_map = {\"kma\":\"matricks\", \"teetow\":\"matricks\", \"jlha\":\"matricks\", \"jdv\":\"void\", \"jaf\":\"serp\"}\nusers = {}\nfor line in sys.stdin:\n\tfields = line.split()\n\tname = user_map.get(fields[1], fields[1])\n\tusers[name] = users.get(name, 0) + 1\n\t\ntotal = reduce(lambda x,y: x+y, users.values())\nfor u in users:\n\tprint \"%6s %6d %s\" % (\"%03.2f\"%(users[u]*100.0/total), users[u], u)\nprint \"%03.2f %6d %s\" % (100, total, \"Total\")\n"
  },
  {
    "path": "scripts/refactor_count.py",
    "content": "import os, re, sys\n\nalphanum = \"0123456789abcdefghijklmnopqrstuvwzyxABCDEFGHIJKLMNOPQRSTUVWXYZ_\"\ncpp_keywords = [\"auto\", \"const\", \"double\", \"float\", \"int\", \"short\", \"struct\", \"unsigned\", # C\n\"break\", \"continue\", \"else\", \"for\", \"long\", \"signed\", \"switch\", \"void\",\n\"case\", \"default\", \"enum\", \"goto\", \"register\", \"sizeof\", \"typedef\", \"volatile\",\n\"char\", \"do\", \"extern\", \"if\", \"return\", \"static\", \"union\", \"while\",\n\n\"asm\", \"dynamic_cast\", \"namespace\", \"reinterpret_cast\", \"try\", # C++\n\"bool\", \"explicit\", \"new\", \"static_cast\", \"typeid\",\n\"catch\", \"false\", \"operator\", \"template\", \"typename\",\n\"class\", \"friend\", \"private\", \"this\", \"using\",\n\"const_cast\", \"inline\", \"public\", \"throw\", \"virtual\",\n\"delete\", \"mutable\", \"protected\", \"true\", \"wchar_t\"]\n\nallowed_words = []\n\n#allowed_words += [\"bitmap_left\", \"advance\", \"glyph\"] # ft2\n\n\nallowed_words += [\"qsort\"] # stdio / stdlib\nallowed_words += [\"size_t\", \"cosf\", \"sinf\", \"asinf\", \"acosf\", \"atanf\", \"powf\", \"fabs\", \"rand\", \"powf\", \"fmod\", \"sqrtf\"] # math.h\nallowed_words += [\"time_t\", \"time\", \"strftime\", \"localtime\"] # time.h\nallowed_words += [ # system.h\n\t\"int64\",\n\t\"dbg_assert\", \"dbg_msg\", \"dbg_break\", \"dbg_logger_stdout\", \"dbg_logger_debugger\", \"dbg_logger_file\",\n\t\"mem_alloc\", \"mem_zero\", \"mem_free\", \"mem_copy\", \"mem_move\", \"mem_comp\", \"mem_stats\", \"total_allocations\", \"allocated\",\n\t\"thread_create\", \"thread_sleep\", \"lock_wait\", \"lock_create\", \"lock_release\", \"lock_destroy\", \"swap_endian\",\n\t\"io_open\", \"io_read\", \"io_read\", \"io_write\", \"io_flush\", \"io_close\", \"io_seek\", \"io_skip\", \"io_tell\", \"io_length\",\n\t\"str_comp\", \"str_length\", \"str_quickhash\", \"str_format\", \"str_copy\", \"str_comp_nocase\", \"str_sanitize\", \"str_append\",\n\t\"str_comp_num\", \"str_find_nocase\", \"str_sanitize_strong\", \"str_uppercase\", \"str_toint\", \"str_tofloat\",\n\t\"str_utf8_encode\", \"str_utf8_rewind\", \"str_utf8_forward\", \"str_utf8_decode\", \"str_sanitize_cc\", \"str_skip_whitespaces\",\n\t\"fs_makedir\", \"fs_listdir\", \"fs_storage_path\", \"fs_is_dir\",\n\t\"net_init\", \"net_addr_comp\", \"net_host_lookup\", \"net_addr_str\", \"type\", \"port\", \"net_addr_from_str\", \n\t\"net_udp_create\", \"net_udp_send\", \"net_udp_recv\", \"net_udp_close\", \"net_socket_read_wait\",\n\t\"net_stats\", \"sent_bytes\", \"recv_bytes\", \"recv_packets\", \"sent_packets\",\n\t\"time_get\", \"time_freq\", \"time_timestamp\"] \n\t\nallowed_words += [\"vec2\", \"vec3\", \"vec4\", \"round\", \"clamp\", \"length\", \"dot\", \"normalize\", \"frandom\", \"mix\", \"distance\", \"min\",\n        \"closest_point_on_line\", \"max\", \"absolute\"] # math.hpp\nallowed_words += [  # tl\n\t\"array\", \"sorted_array\", \"string\",\n\t\"all\", \"sort\", \"add\", \"remove_index\", \"remove\", \"delete_all\", \"set_size\",\n\t\"base_ptr\", \"size\", \"swap\", \"empty\", \"front\", \"pop_front\", \"find_binary\", \"find_linear\", \"clear\", \"range\", \"end\", \"cstr\",\n\t\"partition_linear\", \"partition_binary\"]\nallowed_words += [\"fx2f\", \"f2fx\"] # fixed point math\n\ndef CheckIdentifier(ident):\n\treturn False\n\nclass Checker:\n\tdef CheckStart(self, checker, filename):\n\t\tpass\n\tdef CheckLine(self, checker, line):\n\t\tpass\n\tdef CheckEnd(self, checker):\n\t\tpass\n\nclass FilenameExtentionChecker(Checker):\n\tdef __init__(self):\n\t\tself.allowed = [\".cpp\", \".h\"]\n\tdef CheckStart(self, checker, filename):\n\t\text = os.path.splitext(filename)[1]\n\t\tif not ext in self.allowed:\n\t\t\tchecker.Error(\"file extention '%s' is not allowed\" % ext)\n\nclass IncludeChecker(Checker):\n\tdef __init__(self):\n\t\tself.disallowed_headers = [\"stdio.h\", \"stdlib.h\", \"string.h\", \"memory.h\"]\n\tdef CheckLine(self, checker, line):\n\t\tif \"#include\" in line:\n\t\t\tinclude_file = \"\"\n\t\t\tif '<' in line:\n\t\t\t\tinclude_file = line.split('<')[1].split(\">\")[0]\n\t\t\t\t#if not \"/\" in include_file:\n\t\t\t\t#\tchecker.Error(\"%s is not allowed\" % include_file)\n\t\t\telif '\"' in line:\n\t\t\t\tinclude_file = line.split('\"')[1]\n\t\t\t\n\t\t\t#print include_file\n\t\t\tif include_file in self.disallowed_headers:\n\t\t\t\tchecker.Error(\"%s is not allowed\" % include_file)\n\nclass HeaderGuardChecker(Checker):\n\tdef CheckStart(self, checker, filename):\n\t\tself.check = \".h\" in filename\n\t\tself.guard = \"#ifndef \" + filename[4:].replace(\"/\", \"_\").replace(\".hpp\", \"\").replace(\".h\", \"\").upper() + \"_H\"\n\tdef CheckLine(self, checker, line):\n\t\tif self.check:\n\t\t\t#if \"#\" in line:\n\t\t\tself.check = False\n\t\t\t#if not self.check:\n\t\t\tif line.strip() ==  self.guard:\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tchecker.Error(\"malformed or missing header guard. Should be '%s'\" % self.guard)\n\nclass CommentChecker(Checker):\n\tdef CheckLine(self, checker, line):\n\t\tif line.strip()[-2:] == \"*/\" and \"/*\" in line:\n\t\t\tchecker.Error(\"single line multiline comment\")\n\nclass FileChecker:\n\tdef __init__(self):\n\t\tself.checkers = []\n\t\tself.checkers += [FilenameExtentionChecker()]\n\t\tself.checkers += [HeaderGuardChecker()]\n\t\tself.checkers += [IncludeChecker()]\n\t\tself.checkers += [CommentChecker()]\n\n\tdef Error(self, errormessage):\n\t\tself.current_errors += [(self.current_line, errormessage)]\n\n\tdef CheckLine(self, line):\n\t\tfor c in self.checkers:\n\t\t\tc.CheckLine(self, line)\n\t\treturn True\n\t\n\tdef CheckFile(self, filename):\n\t\tself.current_file = filename\n\t\tself.current_line = 0\n\t\tself.current_errors = []\n\t\tfor c in self.checkers:\n\t\t\tc.CheckStart(self, filename)\n\t\t\t\n\t\tfor line in file(filename).readlines():\n\t\t\tself.current_line += 1\n\t\t\tif \"ignore_check\" in line:\n\t\t\t\tcontinue\n\t\t\tself.CheckLine(line)\n\n\t\tfor c in self.checkers:\n\t\t\tc.CheckEnd(self)\n\t\n\tdef GetErrors(self):\n\t\treturn self.current_errors\n\t\t\ndef cstrip(lines):\n\td = \"\"\n\tfor l in lines:\n\t\tif \"ignore_convention\" in l:\n\t\t\tcontinue\n\t\tl = re.sub(\"^[\\t ]*#.*\", \"\", l)\n\t\tl = re.sub(\"//.*\", \"\", l)\n\t\tl = re.sub('\\\".*?\\\"', '\"String\"', l) # remove strings\n\t\td += l.strip() + \" \"\n\td = re.sub('\\/\\*.*?\\*\\/', \"\", d) # remove /* */ comments\n\td = d.replace(\"\\t\", \" \") # tab to space\n\td = re.sub(\"  *\", \" \", d) # remove double spaces\n\t#d = re.sub(\"\", \"\", d) # remove /* */ comments\n\t\n\td = d.strip()\n\t\n\t# this eats up cases like 'n {'\n\ti = 1\n\twhile i < len(d)-2:\n\t\tif d[i] == ' ':\n\t\t\tif not (d[i-1] in alphanum and d[i+1] in alphanum):\n\t\t\t\td = d[:i] + d[i+1:]\n\t\ti += 1\n\treturn d\n\n#def stripstrings(data):\n#\treturn re.sub('\\\".*?\\\"', 'STRING', data)\n\t\ndef get_identifiers(data):\n\tidents = {}\n\tdata = \" \"+data+\" \"\n\tregexp = re.compile(\"[^a-zA-Z0-9_][a-zA-Z_][a-zA-Z0-9_]+[^a-zA-Z0-9_]\")\n\tstart = 0\n\twhile 1:\n\t\tm = regexp.search(data, start)\n\t\t\n\t\tif m == None:\n\t\t\tbreak\n\t\tstart = m.end()-1\n\t\tname = data[m.start()+1:m.end()-1]\n\t\tif name in idents:\n\t\t\tidents[name] += 1\n\t\telse:\n\t\t\tidents[name] = 1\n\treturn idents\n\ngrand_total = 0\ngrand_offenders = 0\n\ngen_html = 1\n\nif gen_html:\n\tprint \"<head>\"\n\tprint '<link href=\"/style.css\" rel=\"stylesheet\" type=\"text/css\" />'\n\tprint \"</head>\"\n\tprint \"<body>\"\n\n\n\n\tprint '<div id=\"outer\">'\n\n\tprint '<div id=\"top_left\"><div id=\"top_right\"><div id=\"top_mid\">'\n\tprint '<a href=\"/\"><img src=\"/images/twlogo.png\" alt=\"teeworlds logo\" /></a>'\n\tprint '</div></div></div>'\n\n\tprint '<div id=\"menu_left\"><div id=\"menu_right\"><div id=\"menu_mid\">'\n\tprint '</div></div></div>'\n\n\tprint '<div id=\"tlc\"><div id=\"trc\"><div id=\"tb\">&nbsp;</div></div></div>'\n\tprint '<div id=\"lb\"><div id=\"rb\"><div id=\"mid\">'\n\tprint '<div id=\"container\">'\n\n\tprint '<p class=\"topic_text\">'\n\tprint '<h1>Code Refactoring Progress</h1>'\n\tprint '''This is generated by a script that find identifiers in the code\n\tthat doesn't conform to the code standard. Right now it only shows headers\n\tbecause they need to be fixed before we can do the rest of the source.\n\tThis is a ROUGH estimate of the progress'''\n\tprint '</p>'\n\n\tprint '<p class=\"topic_text\">'\n\tprint '<table>'\n\t#print \"<tr><td><b>%</b></td><td><b>#</b></td><td><b>File</b></td><td><b>Offenders</b></td></tr>\"\n\nline_order = 1\ntotal_files = 0\ncomplete_files = 0\ntotal_errors = 0\n\nfor (root,dirs,files) in os.walk(\"src\"):\n\tfor filename in files:\n\t\tfilename = os.path.join(root, filename)\n\t\tif \"/.\" in filename or \"/external/\" in filename or \"/base/\" in filename or \"/generated/\" in filename:\n\t\t\tcontinue\n\t\tif \"src/osxlaunch/client.h\" in filename: # ignore this file, ObjC file\n\t\t\tcontinue\n\t\tif \"e_config_variables.h\" in filename: # ignore config files\n\t\t\tcontinue\n\t\tif \"src/game/variables.hpp\" in filename: # ignore config files\n\t\t\tcontinue\n\t\t\t\n\t\tif not (\".hpp\" in filename or \".h\" in filename or \".cpp\" in filename):\n\t\t\tcontinue\n\t\t\n\t\t#total_files += 1\n\t\t\n\t\t#if not \"src/engine/client/ec_client.cpp\" in filename:\n\t\t#\tcontinue\n\t\t\n\t\tf = FileChecker()\n\t\tf.CheckFile(filename)\n\t\tnum_errors = len(f.GetErrors())\n\t\ttotal_errors += num_errors\n\t\t\n\t\tif num_errors:\n\t\t\tprint '<tr style=\"background: #e0e0e0\"><td colspan=\"2\">%s, %d errors</td></tr>' % (filename, num_errors),\n\t\t\tfor line, msg in f.GetErrors():\n\t\t\t\tprint '<tr\"><td>%d</td><td>%s</td></tr>' % (line, msg)\n\t\t\t#print '<table>'\n\t\t\t#GetErrors()\n\t\t\t\n\t\t\n\t\t\n\t\t\n\t\tif 0:\n\t\t\ttext = cstrip(file(filename).readlines()) # remove all preprocessor stuff and comments\n\t\t\t#text = stripstrings(text) # remove strings (does not solve all cases however)\n\t\t\t#print text\n\t\t\t\n\t\t\tidents = get_identifiers(text)\n\t\t\toffenders = 0\n\t\t\ttotal = 0\n\t\t\toffender_list = {}\n\t\t\tfor name in idents:\n\t\t\t\t#print name\n\t\t\t\tif len(name) <= 2: # skip things that are too small\n\t\t\t\t\tcontinue\n\t\t\t\tif name in cpp_keywords: # skip keywords\n\t\t\t\t\tcontinue\n\t\t\t\tif name in allowed_words: # skip allowed keywords\n\t\t\t\t\tcontinue\n\t\t\t\t\t\n\t\t\t\ttotal += idents[name]\n\t\t\t\tif name != name.lower(): # strip names that are not only lower case\n\t\t\t\t\tcontinue\n\t\t\t\toffender_list[name] = idents[name]\n\t\t\t\tif not gen_html:\n\t\t\t\t\tprint \"[%d] %s\"%(idents[name], name)\n\t\t\t\toffenders += idents[name]\n\t\t\t\n\t\t\tgrand_total += total\n\t\t\tgrand_offenders += offenders\n\t\t\t\n\t\t\tif total == 0:\n\t\t\t\ttotal = 1\n\t\t\t\n\t\t\tline_order = -line_order\n\t\t\t\n\t\t\t\n\t\t\tdone = int((1-(offenders / float(total))) * 100)\n\t\t\tif done == 100:\n\t\t\t\tcomplete_files += 1\n\n\t\t\tif done != 100 and gen_html:\n\t\t\t\tcolor = \"#ffa0a0\"\n\t\t\t\tif done > 20:\n\t\t\t\t\tcolor = \"#ffd080\"\n\t\t\t\tif done > 50:\n\t\t\t\t\tcolor = \"#ffff80\"\n\t\t\t\tif done > 75:\n\t\t\t\t\tcolor = \"#e0ff80\"\n\t\t\t\tif done == 100:\n\t\t\t\t\tcolor = \"#80ff80\"\n\t\t\t\t\t\n\t\t\t\tline_color = \"#f0efd5\"\n\t\t\t\tif line_order > 0:\n\t\t\t\t\tline_color = \"#ffffff\"\n\t\t\t\t\n\t\t\t\toffender_string = \"\"\n\t\t\t\tcount = 0\n\t\t\t\tfor name in offender_list:\n\t\t\t\t\tcount += 1\n\t\t\t\t\toffender_string += \"[%d]%s \" % (offender_list[name], name)\n\t\t\t\t\t\n\t\t\t\t\tif count%5 == 0:\n\t\t\t\t\t\toffender_string += \"<br/>\"\n\t\t\t\t\t\n\t\t\t\tprint '<tr style=\"background: %s\">' % line_color,\n\t\t\t\tprint '<td style=\"text-align: right; background: %s\"><b>%d%%</b></td><td style=\"text-align: center\">%d</td><td>%s</td>' % (color, done, offenders, filename),\n\t\t\t\tprint '<td style=\"text-align: right\">%s</td>' % offender_string\n\t\t\t\tprint \"</tr>\"\n\t\t\tcount = 0\n\nif gen_html:\n\tprint \"</table>\"\n\t\n\tprint \"<h1>%d errors</h1>\" % total_errors\n\t\n\t\n\tif 0:\n\t\tprint \"<h1>%.1f%% Identifiers done</h1>\" % ((1-(grand_offenders / float(grand_total))) * 100)\n\t\tprint \"%d left of %d\" % (grand_offenders, grand_total)\n\t\tprint \"<h1>%.1f%% Files done</h1>\" % ((complete_files / float(total_files)) * 100)\n\t\tprint \"%d left of %d\" % (total_files-complete_files, total_files)\n\n\tprint \"</p>\"\n\tprint \"<div style='clear:both;'></div>\"\n\tprint '</div>'\n\tprint '</div></div></div>'\n\n\tprint '<div id=\"blc\"><div id=\"brc\"><div id=\"bb\">&nbsp;</div></div></div>'\n\tprint '</div>'\n\n\tprint \"</body>\"\n"
  },
  {
    "path": "scripts/tw_api.py",
    "content": "# coding: utf-8\nfrom socket import *\nimport struct\nimport sys\nimport threading\nimport time\n\n\n\nNUM_MASTERSERVERS = 4\nMASTERSERVER_PORT = 8300\n\nTIMEOUT = 2\n\nSERVERTYPE_NORMAL = 0\nSERVERTYPE_LEGACY = 1\n\nPACKET_GETLIST = \"\\x20\\x00\\x00\\x00\\x00\\x00\\xff\\xff\\xff\\xffreqt\"\nPACKET_GETLIST2 = \"\\x20\\x00\\x00\\x00\\x00\\x00\\xff\\xff\\xff\\xffreq2\"\nPACKET_GETINFO = \"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xffgief\"\nPACKET_GETINFO2 = \"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xffgie2\" + \"\\x00\"\nPACKET_GETINFO3 = \"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xffgie3\" + \"\\x00\"\n\n\n\nclass Server_Info(threading.Thread):\n\n\tdef __init__(self, address, type):\n\t\tself.address = address\n\t\tself.type = type\n\t\tself.finished = False\n\t\tthreading.Thread.__init__(self, target = self.run)\n\n\tdef run(self):\n\t\tself.info = None\n\t\tif self.type == SERVERTYPE_NORMAL:\n\t\t\tself.info = get_server_info3(self.address)\n\t\telif self.type == SERVERTYPE_LEGACY:\n\t\t\tself.info = get_server_info(self.address)\n\t\t\tif self.info:\n\t\t\t\tself.info = get_server_info2(self.address)\n\t\tself.finished = True\n\n\ndef get_server_info(address):\n\ttry:\n\t\tsock = socket(AF_INET, SOCK_DGRAM)\n\t\tsock.settimeout(TIMEOUT);\n\t\tsock.sendto(PACKET_GETINFO, address)\n\t\tdata, addr = sock.recvfrom(1024)\n\t\tsock.close()\n\n\t\tdata = data[14:] # skip header\n\t\tslots = data.split(\"\\x00\")\n\n\t\tserver_info = {}\n\t\tserver_info[\"version\"] = slots[0]\n\t\tserver_info[\"name\"] = slots[1]\n\t\tserver_info[\"map\"] = slots[2]\n\t\tserver_info[\"gametype\"] = slots[3]\n\t\tserver_info[\"flags\"] = int(slots[4])\n\t\tserver_info[\"progression\"] = int(slots[5])\n\t\tserver_info[\"num_players\"] = int(slots[6])\n\t\tserver_info[\"max_players\"] = int(slots[7])\n\t\tserver_info[\"players\"] = []\n\n\t\tfor i in xrange(0, server_info[\"num_players\"]):\n\t\t\tplayer = {}\n\t\t\tplayer[\"name\"] = slots[8+i*2]\n\t\t\tplayer[\"score\"] = int(slots[8+i*2+1])\n\t\t\tserver_info[\"players\"].append(player)\n\n\t\treturn server_info\n\n\texcept:\n\t\tsock.close()\n\t\treturn None\n\n\ndef get_server_info2(address):\n\ttry:\n\t\tsock = socket(AF_INET, SOCK_DGRAM)\n\t\tsock.settimeout(TIMEOUT);\n\t\tsock.sendto(PACKET_GETINFO2, address)\n\t\tdata, addr = sock.recvfrom(1024)\n\t\tsock.close()\n\n\t\tdata = data[14:] # skip header\n\t\tslots = data.split(\"\\x00\")\n\n\t\tserver_info = {}\n\t\tserver_info[\"token\"] = slots[0]\n\t\tserver_info[\"version\"] = slots[1]\n\t\tserver_info[\"name\"] = slots[2]\n\t\tserver_info[\"map\"] = slots[3]\n\t\tserver_info[\"gametype\"] = slots[4]\n\t\tserver_info[\"flags\"] = int(slots[5])\n\t\tserver_info[\"progression\"] = int(slots[6])\n\t\tserver_info[\"num_players\"] = int(slots[7])\n\t\tserver_info[\"max_players\"] = int(slots[8])\n\t\tserver_info[\"players\"] = []\n\n\t\tfor i in xrange(0, server_info[\"num_players\"]):\n\t\t\tplayer = {}\n\t\t\tplayer[\"name\"] = slots[9+i*2]\n\t\t\tplayer[\"score\"] = int(slots[9+i*2+1])\n\t\t\tserver_info[\"players\"].append(player)\n\n\t\treturn server_info\n\n\texcept:\n\t\tsock.close()\n\t\treturn None\n\n\ndef get_server_info3(address):\n\ttry:\n\t\tsock = socket(AF_INET, SOCK_DGRAM)\n\t\tsock.settimeout(TIMEOUT);\n\t\tsock.sendto(PACKET_GETINFO3, address)\n\t\tdata, addr = sock.recvfrom(1400)\n\t\tsock.close()\n\n\t\tdata = data[14:] # skip header\n\t\tslots = data.split(\"\\x00\")\n\n\t\tserver_info = {}\n\t\tserver_info[\"token\"] = slots[0]\n\t\tserver_info[\"version\"] = slots[1]\n\t\tserver_info[\"name\"] = slots[2]\n\t\tserver_info[\"map\"] = slots[3]\n\t\tserver_info[\"gametype\"] = slots[4]\n\t\tserver_info[\"flags\"] = int(slots[5])\n\t\tserver_info[\"num_players\"] = int(slots[6])\n\t\tserver_info[\"max_players\"] = int(slots[7])\n\t\tserver_info[\"num_clients\"] = int(slots[8])\n\t\tserver_info[\"max_clients\"] = int(slots[9])\n\t\tserver_info[\"players\"] = []\n\n\t\tfor i in xrange(0, server_info[\"num_clients\"]):\n\t\t\tplayer = {}\n\t\t\tplayer[\"name\"] = slots[10+i*5]\n\t\t\tplayer[\"clan\"] = slots[10+i*5+1]\n\t\t\tplayer[\"country\"] = int(slots[10+i*5+2])\n\t\t\tplayer[\"score\"] = int(slots[10+i*5+3])\n\t\t\tif int(slots[10+i*5+4]):\n\t\t\t\tplayer[\"player\"] = True\n\t\t\telse:\n\t\t\t\tplayer[\"player\"] = False\n\t\t\tserver_info[\"players\"].append(player)\n\n\t\treturn server_info\n\n\texcept:\n\t\tsock.close()\n\t\treturn None\n\n\n\nclass Master_Server_Info(threading.Thread):\n\n\tdef __init__(self, address):\n\t\tself.address = address\n\t\tself.finished = False\n\t\tthreading.Thread.__init__(self, target = self.run)\n\n\tdef run(self):\n\t\tself.servers = get_list(self.address) + get_list2(self.address)\n\t\tself.finished = True\n\n\ndef get_list(address):\n\tservers = []\n\n\ttry:\n\t\tsock = socket(AF_INET, SOCK_DGRAM)\n\t\tsock.settimeout(TIMEOUT)\n\t\tsock.sendto(PACKET_GETLIST, address)\n\n\t\twhile 1:\n\t\t\tdata, addr = sock.recvfrom(1024)\n\n\t\t\tdata = data[14:]\n\t\t\tnum_servers = len(data) / 6\n\n\t\t\tfor n in range(0, num_servers):\n\t\t\t\tip = \".\".join(map(str, map(ord, data[n*6:n*6+4])))\n\t\t\t\tport = ord(data[n*6+5]) * 256 + ord(data[n*6+4])\n\t\t\t\tservers += [[(ip, port), SERVERTYPE_LEGACY]]\n\n\texcept:\n\t\tsock.close()\n\n\treturn servers\n\n\ndef get_list2(address):\n\tservers = []\n\n\ttry:\n\t\tsock = socket(AF_INET, SOCK_DGRAM)\n\t\tsock.settimeout(TIMEOUT)\n\t\tsock.sendto(PACKET_GETLIST2, address)\n\n\t\twhile 1:\n\t\t\tdata, addr = sock.recvfrom(1400)\n\t\t\t\n\t\t\tdata = data[14:]\n\t\t\tnum_servers = len(data) / 18\n\n\t\t\tfor n in range(0, num_servers): \n\t\t\t\tif data[n*18:n*18+12] == \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xff\\xff\":\n\t\t\t\t\tip = \".\".join(map(str, map(ord, data[n*18+12:n*18+16])))\n\t\t\t\telse:\n\t\t\t\t\tip = \":\".join(map(str, map(ord, data[n*18:n*18+16])))\n\t\t\t\tport = (ord(data[n*18+16])<<8) + ord(data[n*18+17])\n\t\t\t\tservers += [[(ip, port), SERVERTYPE_NORMAL]]\n\n\texcept:\n\t\tsock.close()\n\n\treturn servers\n\n\n\nmaster_servers = []\n\nfor i in range(1, NUM_MASTERSERVERS+1):\n\tm = Master_Server_Info((\"master%d.teeworlds.com\"%i, MASTERSERVER_PORT))\n\tmaster_servers.append(m)\n\tm.start()\n\ttime.sleep(0.001) # avoid issues\n\nservers = []\n\nwhile len(master_servers) != 0:\n\tif master_servers[0].finished == True:\n\t\tif master_servers[0].servers:\n\t\t\tservers += master_servers[0].servers\n\t\tdel master_servers[0]\n\ttime.sleep(0.001) # be nice\n\nservers_info = []\n\nprint str(len(servers)) + \" servers\"\n\nfor server in servers:\n\ts = Server_Info(server[0], server[1])\n\tservers_info.append(s)\n\ts.start()\n\ttime.sleep(0.001) # avoid issues\n\nnum_players = 0\nnum_clients = 0\n\nwhile len(servers_info) != 0:\n\tif servers_info[0].finished == True:\n\n\t\tif servers_info[0].info:\n\t\t\tnum_players += servers_info[0].info[\"num_players\"]\n\t\t\tif servers_info[0].type == SERVERTYPE_NORMAL:\n\t\t\t\tnum_clients += servers_info[0].info[\"num_clients\"]\n\t\t\telse:\n\t\t\t\tnum_clients += servers_info[0].info[\"num_players\"]\n\n\t\tdel servers_info[0]\n\n\ttime.sleep(0.001) # be nice\n\nprint str(num_players) + \" players and \" + str(num_clients-num_players) + \" spectators\"\n"
  },
  {
    "path": "scripts/twlib.py",
    "content": "import sys\nif sys.version_info[0] == 2:\n\timport urllib\n\turl_lib = urllib\nelif sys.version_info[0] == 3:\n\timport urllib.request\n\turl_lib = urllib.request\n\ndef fetch_file(url):\n\ttry:\n\t\tprint(\"trying %s\" % url)\n\t\tlocal = dict(url_lib.urlopen(url).info())[\"content-disposition\"].split(\"=\")[1]\n\t\turl_lib.urlretrieve(url, local)\n\t\treturn local\n\texcept:\n\t\treturn False\n"
  },
  {
    "path": "scripts/update_localization.py",
    "content": "import os, re, sys\nmatch = re.search('(.*)/', sys.argv[0])\nif match != None:\n\tos.chdir(match.group(1))\n\nsource_exts = [\".c\", \".cpp\", \".h\"]\ncontent_author = \"\"\n\ndef parse_source():\n\tstringtable = {}\n\tdef process_line(line):\n\t\tif 'Localize(\"'.encode() in line:\n\t\t\tfields = line.split('Localize(\"'.encode(), 1)[1].split('\"'.encode(), 1)\n\t\t\tstringtable[fields[0]] = \"\"\n\t\t\tprocess_line(fields[1])\n\n\tfor root, dirs, files in os.walk(\"src\"):\n\t\tfor name in files:\n\t\t\tfilename = os.path.join(root, name)\n\t\t\t\n\t\t\tif os.sep + \"external\" + os.sep in filename:\n\t\t\t\tcontinue\n\t\t\t\n\t\t\tif filename[-2:] in source_exts or filename[-4:] in source_exts:\n\t\t\t\tfor line in open(filename, \"rb\"):\n\t\t\t\t\tprocess_line(line)\n\n\treturn stringtable\n\ndef load_languagefile(filename):\n\tf = open(filename, \"rb\")\n\tlines = f.readlines()\n\tf.close()\n\n\tstringtable = {}\n\tauthorpart = 0\n\tglobal content_author\n\n\tfor i in range(0, len(lines)-1):\n\t\tif authorpart == 0 and \"\\\"authors\\\":\".encode() in lines[i]:\n\t\t\tauthorpart = 1\n\t\t\tcontent_author = lines[i]\n\t\telif authorpart == 1:\n\t\t\tif  \"\\\"translated strings\\\":\".encode() in lines[i]:\n\t\t\t\tauthorpart = 2\n\t\t\telse:\n\t\t\t\tcontent_author += lines[i]\n\t\telif \"\\\"or\\\":\".encode() in lines[i]:\n\t\t\t\tstringtable[lines[i].strip()[7:-2]] = lines[i+1].strip()[7:-1]\n\n\treturn stringtable\n\ndef generate_languagefile(outputfilename, srctable, loctable):\n\tf = open(outputfilename, \"wb\")\n\n\tnum_items = 0\n\tnew_items = 0\n\told_items = 0\n\n\tsrctable_keys = []\n\tfor key in srctable:\n\t\tsrctable_keys.append(key)\n\tsrctable_keys.sort()\n\n\tcontent = content_author\n\n\tcontent += \"\\\"translated strings\\\": [\\n\".encode()\n\tfor k in srctable_keys:\n\t\tif k in loctable and len(loctable[k]):\n\t\t\tif not num_items == 0:\n\t\t\t\tcontent += \",\\n\".encode()\n\t\t\tcontent += \"\\t{\\n\\t\\t\\\"or\\\": \\\"\".encode() + k + \"\\\",\\n\\t\\t\\\"tr\\\": \\\"\".encode() + loctable[k] + \"\\\"\\n\\t}\".encode()\n\t\t\tnum_items += 1\n\tcontent += \"],\\n\".encode()\n\n\tcontent += \"\\\"needs translation\\\": [\\n\".encode()\n\tfor k in srctable_keys:\n\t\tif not k in loctable or len(loctable[k]) == 0:\n\t\t\tif not new_items == 0:\n\t\t\t\tcontent += \",\\n\".encode()\n\t\t\tcontent += \"\\t{\\n\\t\\t\\\"or\\\": \\\"\".encode() + k + \"\\\",\\n\\t\\t\\\"tr\\\": \\\"\\\"\\n\\t}\".encode()\n\t\t\tnum_items += 1\n\t\t\tnew_items += 1\n\tcontent += \"],\\n\".encode()\n\n\tcontent += \"\\\"old translations\\\": [\\n\".encode()\n\tfor k in loctable:\n\t\tif not k in srctable:\n\t\t\tif not old_items == 0:\n\t\t\t\tcontent += \",\\n\".encode()\n\t\t\tcontent += \"\\t{\\n\\t\\t\\\"or\\\": \\\"\".encode() + k + \"\\\",\\n\\t\\t\\\"tr\\\": \\\"\".encode() + loctable[k] + \"\\\"\\n\\t}\".encode()\n\t\t\tnum_items += 1\n\t\t\told_items += 1\n\tcontent += \"]\\n}\\n\".encode()\n\n\tf.write(content)\n\tf.close()\n\tprint(\"%-40s %8d %8d %8d\" % (outputfilename, num_items, new_items, old_items))\n\nsrctable = parse_source()\n\nprint(\"%-40s %8s %8s %8s\" % (\"filename\", \"total\", \"new\", \"old\"))\n\nfor filename in os.listdir(\"data/languages\"):\n\tif not filename[-5:] == \".json\" or filename == \"index.json\":\n\t\tcontinue\n\n\tfilename = \"data/languages/\" + filename\n\tgenerate_languagefile(filename, srctable, load_languagefile(filename))\n"
  },
  {
    "path": "src/base/detect.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef BASE_DETECT_H\n#define BASE_DETECT_H\n\n/*\n\tthis file detected the family, platform and architecture\n\tto compile for.\n*/\n\n/* platforms */\n\n/* windows Family */\n#if defined(WIN64) || defined(_WIN64)\n\t/* Hmm, is this IA64 or x86-64? */\n\t#define CONF_FAMILY_WINDOWS 1\n\t#define CONF_FAMILY_STRING \"windows\"\n\t#define CONF_PLATFORM_WIN64 1\n\t#define CONF_PLATFORM_STRING \"win64\"\n#elif defined(WIN32) || defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__)\n\t#define CONF_FAMILY_WINDOWS 1\n\t#define CONF_FAMILY_STRING \"windows\"\n\t#define CONF_PLATFORM_WIN32 1\n\t#define CONF_PLATFORM_STRING \"win32\"\n#endif\n\n/* unix family */\n#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)\n\t#define CONF_FAMILY_UNIX 1\n\t#define CONF_FAMILY_STRING \"unix\"\n\t#define CONF_PLATFORM_FREEBSD 1\n\t#define CONF_PLATFORM_STRING \"freebsd\"\n#endif\n\n#if defined(__OpenBSD__)\n\t#define CONF_FAMILY_UNIX 1\n\t#define CONF_FAMILY_STRING \"unix\"\n\t#define CONF_PLATFORM_OPENBSD 1\n\t#define CONF_PLATFORM_STRING \"openbsd\"\n#endif\n\n#if defined(__LINUX__) || defined(__linux__)\n\t#define CONF_FAMILY_UNIX 1\n\t#define CONF_FAMILY_STRING \"unix\"\n\t#define CONF_PLATFORM_LINUX 1\n\t#define CONF_PLATFORM_STRING \"linux\"\n#endif\n\n#if defined(__GNU__) || defined(__gnu__)\n\t#define CONF_FAMILY_UNIX 1\n\t#define CONF_FAMILY_STRING \"unix\"\n\t#define CONF_PLATFORM_HURD 1\n\t#define CONF_PLATFORM_STRING \"gnu\"\n#endif\n\n#if defined(MACOSX) || defined(__APPLE__) || defined(__DARWIN__)\n\t#define CONF_FAMILY_UNIX 1\n\t#define CONF_FAMILY_STRING \"unix\"\n\t#define CONF_PLATFORM_MACOSX 1\n\t#define CONF_PLATFORM_STRING \"macosx\"\n#endif\n\n#if defined(__sun)\n\t#define CONF_FAMILY_UNIX 1\n\t#define CONF_FAMILY_STRING \"unix\"\n\t#define CONF_PLATFORM_SOLARIS 1\n\t#define CONF_PLATFORM_STRING \"solaris\"\n#endif\n\n/* beos family */\n#if defined(__BeOS) || defined(__BEOS__)\n\t#define CONF_FAMILY_BEOS 1\n\t#define CONF_FAMILY_STRING \"beos\"\n\t#define CONF_PLATFORM_BEOS 1\n\t#define CONF_PLATFORM_STRING \"beos\"\n#endif\n\n\n/* use gcc endianness definitions when available */\n#if defined(__GNUC__) && !defined(__APPLE__) && !defined(__MINGW32__) && !defined(__sun)\n\t#if defined(__FreeBSD__) || defined(__OpenBSD__)\n\t\t#include <sys/endian.h>\n\t#else\n\t\t#include <endian.h>\n\t#endif\n\n\t#if __BYTE_ORDER == __LITTLE_ENDIAN\n\t\t#define CONF_ARCH_ENDIAN_LITTLE 1\n\t#elif __BYTE_ORDER == __BIG_ENDIAN\n\t\t#define CONF_ARCH_ENDIAN_BIG 1\n\t#endif\n#endif\n\n\n/* architectures */\n#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(CONF_PLATFORM_WIN32)\n\t#define CONF_ARCH_IA32 1\n\t#define CONF_ARCH_STRING \"ia32\"\n\t#if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG)\n\t\t#define CONF_ARCH_ENDIAN_LITTLE 1\n\t#endif\n#endif\n\n#if defined(__ia64__) || defined(_M_IA64)\n\t#define CONF_ARCH_IA64 1\n\t#define CONF_ARCH_STRING \"ia64\"\n\t#if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG)\n\t\t#define CONF_ARCH_ENDIAN_LITTLE 1\n\t#endif\n#endif\n\n#if defined(__amd64__) || defined(__x86_64__) || defined(_M_X64)\n\t#define CONF_ARCH_AMD64 1\n\t#define CONF_ARCH_STRING \"amd64\"\n\t#if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG)\n\t\t#define CONF_ARCH_ENDIAN_LITTLE 1\n\t#endif\n#endif\n\n#if defined(__powerpc__) || defined(__ppc__)\n\t#define CONF_ARCH_PPC 1\n\t#define CONF_ARCH_STRING \"ppc\"\n\t#if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG)\n\t\t#define CONF_ARCH_ENDIAN_BIG 1\n\t#endif\n#endif\n\n#if defined(__sparc__)\n\t#define CONF_ARCH_SPARC 1\n\t#define CONF_ARCH_STRING \"sparc\"\n\t#if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG)\n\t\t#define CONF_ARCH_ENDIAN_BIG 1\n\t#endif\n#endif\n\n\n#ifndef CONF_FAMILY_STRING\n#define CONF_FAMILY_STRING \"unknown\"\n#endif\n\n#ifndef CONF_PLATFORM_STRING\n#define CONF_PLATFORM_STRING \"unknown\"\n#endif\n\n#ifndef CONF_ARCH_STRING\n#define CONF_ARCH_STRING \"unknown\"\n#endif\n\n#endif\n"
  },
  {
    "path": "src/base/math.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef BASE_MATH_H\n#define BASE_MATH_H\n\n#include <stdlib.h>\n\ntemplate <typename T>\ninline T clamp(T val, T min, T max)\n{\n\tif(val < min)\n\t\treturn min;\n\tif(val > max)\n\t\treturn max;\n\treturn val;\n}\n\ninline float sign(float f)\n{\n\treturn f<0.0f?-1.0f:1.0f;\n}\n\ninline int round(float f)\n{\n\tif(f > 0)\n\t\treturn (int)(f+0.5f);\n\treturn (int)(f-0.5f);\n}\n\ntemplate<typename T, typename TB>\ninline T mix(const T a, const T b, TB amount)\n{\n\treturn a + (b-a)*amount;\n}\n\ninline float frandom() { return rand()/(float)(RAND_MAX); }\n\n// float to fixed\ninline int f2fx(float v) { return (int)(v*(float)(1<<10)); }\ninline float fx2f(int v) { return v*(1.0f/(1<<10)); }\n\ninline int gcd(int a, int b)\n{\n\twhile(b != 0)\n\t{\n\t\tint c = a % b;\n\t\ta = b;\n\t\tb = c;\n\t}\n\treturn a;\n}\n\nclass fxp\n{\n\tint value;\npublic:\n\tvoid set(int v) { value = v; }\n\tint get() const { return value; }\n\tfxp &operator = (int v) { value = v<<10; return *this; }\n\tfxp &operator = (float v) { value = (int)(v*(float)(1<<10)); return *this; }\n\toperator float() const { return value/(float)(1<<10); }\n};\n\nconst float pi = 3.1415926535897932384626433f;\n\ntemplate <typename T> inline T min(T a, T b) { return a<b?a:b; }\ntemplate <typename T> inline T max(T a, T b) { return a>b?a:b; }\ntemplate <typename T> inline T absolute(T a) { return a<T(0)?-a:a; }\n\n#endif // BASE_MATH_H\n"
  },
  {
    "path": "src/base/system.c",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <string.h>\n#include <ctype.h>\n#include <time.h>\n\n#include \"system.h\"\n\n#if defined(CONF_FAMILY_UNIX)\n\t#include <sys/time.h>\n\t#include <unistd.h>\n\n\t/* unix net includes */\n\t#include <sys/stat.h>\n\t#include <sys/types.h>\n\t#include <sys/socket.h>\n\t#include <sys/ioctl.h>\n\t#include <errno.h>\n\t#include <netdb.h>\n\t#include <netinet/in.h>\n\t#include <fcntl.h>\n\t#include <pthread.h>\n\t#include <arpa/inet.h>\n\n\t#include <dirent.h>\n\n\t#if defined(CONF_PLATFORM_MACOSX)\n\t\t#include <Carbon/Carbon.h>\n\t#endif\n\n#elif defined(CONF_FAMILY_WINDOWS)\n\t#define WIN32_LEAN_AND_MEAN\n\t#define _WIN32_WINNT 0x0501 /* required for mingw to get getaddrinfo to work */\n\t#include <windows.h>\n\t#include <winsock2.h>\n\t#include <ws2tcpip.h>\n\t#include <fcntl.h>\n\t#include <direct.h>\n\t#include <errno.h>\n#else\n\t#error NOT IMPLEMENTED\n#endif\n\n#if defined(CONF_PLATFORM_SOLARIS)\n\t#include <sys/filio.h>\n#endif\n\n#if defined(__cplusplus)\nextern \"C\" {\n#endif\n\nIOHANDLE io_stdin() { return (IOHANDLE)stdin; }\nIOHANDLE io_stdout() { return (IOHANDLE)stdout; }\nIOHANDLE io_stderr() { return (IOHANDLE)stderr; }\n\nstatic DBG_LOGGER loggers[16];\nstatic int num_loggers = 0;\n\nstatic NETSTATS network_stats = {0};\nstatic MEMSTATS memory_stats = {0};\n\nstatic NETSOCKET invalid_socket = {NETTYPE_INVALID, -1, -1};\n\nvoid dbg_logger(DBG_LOGGER logger)\n{\n\tloggers[num_loggers++] = logger;\n}\n\nvoid dbg_assert_imp(const char *filename, int line, int test, const char *msg)\n{\n\tif(!test)\n\t{\n\t\tdbg_msg(\"assert\", \"%s(%d): %s\", filename, line, msg);\n\t\tdbg_break();\n\t}\n}\n\nvoid dbg_break()\n{\n\t*((volatile unsigned*)0) = 0x0;\n}\n\nvoid dbg_msg(const char *sys, const char *fmt, ...)\n{\n\tva_list args;\n\tchar str[1024*4];\n\tchar *msg;\n\tint i, len;\n\n\tstr_format(str, sizeof(str), \"[%08x][%s]: \", (int)time(0), sys);\n\tlen = strlen(str);\n\tmsg = (char *)str + len;\n\n\tva_start(args, fmt);\n#if defined(CONF_FAMILY_WINDOWS)\n\t_vsnprintf(msg, sizeof(str)-len, fmt, args);\n#else\n\tvsnprintf(msg, sizeof(str)-len, fmt, args);\n#endif\n\tva_end(args);\n\n\tfor(i = 0; i < num_loggers; i++)\n\t\tloggers[i](str);\n}\n\nstatic void logger_stdout(const char *line)\n{\n\tprintf(\"%s\\n\", line);\n\tfflush(stdout);\n}\n\nstatic void logger_debugger(const char *line)\n{\n#if defined(CONF_FAMILY_WINDOWS)\n\tOutputDebugString(line);\n\tOutputDebugString(\"\\n\");\n#endif\n}\n\n\nstatic IOHANDLE logfile = 0;\nstatic void logger_file(const char *line)\n{\n\tio_write(logfile, line, strlen(line));\n\tio_write_newline(logfile);\n\tio_flush(logfile);\n}\n\nvoid dbg_logger_stdout() { dbg_logger(logger_stdout); }\nvoid dbg_logger_debugger() { dbg_logger(logger_debugger); }\nvoid dbg_logger_file(const char *filename)\n{\n\tlogfile = io_open(filename, IOFLAG_WRITE);\n\tif(logfile)\n\t\tdbg_logger(logger_file);\n\telse\n\t\tdbg_msg(\"dbg/logger\", \"failed to open '%s' for logging\", filename);\n\n}\n/* */\n\ntypedef struct MEMHEADER\n{\n\tconst char *filename;\n\tint line;\n\tint size;\n\tstruct MEMHEADER *prev;\n\tstruct MEMHEADER *next;\n} MEMHEADER;\n\ntypedef struct MEMTAIL\n{\n\tint guard;\n} MEMTAIL;\n\nstatic struct MEMHEADER *first = 0;\nstatic const int MEM_GUARD_VAL = 0xbaadc0de;\n\nvoid *mem_alloc_debug(const char *filename, int line, unsigned size, unsigned alignment)\n{\n\t/* TODO: fix alignment */\n\t/* TODO: add debugging */\n\tMEMTAIL *tail;\n\tMEMHEADER *header = (struct MEMHEADER *)malloc(size+sizeof(MEMHEADER)+sizeof(MEMTAIL));\n\tdbg_assert(header != 0, \"mem_alloc failure\");\n\tif(!header)\n\t\treturn NULL;\n\ttail = (struct MEMTAIL *)(((char*)(header+1))+size);\n\theader->size = size;\n\theader->filename = filename;\n\theader->line = line;\n\n\tmemory_stats.allocated += header->size;\n\tmemory_stats.total_allocations++;\n\tmemory_stats.active_allocations++;\n\n\ttail->guard = MEM_GUARD_VAL;\n\n\theader->prev = (MEMHEADER *)0;\n\theader->next = first;\n\tif(first)\n\t\tfirst->prev = header;\n\tfirst = header;\n\n\t/*dbg_msg(\"mem\", \"++ %p\", header+1); */\n\treturn header+1;\n}\n\nvoid mem_free(void *p)\n{\n\tif(p)\n\t{\n\t\tMEMHEADER *header = (MEMHEADER *)p - 1;\n\t\tMEMTAIL *tail = (MEMTAIL *)(((char*)(header+1))+header->size);\n\n\t\tif(tail->guard != MEM_GUARD_VAL)\n\t\t\tdbg_msg(\"mem\", \"!! %p\", p);\n\t\t/* dbg_msg(\"mem\", \"-- %p\", p); */\n\t\tmemory_stats.allocated -= header->size;\n\t\tmemory_stats.active_allocations--;\n\n\t\tif(header->prev)\n\t\t\theader->prev->next = header->next;\n\t\telse\n\t\t\tfirst = header->next;\n\t\tif(header->next)\n\t\t\theader->next->prev = header->prev;\n\n\t\tfree(header);\n\t}\n}\n\nvoid mem_debug_dump(IOHANDLE file)\n{\n\tchar buf[1024];\n\tMEMHEADER *header = first;\n\tif(!file)\n\t\tfile = io_open(\"memory.txt\", IOFLAG_WRITE);\n\n\tif(file)\n\t{\n\t\twhile(header)\n\t\t{\n\t\t\tstr_format(buf, sizeof(buf), \"%s(%d): %d\", header->filename, header->line, header->size);\n\t\t\tio_write(file, buf, strlen(buf));\n\t\t\tio_write_newline(file);\n\t\t\theader = header->next;\n\t\t}\n\n\t\tio_close(file);\n\t}\n}\n\n\nvoid mem_copy(void *dest, const void *source, unsigned size)\n{\n\tmemcpy(dest, source, size);\n}\n\nvoid mem_move(void *dest, const void *source, unsigned size)\n{\n\tmemmove(dest, source, size);\n}\n\nvoid mem_zero(void *block,unsigned size)\n{\n\tmemset(block, 0, size);\n}\n\nint mem_check_imp()\n{\n\tMEMHEADER *header = first;\n\twhile(header)\n\t{\n\t\tMEMTAIL *tail = (MEMTAIL *)(((char*)(header+1))+header->size);\n\t\tif(tail->guard != MEM_GUARD_VAL)\n\t\t{\n\t\t\tdbg_msg(\"mem\", \"Memory check failed at %s(%d): %d\", header->filename, header->line, header->size);\n\t\t\treturn 0;\n\t\t}\n\t\theader = header->next;\n\t}\n\n\treturn 1;\n}\n\nIOHANDLE io_open(const char *filename, int flags)\n{\n\tif(flags == IOFLAG_READ)\n\t{\n\t#if defined(CONF_FAMILY_WINDOWS)\n\t\t// check for filename case sensitive\n\t\tWIN32_FIND_DATA finddata;\n\t\tHANDLE handle;\n\t\tint length;\n\n\t\tlength = str_length(filename);\n\t\tif(!filename || !length || filename[length-1] == '\\\\')\n\t\t\treturn 0x0;\n\t\thandle = FindFirstFile(filename, &finddata);\n\t\tif(handle == INVALID_HANDLE_VALUE)\n\t\t\treturn 0x0;\n\t\telse if(str_comp(filename+length-str_length(finddata.cFileName), finddata.cFileName) != 0)\n\t\t{\n\t\t\tFindClose(handle);\n\t\t\treturn 0x0;\n\t\t}\n\t\tFindClose(handle);\n\t#endif\n\t\treturn (IOHANDLE)fopen(filename, \"rb\");\n\t}\n\tif(flags == IOFLAG_WRITE)\n\t\treturn (IOHANDLE)fopen(filename, \"wb\");\n\treturn 0x0;\n}\n\nunsigned io_read(IOHANDLE io, void *buffer, unsigned size)\n{\n\treturn fread(buffer, 1, size, (FILE*)io);\n}\n\nunsigned io_skip(IOHANDLE io, int size)\n{\n\tfseek((FILE*)io, size, SEEK_CUR);\n\treturn size;\n}\n\nint io_seek(IOHANDLE io, int offset, int origin)\n{\n\tint real_origin;\n\n\tswitch(origin)\n\t{\n\tcase IOSEEK_START:\n\t\treal_origin = SEEK_SET;\n\t\tbreak;\n\tcase IOSEEK_CUR:\n\t\treal_origin = SEEK_CUR;\n\t\tbreak;\n\tcase IOSEEK_END:\n\t\treal_origin = SEEK_END;\n\t\tbreak;\n\tdefault:\n\t\treturn -1;\n\t}\n\n\treturn fseek((FILE*)io, offset, real_origin);\n}\n\nlong int io_tell(IOHANDLE io)\n{\n\treturn ftell((FILE*)io);\n}\n\nlong int io_length(IOHANDLE io)\n{\n\tlong int length;\n\tio_seek(io, 0, IOSEEK_END);\n\tlength = io_tell(io);\n\tio_seek(io, 0, IOSEEK_START);\n\treturn length;\n}\n\nunsigned io_write(IOHANDLE io, const void *buffer, unsigned size)\n{\n\treturn fwrite(buffer, 1, size, (FILE*)io);\n}\n\nunsigned io_write_newline(IOHANDLE io)\n{\n#if defined(CONF_FAMILY_WINDOWS)\n\treturn fwrite(\"\\r\\n\", 1, 2, (FILE*)io);\n#else\n\treturn fwrite(\"\\n\", 1, 1, (FILE*)io);\n#endif\n}\n\nint io_close(IOHANDLE io)\n{\n\tfclose((FILE*)io);\n\treturn 1;\n}\n\nint io_flush(IOHANDLE io)\n{\n\tfflush((FILE*)io);\n\treturn 0;\n}\n\nvoid *thread_create(void (*threadfunc)(void *), void *u)\n{\n#if defined(CONF_FAMILY_UNIX)\n\tpthread_t id;\n\tpthread_create(&id, NULL, (void *(*)(void*))threadfunc, u);\n\treturn (void*)id;\n#elif defined(CONF_FAMILY_WINDOWS)\n\treturn CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadfunc, u, 0, NULL);\n#else\n\t#error not implemented\n#endif\n}\n\nvoid thread_wait(void *thread)\n{\n#if defined(CONF_FAMILY_UNIX)\n\tpthread_join((pthread_t)thread, NULL);\n#elif defined(CONF_FAMILY_WINDOWS)\n\tWaitForSingleObject((HANDLE)thread, INFINITE);\n#else\n\t#error not implemented\n#endif\n}\n\nvoid thread_destroy(void *thread)\n{\n#if defined(CONF_FAMILY_UNIX)\n\tvoid *r = 0;\n\tpthread_join((pthread_t)thread, &r);\n#else\n\t/*#error not implemented*/\n#endif\n}\n\nvoid thread_yield()\n{\n#if defined(CONF_FAMILY_UNIX)\n\tsched_yield();\n#elif defined(CONF_FAMILY_WINDOWS)\n\tSleep(0);\n#else\n\t#error not implemented\n#endif\n}\n\nvoid thread_sleep(int milliseconds)\n{\n#if defined(CONF_FAMILY_UNIX)\n\tusleep(milliseconds*1000);\n#elif defined(CONF_FAMILY_WINDOWS)\n\tSleep(milliseconds);\n#else\n\t#error not implemented\n#endif\n}\n\nvoid thread_detach(void *thread)\n{\n#if defined(CONF_FAMILY_UNIX)\n\tpthread_detach((pthread_t)(thread));\n#elif defined(CONF_FAMILY_WINDOWS)\n\tCloseHandle(thread);\n#else\n\t#error not implemented\n#endif\n}\n\n\n\n\n#if defined(CONF_FAMILY_UNIX)\ntypedef pthread_mutex_t LOCKINTERNAL;\n#elif defined(CONF_FAMILY_WINDOWS)\ntypedef CRITICAL_SECTION LOCKINTERNAL;\n#else\n\t#error not implemented on this platform\n#endif\n\nLOCK lock_create()\n{\n\tLOCKINTERNAL *lock = (LOCKINTERNAL*)mem_alloc(sizeof(LOCKINTERNAL), 4);\n\n#if defined(CONF_FAMILY_UNIX)\n\tpthread_mutex_init(lock, 0x0);\n#elif defined(CONF_FAMILY_WINDOWS)\n\tInitializeCriticalSection((LPCRITICAL_SECTION)lock);\n#else\n\t#error not implemented on this platform\n#endif\n\treturn (LOCK)lock;\n}\n\nvoid lock_destroy(LOCK lock)\n{\n#if defined(CONF_FAMILY_UNIX)\n\tpthread_mutex_destroy((LOCKINTERNAL *)lock);\n#elif defined(CONF_FAMILY_WINDOWS)\n\tDeleteCriticalSection((LPCRITICAL_SECTION)lock);\n#else\n\t#error not implemented on this platform\n#endif\n\tmem_free(lock);\n}\n\nint lock_try(LOCK lock)\n{\n#if defined(CONF_FAMILY_UNIX)\n\treturn pthread_mutex_trylock((LOCKINTERNAL *)lock);\n#elif defined(CONF_FAMILY_WINDOWS)\n\treturn !TryEnterCriticalSection((LPCRITICAL_SECTION)lock);\n#else\n\t#error not implemented on this platform\n#endif\n}\n\nvoid lock_wait(LOCK lock)\n{\n#if defined(CONF_FAMILY_UNIX)\n\tpthread_mutex_lock((LOCKINTERNAL *)lock);\n#elif defined(CONF_FAMILY_WINDOWS)\n\tEnterCriticalSection((LPCRITICAL_SECTION)lock);\n#else\n\t#error not implemented on this platform\n#endif\n}\n\nvoid lock_release(LOCK lock)\n{\n#if defined(CONF_FAMILY_UNIX)\n\tpthread_mutex_unlock((LOCKINTERNAL *)lock);\n#elif defined(CONF_FAMILY_WINDOWS)\n\tLeaveCriticalSection((LPCRITICAL_SECTION)lock);\n#else\n\t#error not implemented on this platform\n#endif\n}\n\n#if !defined(CONF_PLATFORM_MACOSX)\n\t#if defined(CONF_FAMILY_UNIX)\n\tvoid semaphore_init(SEMAPHORE *sem) { sem_init(sem, 0, 0); }\n\tvoid semaphore_wait(SEMAPHORE *sem) { sem_wait(sem); }\n\tvoid semaphore_signal(SEMAPHORE *sem) { sem_post(sem); }\n\tvoid semaphore_destroy(SEMAPHORE *sem) { sem_destroy(sem); }\n\t#elif defined(CONF_FAMILY_WINDOWS)\n\tvoid semaphore_init(SEMAPHORE *sem) { *sem = CreateSemaphore(0, 0, 10000, 0); }\n\tvoid semaphore_wait(SEMAPHORE *sem) { WaitForSingleObject((HANDLE)*sem, INFINITE); }\n\tvoid semaphore_signal(SEMAPHORE *sem) { ReleaseSemaphore((HANDLE)*sem, 1, NULL); }\n\tvoid semaphore_destroy(SEMAPHORE *sem) { CloseHandle((HANDLE)*sem); }\n\t#else\n\t\t#error not implemented on this platform\n\t#endif\n#endif\n\n\n/* -----  time ----- */\nint64 time_get()\n{\n#if defined(CONF_FAMILY_UNIX)\n\tstruct timeval val;\n\tgettimeofday(&val, NULL);\n\treturn (int64)val.tv_sec*(int64)1000000+(int64)val.tv_usec;\n#elif defined(CONF_FAMILY_WINDOWS)\n\tstatic int64 last = 0;\n\tint64 t;\n\tQueryPerformanceCounter((PLARGE_INTEGER)&t);\n\tif(t<last) /* for some reason, QPC can return values in the past */\n\t\treturn last;\n\tlast = t;\n\treturn t;\n#else\n\t#error not implemented\n#endif\n}\n\nint64 time_freq()\n{\n#if defined(CONF_FAMILY_UNIX)\n\treturn 1000000;\n#elif defined(CONF_FAMILY_WINDOWS)\n\tint64 t;\n\tQueryPerformanceFrequency((PLARGE_INTEGER)&t);\n\treturn t;\n#else\n\t#error not implemented\n#endif\n}\n\n/* -----  network ----- */\nstatic void netaddr_to_sockaddr_in(const NETADDR *src, struct sockaddr_in *dest)\n{\n\tmem_zero(dest, sizeof(struct sockaddr_in));\n\tif(src->type != NETTYPE_IPV4)\n\t{\n\t\tdbg_msg(\"system\", \"couldn't convert NETADDR of type %d to ipv4\", src->type);\n\t\treturn;\n\t}\n\n\tdest->sin_family = AF_INET;\n\tdest->sin_port = htons(src->port);\n\tmem_copy(&dest->sin_addr.s_addr, src->ip, 4);\n}\n\nstatic void netaddr_to_sockaddr_in6(const NETADDR *src, struct sockaddr_in6 *dest)\n{\n\tmem_zero(dest, sizeof(struct sockaddr_in6));\n\tif(src->type != NETTYPE_IPV6)\n\t{\n\t\tdbg_msg(\"system\", \"couldn't not convert NETADDR of type %d to ipv6\", src->type);\n\t\treturn;\n\t}\n\n\tdest->sin6_family = AF_INET6;\n\tdest->sin6_port = htons(src->port);\n\tmem_copy(&dest->sin6_addr.s6_addr, src->ip, 16);\n}\n\nstatic void sockaddr_to_netaddr(const struct sockaddr *src, NETADDR *dst)\n{\n\tif(src->sa_family == AF_INET)\n\t{\n\t\tmem_zero(dst, sizeof(NETADDR));\n\t\tdst->type = NETTYPE_IPV4;\n\t\tdst->port = htons(((struct sockaddr_in*)src)->sin_port);\n\t\tmem_copy(dst->ip, &((struct sockaddr_in*)src)->sin_addr.s_addr, 4);\n\t}\n\telse if(src->sa_family == AF_INET6)\n\t{\n\t\tmem_zero(dst, sizeof(NETADDR));\n\t\tdst->type = NETTYPE_IPV6;\n\t\tdst->port = htons(((struct sockaddr_in6*)src)->sin6_port);\n\t\tmem_copy(dst->ip, &((struct sockaddr_in6*)src)->sin6_addr.s6_addr, 16);\n\t}\n\telse\n\t{\n\t\tmem_zero(dst, sizeof(struct sockaddr));\n\t\tdbg_msg(\"system\", \"couldn't convert sockaddr of family %d\", src->sa_family);\n\t}\n}\n\nint net_addr_comp(const NETADDR *a, const NETADDR *b)\n{\n\treturn mem_comp(a, b, sizeof(NETADDR));\n}\n\nvoid net_addr_str(const NETADDR *addr, char *string, int max_length, int add_port)\n{\n\tif(addr->type == NETTYPE_IPV4)\n\t{\n\t\tif(add_port != 0)\n\t\t\tstr_format(string, max_length, \"%d.%d.%d.%d:%d\", addr->ip[0], addr->ip[1], addr->ip[2], addr->ip[3], addr->port);\n\t\telse\n\t\t\tstr_format(string, max_length, \"%d.%d.%d.%d\", addr->ip[0], addr->ip[1], addr->ip[2], addr->ip[3]);\n\t}\n\telse if(addr->type == NETTYPE_IPV6)\n\t{\n\t\tif(add_port != 0)\n\t\t\tstr_format(string, max_length, \"[%x:%x:%x:%x:%x:%x:%x:%x]:%d\",\n\t\t\t\t(addr->ip[0]<<8)|addr->ip[1], (addr->ip[2]<<8)|addr->ip[3], (addr->ip[4]<<8)|addr->ip[5], (addr->ip[6]<<8)|addr->ip[7],\n\t\t\t\t(addr->ip[8]<<8)|addr->ip[9], (addr->ip[10]<<8)|addr->ip[11], (addr->ip[12]<<8)|addr->ip[13], (addr->ip[14]<<8)|addr->ip[15],\n\t\t\t\taddr->port);\n\t\telse\n\t\t\tstr_format(string, max_length, \"[%x:%x:%x:%x:%x:%x:%x:%x]\",\n\t\t\t\t(addr->ip[0]<<8)|addr->ip[1], (addr->ip[2]<<8)|addr->ip[3], (addr->ip[4]<<8)|addr->ip[5], (addr->ip[6]<<8)|addr->ip[7],\n\t\t\t\t(addr->ip[8]<<8)|addr->ip[9], (addr->ip[10]<<8)|addr->ip[11], (addr->ip[12]<<8)|addr->ip[13], (addr->ip[14]<<8)|addr->ip[15]);\n\t}\n\telse\n\t\tstr_format(string, max_length, \"unknown type %d\", addr->type);\n}\n\nstatic int priv_net_extract(const char *hostname, char *host, int max_host, int *port)\n{\n\tint i;\n\n\t*port = 0;\n\thost[0] = 0;\n\n\tif(hostname[0] == '[')\n\t{\n\t\t// ipv6 mode\n\t\tfor(i = 1; i < max_host && hostname[i] && hostname[i] != ']'; i++)\n\t\t\thost[i-1] = hostname[i];\n\t\thost[i-1] = 0;\n\t\tif(hostname[i] != ']') // malformatted\n\t\t\treturn -1;\n\n\t\ti++;\n\t\tif(hostname[i] == ':')\n\t\t\t*port = atol(hostname+i+1);\n\t}\n\telse\n\t{\n\t\t// generic mode (ipv4, hostname etc)\n\t\tfor(i = 0; i < max_host-1 && hostname[i] && hostname[i] != ':'; i++)\n\t\t\thost[i] = hostname[i];\n\t\thost[i] = 0;\n\n\t\tif(hostname[i] == ':')\n\t\t\t*port = atol(hostname+i+1);\n\t}\n\n\treturn 0;\n}\n\nint net_host_lookup(const char *hostname, NETADDR *addr, int types)\n{\n\tstruct addrinfo hints;\n\tstruct addrinfo *result;\n\tint e;\n\tchar host[256];\n\tint port = 0;\n\n\tif(priv_net_extract(hostname, host, sizeof(host), &port))\n\t\treturn -1;\n\t/*\n\tdbg_msg(\"host lookup\", \"host='%s' port=%d %d\", host, port, types);\n\t*/\n\n\tmem_zero(&hints, sizeof(hints));\n\n\thints.ai_family = AF_UNSPEC;\n\n\tif(types == NETTYPE_IPV4)\n\t\thints.ai_family = AF_INET;\n\telse if(types == NETTYPE_IPV6)\n\t\thints.ai_family = AF_INET6;\n\n\te = getaddrinfo(host, NULL, &hints, &result);\n\tif(e != 0 || !result)\n\t\treturn -1;\n\n\tsockaddr_to_netaddr(result->ai_addr, addr);\n\tfreeaddrinfo(result);\n\taddr->port = port;\n\treturn 0;\n}\n\nstatic int parse_int(int *out, const char **str)\n{\n\tint i = 0;\n\t*out = 0;\n\tif(**str < '0' || **str > '9')\n\t\treturn -1;\n\n\ti = **str - '0';\n\t(*str)++;\n\n\twhile(1)\n\t{\n\t\tif(**str < '0' || **str > '9')\n\t\t{\n\t\t\t*out = i;\n\t\t\treturn 0;\n\t\t}\n\n\t\ti = (i*10) + (**str - '0');\n\t\t(*str)++;\n\t}\n\n\treturn 0;\n}\n\nstatic int parse_char(char c, const char **str)\n{\n\tif(**str != c) return -1;\n\t(*str)++;\n\treturn 0;\n}\n\nstatic int parse_uint8(unsigned char *out, const char **str)\n{\n\tint i;\n\tif(parse_int(&i, str) != 0) return -1;\n\tif(i < 0 || i > 0xff) return -1;\n\t*out = i;\n\treturn 0;\n}\n\nstatic int parse_uint16(unsigned short *out, const char **str)\n{\n\tint i;\n\tif(parse_int(&i, str) != 0) return -1;\n\tif(i < 0 || i > 0xffff) return -1;\n\t*out = i;\n\treturn 0;\n}\n\nint net_addr_from_str(NETADDR *addr, const char *string)\n{\n\tconst char *str = string;\n\tmem_zero(addr, sizeof(NETADDR));\n\n\tif(str[0] == '[')\n\t{\n\t\t/* ipv6 */\n\t\tstruct sockaddr_in6 sa6;\n\t\tchar buf[128];\n\t\tint i;\n\t\tstr++;\n\t\tfor(i = 0; i < 127 && str[i] && str[i] != ']'; i++)\n\t\t\tbuf[i] = str[i];\n\t\tbuf[i] = 0;\n\t\tstr += i;\n#if defined(CONF_FAMILY_WINDOWS)\n\t\t{\n\t\t\tint size;\n\t\t\tsa6.sin6_family = AF_INET6;\n\t\t\tsize = (int)sizeof(sa6);\n\t\t\tif(WSAStringToAddress(buf, AF_INET6, NULL, (struct sockaddr *)&sa6, &size) != 0)\n\t\t\t\treturn -1;\n\t\t}\n#else\n\t\tif(inet_pton(AF_INET6, buf, &sa6) != 1)\n\t\t\treturn -1;\n#endif\n\t\tsockaddr_to_netaddr((struct sockaddr *)&sa6, addr);\n\n\t\tif(*str == ']')\n\t\t{\n\t\t\tstr++;\n\t\t\tif(*str == ':')\n\t\t\t{\n\t\t\t\tstr++;\n\t\t\t\tif(parse_uint16(&addr->port, &str))\n\t\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\treturn -1;\n\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\t/* ipv4 */\n\t\tif(parse_uint8(&addr->ip[0], &str)) return -1;\n\t\tif(parse_char('.', &str)) return -1;\n\t\tif(parse_uint8(&addr->ip[1], &str)) return -1;\n\t\tif(parse_char('.', &str)) return -1;\n\t\tif(parse_uint8(&addr->ip[2], &str)) return -1;\n\t\tif(parse_char('.', &str)) return -1;\n\t\tif(parse_uint8(&addr->ip[3], &str)) return -1;\n\t\tif(*str == ':')\n\t\t{\n\t\t\tstr++;\n\t\t\tif(parse_uint16(&addr->port, &str)) return -1;\n\t\t}\n\n\t\taddr->type = NETTYPE_IPV4;\n\t}\n\n\treturn 0;\n}\n\nstatic void priv_net_close_socket(int sock)\n{\n#if defined(CONF_FAMILY_WINDOWS)\n\tclosesocket(sock);\n#else\n\tclose(sock);\n#endif\n}\n\nstatic int priv_net_close_all_sockets(NETSOCKET sock)\n{\n\t/* close down ipv4 */\n\tif(sock.ipv4sock >= 0)\n\t{\n\t\tpriv_net_close_socket(sock.ipv4sock);\n\t\tsock.ipv4sock = -1;\n\t\tsock.type &= ~NETTYPE_IPV4;\n\t}\n\n\t/* close down ipv6 */\n\tif(sock.ipv6sock >= 0)\n\t{\n\t\tpriv_net_close_socket(sock.ipv6sock);\n\t\tsock.ipv6sock = -1;\n\t\tsock.type &= ~NETTYPE_IPV6;\n\t}\n\treturn 0;\n}\n\nstatic int priv_net_create_socket(int domain, int type, struct sockaddr *addr, int sockaddrlen)\n{\n\tint sock, e;\n\n\t/* create socket */\n\tsock = socket(domain, type, 0);\n\tif(sock < 0)\n\t{\n#if defined(CONF_FAMILY_WINDOWS)\n\t\tchar buf[128];\n\t\tint error = WSAGetLastError();\n\t\tif(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, 0, error, 0, buf, sizeof(buf), 0) == 0)\n\t\t\tbuf[0] = 0;\n\t\tdbg_msg(\"net\", \"failed to create socket with domain %d and type %d (%d '%s')\", domain, type, error, buf);\n#else\n\t\tdbg_msg(\"net\", \"failed to create socket with domain %d and type %d (%d '%s')\", domain, type, errno, strerror(errno));\n#endif\n\t\treturn -1;\n\t}\n\n\t/* set to IPv6 only if thats what we are creating */\n#if defined(IPV6_V6ONLY)\t/* windows sdk 6.1 and higher */\n\tif(domain == AF_INET6)\n\t{\n\t\tint ipv6only = 1;\n\t\tsetsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&ipv6only, sizeof(ipv6only));\n\t}\n#endif\n\n\t/* bind the socket */\n\te = bind(sock, addr, sockaddrlen);\n\tif(e != 0)\n\t{\n#if defined(CONF_FAMILY_WINDOWS)\n\t\tchar buf[128];\n\t\tint error = WSAGetLastError();\n\t\tif(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, 0, error, 0, buf, sizeof(buf), 0) == 0)\n\t\t\tbuf[0] = 0;\n\t\tdbg_msg(\"net\", \"failed to bind socket with domain %d and type %d (%d '%s')\", domain, type, error, buf);\n#else\n\t\tdbg_msg(\"net\", \"failed to bind socket with domain %d and type %d (%d '%s')\", domain, type, errno, strerror(errno));\n#endif\n\t\tpriv_net_close_socket(sock);\n\t\treturn -1;\n\t}\n\n\t/* return the newly created socket */\n\treturn sock;\n}\n\nNETSOCKET net_udp_create(NETADDR bindaddr)\n{\n\tNETSOCKET sock = invalid_socket;\n\tNETADDR tmpbindaddr = bindaddr;\n\tint broadcast = 1;\n\tint recvsize = 65536;\n\n\tif(bindaddr.type&NETTYPE_IPV4)\n\t{\n\t\tstruct sockaddr_in addr;\n\t\tint socket = -1;\n\n\t\t/* bind, we should check for error */\n\t\ttmpbindaddr.type = NETTYPE_IPV4;\n\t\tnetaddr_to_sockaddr_in(&tmpbindaddr, &addr);\n\t\tsocket = priv_net_create_socket(AF_INET, SOCK_DGRAM, (struct sockaddr *)&addr, sizeof(addr));\n\t\tif(socket >= 0)\n\t\t{\n\t\t\tsock.type |= NETTYPE_IPV4;\n\t\t\tsock.ipv4sock = socket;\n\n\t\t\t/* set broadcast */\n\t\t\tsetsockopt(socket, SOL_SOCKET, SO_BROADCAST, (const char*)&broadcast, sizeof(broadcast));\n\n\t\t\t/* set receive buffer size */\n\t\t\tsetsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char*)&recvsize, sizeof(recvsize));\n\t\t}\n\t}\n\n\tif(bindaddr.type&NETTYPE_IPV6)\n\t{\n\t\tstruct sockaddr_in6 addr;\n\t\tint socket = -1;\n\n\t\t/* bind, we should check for error */\n\t\ttmpbindaddr.type = NETTYPE_IPV6;\n\t\tnetaddr_to_sockaddr_in6(&tmpbindaddr, &addr);\n\t\tsocket = priv_net_create_socket(AF_INET6, SOCK_DGRAM, (struct sockaddr *)&addr, sizeof(addr));\n\t\tif(socket >= 0)\n\t\t{\n\t\t\tsock.type |= NETTYPE_IPV6;\n\t\t\tsock.ipv6sock = socket;\n\n\t\t\t/* set broadcast */\n\t\t\tsetsockopt(socket, SOL_SOCKET, SO_BROADCAST, (const char*)&broadcast, sizeof(broadcast));\n\n\t\t\t/* set receive buffer size */\n\t\t\tsetsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char*)&recvsize, sizeof(recvsize));\n\t\t}\n\t}\n\n\t/* set non-blocking */\n\tnet_set_non_blocking(sock);\n\n\t/* return */\n\treturn sock;\n}\n\nint net_udp_send(NETSOCKET sock, const NETADDR *addr, const void *data, int size)\n{\n\tint d = -1;\n\n\tif(addr->type&NETTYPE_IPV4)\n\t{\n\t\tif(sock.ipv4sock >= 0)\n\t\t{\n\t\t\tstruct sockaddr_in sa;\n\t\t\tif(addr->type&NETTYPE_LINK_BROADCAST)\n\t\t\t{\n\t\t\t\tmem_zero(&sa, sizeof(sa));\n\t\t\t\tsa.sin_port = htons(addr->port);\n\t\t\t\tsa.sin_family = AF_INET;\n\t\t\t\tsa.sin_addr.s_addr = INADDR_BROADCAST;\n\t\t\t}\n\t\t\telse\n\t\t\t\tnetaddr_to_sockaddr_in(addr, &sa);\n\n\t\t\td = sendto((int)sock.ipv4sock, (const char*)data, size, 0, (struct sockaddr *)&sa, sizeof(sa));\n\t\t}\n\t\telse\n\t\t\tdbg_msg(\"net\", \"can't sent ipv4 traffic to this socket\");\n\t}\n\n\tif(addr->type&NETTYPE_IPV6)\n\t{\n\t\tif(sock.ipv6sock >= 0)\n\t\t{\n\t\t\tstruct sockaddr_in6 sa;\n\t\t\tif(addr->type&NETTYPE_LINK_BROADCAST)\n\t\t\t{\n\t\t\t\tmem_zero(&sa, sizeof(sa));\n\t\t\t\tsa.sin6_port = htons(addr->port);\n\t\t\t\tsa.sin6_family = AF_INET6;\n\t\t\t\tsa.sin6_addr.s6_addr[0] = 0xff; /* multicast */\n\t\t\t\tsa.sin6_addr.s6_addr[1] = 0x02; /* link local scope */\n\t\t\t\tsa.sin6_addr.s6_addr[15] = 1; /* all nodes */\n\t\t\t}\n\t\t\telse\n\t\t\t\tnetaddr_to_sockaddr_in6(addr, &sa);\n\n\t\t\td = sendto((int)sock.ipv6sock, (const char*)data, size, 0, (struct sockaddr *)&sa, sizeof(sa));\n\t\t}\n\t\telse\n\t\t\tdbg_msg(\"net\", \"can't sent ipv6 traffic to this socket\");\n\t}\n\t/*\n\telse\n\t\tdbg_msg(\"net\", \"can't sent to network of type %d\", addr->type);\n\t\t*/\n\n\t/*if(d < 0)\n\t{\n\t\tchar addrstr[256];\n\t\tnet_addr_str(addr, addrstr, sizeof(addrstr));\n\n\t\tdbg_msg(\"net\", \"sendto error (%d '%s')\", errno, strerror(errno));\n\t\tdbg_msg(\"net\", \"\\tsock = %d %x\", sock, sock);\n\t\tdbg_msg(\"net\", \"\\tsize = %d %x\", size, size);\n\t\tdbg_msg(\"net\", \"\\taddr = %s\", addrstr);\n\n\t}*/\n\tnetwork_stats.sent_bytes += size;\n\tnetwork_stats.sent_packets++;\n\treturn d;\n}\n\nint net_udp_recv(NETSOCKET sock, NETADDR *addr, void *data, int maxsize)\n{\n\tchar sockaddrbuf[128];\n\tsocklen_t fromlen;// = sizeof(sockaddrbuf);\n\tint bytes = 0;\n\n\tif(bytes == 0 && sock.ipv4sock >= 0)\n\t{\n\t\tfromlen = sizeof(struct sockaddr_in);\n\t\tbytes = recvfrom(sock.ipv4sock, (char*)data, maxsize, 0, (struct sockaddr *)&sockaddrbuf, &fromlen);\n\t}\n\n\tif(bytes <= 0 && sock.ipv6sock >= 0)\n\t{\n\t\tfromlen = sizeof(struct sockaddr_in6);\n\t\tbytes = recvfrom(sock.ipv6sock, (char*)data, maxsize, 0, (struct sockaddr *)&sockaddrbuf, &fromlen);\n\t}\n\n\tif(bytes > 0)\n\t{\n\t\tsockaddr_to_netaddr((struct sockaddr *)&sockaddrbuf, addr);\n\t\tnetwork_stats.recv_bytes += bytes;\n\t\tnetwork_stats.recv_packets++;\n\t\treturn bytes;\n\t}\n\telse if(bytes == 0)\n\t\treturn 0;\n\treturn -1; /* error */\n}\n\nint net_udp_close(NETSOCKET sock)\n{\n\treturn priv_net_close_all_sockets(sock);\n}\n\nNETSOCKET net_tcp_create(NETADDR bindaddr)\n{\n\tNETSOCKET sock = invalid_socket;\n\tNETADDR tmpbindaddr = bindaddr;\n\n\tif(bindaddr.type&NETTYPE_IPV4)\n\t{\n\t\tstruct sockaddr_in addr;\n\t\tint socket = -1;\n\n\t\t/* bind, we should check for error */\n\t\ttmpbindaddr.type = NETTYPE_IPV4;\n\t\tnetaddr_to_sockaddr_in(&tmpbindaddr, &addr);\n\t\tsocket = priv_net_create_socket(AF_INET, SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr));\n\t\tif(socket >= 0)\n\t\t{\n\t\t\tsock.type |= NETTYPE_IPV4;\n\t\t\tsock.ipv4sock = socket;\n\t\t}\n\t}\n\n\tif(bindaddr.type&NETTYPE_IPV6)\n\t{\n\t\tstruct sockaddr_in6 addr;\n\t\tint socket = -1;\n\n\t\t/* bind, we should check for error */\n\t\ttmpbindaddr.type = NETTYPE_IPV6;\n\t\tnetaddr_to_sockaddr_in6(&tmpbindaddr, &addr);\n\t\tsocket = priv_net_create_socket(AF_INET6, SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr));\n\t\tif(socket >= 0)\n\t\t{\n\t\t\tsock.type |= NETTYPE_IPV6;\n\t\t\tsock.ipv6sock = socket;\n\t\t}\n\t}\n\n\t/* return */\n\treturn sock;\n}\n\nint net_set_non_blocking(NETSOCKET sock)\n{\n\tunsigned long mode = 1;\n\tif(sock.ipv4sock >= 0)\n\t{\n#if defined(CONF_FAMILY_WINDOWS)\n\t\tioctlsocket(sock.ipv4sock, FIONBIO, (unsigned long *)&mode);\n#else\n\t\tioctl(sock.ipv4sock, FIONBIO, (unsigned long *)&mode);\n#endif\n\t}\n\n\tif(sock.ipv6sock >= 0)\n\t{\n#if defined(CONF_FAMILY_WINDOWS)\n\t\tioctlsocket(sock.ipv6sock, FIONBIO, (unsigned long *)&mode);\n#else\n\t\tioctl(sock.ipv6sock, FIONBIO, (unsigned long *)&mode);\n#endif\n\t}\n\n\treturn 0;\n}\n\nint net_set_blocking(NETSOCKET sock)\n{\n\tunsigned long mode = 0;\n\tif(sock.ipv4sock >= 0)\n\t{\n#if defined(CONF_FAMILY_WINDOWS)\n\t\tioctlsocket(sock.ipv4sock, FIONBIO, (unsigned long *)&mode);\n#else\n\t\tioctl(sock.ipv4sock, FIONBIO, (unsigned long *)&mode);\n#endif\n\t}\n\n\tif(sock.ipv6sock >= 0)\n\t{\n#if defined(CONF_FAMILY_WINDOWS)\n\t\tioctlsocket(sock.ipv6sock, FIONBIO, (unsigned long *)&mode);\n#else\n\t\tioctl(sock.ipv6sock, FIONBIO, (unsigned long *)&mode);\n#endif\n\t}\n\n\treturn 0;\n}\n\nint net_tcp_listen(NETSOCKET sock, int backlog)\n{\n\tint err = -1;\n\tif(sock.ipv4sock >= 0)\n\t\terr = listen(sock.ipv4sock, backlog);\n\tif(sock.ipv6sock >= 0)\n\t\terr = listen(sock.ipv6sock, backlog);\n\treturn err;\n}\n\nint net_tcp_accept(NETSOCKET sock, NETSOCKET *new_sock, NETADDR *a)\n{\n\tint s;\n\tsocklen_t sockaddr_len;\n\n\t*new_sock = invalid_socket;\n\n\tif(sock.ipv4sock >= 0)\n\t{\n\t\tstruct sockaddr_in addr;\n\t\tsockaddr_len = sizeof(addr);\n\n\t\ts = accept(sock.ipv4sock, (struct sockaddr *)&addr, &sockaddr_len);\n\n\t\tif (s != -1)\n\t\t{\n\t\t\tsockaddr_to_netaddr((const struct sockaddr *)&addr, a);\n\t\t\tnew_sock->type = NETTYPE_IPV4;\n\t\t\tnew_sock->ipv4sock = s;\n\t\t\treturn s;\n\t\t}\n\t}\n\n\tif(sock.ipv6sock >= 0)\n\t{\n\t\tstruct sockaddr_in6 addr;\n\t\tsockaddr_len = sizeof(addr);\n\n\t\ts = accept(sock.ipv6sock, (struct sockaddr *)&addr, &sockaddr_len);\n\n\t\tif (s != -1)\n\t\t{\n\t\t\tsockaddr_to_netaddr((const struct sockaddr *)&addr, a);\n\t\t\tnew_sock->type = NETTYPE_IPV6;\n\t\t\tnew_sock->ipv6sock = s;\n\t\t\treturn s;\n\t\t}\n\t}\n\n\treturn -1;\n}\n\nint net_tcp_connect(NETSOCKET sock, const NETADDR *a)\n{\n\tif(a->type&NETTYPE_IPV4)\n\t{\n\t\tstruct sockaddr_in addr;\n\t\tnetaddr_to_sockaddr_in(a, &addr);\n\t\treturn connect(sock.ipv4sock, (struct sockaddr *)&addr, sizeof(addr));\n\t}\n\n\tif(a->type&NETTYPE_IPV6)\n\t{\n\t\tstruct sockaddr_in6 addr;\n\t\tnetaddr_to_sockaddr_in6(a, &addr);\n\t\treturn connect(sock.ipv6sock, (struct sockaddr *)&addr, sizeof(addr));\n\t}\n\n\treturn -1;\n}\n\nint net_tcp_connect_non_blocking(NETSOCKET sock, NETADDR bindaddr)\n{\n\tint res = 0;\n\n\tnet_set_non_blocking(sock);\n\tres = net_tcp_connect(sock, &bindaddr);\n\tnet_set_blocking(sock);\n\n\treturn res;\n}\n\nint net_tcp_send(NETSOCKET sock, const void *data, int size)\n{\n\tint bytes = -1;\n\n\tif(sock.ipv4sock >= 0)\n\t\tbytes = send((int)sock.ipv4sock, (const char*)data, size, 0);\n\tif(sock.ipv6sock >= 0)\n\t\tbytes = send((int)sock.ipv6sock, (const char*)data, size, 0);\n\n\treturn bytes;\n}\n\nint net_tcp_recv(NETSOCKET sock, void *data, int maxsize)\n{\n\tint bytes = -1;\n\n\tif(sock.ipv4sock >= 0)\n\t\tbytes = recv((int)sock.ipv4sock, (char*)data, maxsize, 0);\n\tif(sock.ipv6sock >= 0)\n\t\tbytes = recv((int)sock.ipv6sock, (char*)data, maxsize, 0);\n\n\treturn bytes;\n}\n\nint net_tcp_close(NETSOCKET sock)\n{\n\treturn priv_net_close_all_sockets(sock);\n}\n\nint net_errno()\n{\n#if defined(CONF_FAMILY_WINDOWS)\n\treturn WSAGetLastError();\n#else\n\treturn errno;\n#endif\n}\n\nint net_would_block()\n{\n#if defined(CONF_FAMILY_WINDOWS)\n\treturn net_errno() == WSAEWOULDBLOCK;\n#else\n\treturn net_errno() == EWOULDBLOCK;\n#endif\n}\n\nint net_init()\n{\n#if defined(CONF_FAMILY_WINDOWS)\n\tWSADATA wsaData;\n\tint err = WSAStartup(MAKEWORD(1, 1), &wsaData);\n\tdbg_assert(err == 0, \"network initialization failed.\");\n\treturn err==0?0:1;\n#endif\n\n\treturn 0;\n}\n\nint fs_listdir(const char *dir, FS_LISTDIR_CALLBACK cb, int type, void *user)\n{\n#if defined(CONF_FAMILY_WINDOWS)\n\tWIN32_FIND_DATA finddata;\n\tHANDLE handle;\n\tchar buffer[1024*2];\n\tint length;\n\tstr_format(buffer, sizeof(buffer), \"%s/*\", dir);\n\n\thandle = FindFirstFileA(buffer, &finddata);\n\n\tif (handle == INVALID_HANDLE_VALUE)\n\t\treturn 0;\n\n\tstr_format(buffer, sizeof(buffer), \"%s/\", dir);\n\tlength = str_length(buffer);\n\n\t/* add all the entries */\n\tdo\n\t{\n\t\tstr_copy(buffer+length, finddata.cFileName, (int)sizeof(buffer)-length);\n\t\tif(cb(finddata.cFileName, fs_is_dir(buffer), type, user))\n\t\t\tbreak;\n\t}\n\twhile (FindNextFileA(handle, &finddata));\n\n\tFindClose(handle);\n\treturn 0;\n#else\n\tstruct dirent *entry;\n\tchar buffer[1024*2];\n\tint length;\n\tDIR *d = opendir(dir);\n\n\tif(!d)\n\t\treturn 0;\n\n\tstr_format(buffer, sizeof(buffer), \"%s/\", dir);\n\tlength = str_length(buffer);\n\n\twhile((entry = readdir(d)) != NULL)\n\t{\n\t\tstr_copy(buffer+length, entry->d_name, (int)sizeof(buffer)-length);\n\t\tif(cb(entry->d_name, fs_is_dir(buffer), type, user))\n\t\t\tbreak;\n\t}\n\n\t/* close the directory and return */\n\tclosedir(d);\n\treturn 0;\n#endif\n}\n\nint fs_storage_path(const char *appname, char *path, int max)\n{\n#if defined(CONF_FAMILY_WINDOWS)\n\tchar *home = getenv(\"APPDATA\");\n\tif(!home)\n\t\treturn -1;\n\t_snprintf(path, max, \"%s/%s\", home, appname);\n\treturn 0;\n#else\n\tchar *home = getenv(\"HOME\");\n#if !defined(CONF_PLATFORM_MACOSX)\n\tint i;\n#endif\n\tif(!home)\n\t\treturn -1;\n\n#if defined(CONF_PLATFORM_MACOSX)\n\tsnprintf(path, max, \"%s/Library/Application Support/%s\", home, appname);\n#else\n\tsnprintf(path, max, \"%s/.%s\", home, appname);\n\tfor(i = strlen(home)+2; path[i]; i++)\n\t\tpath[i] = tolower(path[i]);\n#endif\n\n\treturn 0;\n#endif\n}\n\nint fs_makedir(const char *path)\n{\n#if defined(CONF_FAMILY_WINDOWS)\n\tif(_mkdir(path) == 0)\n\t\t\treturn 0;\n\tif(errno == EEXIST)\n\t\treturn 0;\n\treturn -1;\n#else\n\tif(mkdir(path, 0755) == 0)\n\t\treturn 0;\n\tif(errno == EEXIST)\n\t\treturn 0;\n\treturn -1;\n#endif\n}\n\nint fs_is_dir(const char *path)\n{\n#if defined(CONF_FAMILY_WINDOWS)\n\t/* TODO: do this smarter */\n\tWIN32_FIND_DATA finddata;\n\tHANDLE handle;\n\tchar buffer[1024*2];\n\tstr_format(buffer, sizeof(buffer), \"%s/*\", path);\n\n\tif ((handle = FindFirstFileA(buffer, &finddata)) == INVALID_HANDLE_VALUE)\n\t\treturn 0;\n\n\tFindClose(handle);\n\treturn 1;\n#else\n\tstruct stat sb;\n\tif (stat(path, &sb) == -1)\n\t\treturn 0;\n\n\tif (S_ISDIR(sb.st_mode))\n\t\treturn 1;\n\telse\n\t\treturn 0;\n#endif\n}\n\nint fs_chdir(const char *path)\n{\n\tif(fs_is_dir(path))\n\t{\n\t\tif(chdir(path))\n\t\t\treturn 1;\n\t\telse\n\t\t\treturn 0;\n\t}\n\telse\n\t\treturn 1;\n}\n\nchar *fs_getcwd(char *buffer, int buffer_size)\n{\n\tif(buffer == 0)\n\t\treturn 0;\n#if defined(CONF_FAMILY_WINDOWS)\n\treturn _getcwd(buffer, buffer_size);\n#else\n\treturn getcwd(buffer, buffer_size);\n#endif\n}\n\nint fs_parent_dir(char *path)\n{\n\tchar *parent = 0;\n\tfor(; *path; ++path)\n\t{\n\t\tif(*path == '/' || *path == '\\\\')\n\t\t\tparent = path;\n\t}\n\n\tif(parent)\n\t{\n\t\t*parent = 0;\n\t\treturn 0;\n\t}\n\treturn 1;\n}\n\nint fs_remove(const char *filename)\n{\n\tif(remove(filename) != 0)\n\t\treturn 1;\n\treturn 0;\n}\n\nint fs_rename(const char *oldname, const char *newname)\n{\n\tif(rename(oldname, newname) != 0)\n\t\treturn 1;\n\treturn 0;\n}\n\nvoid swap_endian(void *data, unsigned elem_size, unsigned num)\n{\n\tchar *src = (char*) data;\n\tchar *dst = src + (elem_size - 1);\n\n\twhile(num)\n\t{\n\t\tunsigned n = elem_size>>1;\n\t\tchar tmp;\n\t\twhile(n)\n\t\t{\n\t\t\ttmp = *src;\n\t\t\t*src = *dst;\n\t\t\t*dst = tmp;\n\n\t\t\tsrc++;\n\t\t\tdst--;\n\t\t\tn--;\n\t\t}\n\n\t\tsrc = src + (elem_size>>1);\n\t\tdst = src + (elem_size - 1);\n\t\tnum--;\n\t}\n}\n\nint net_socket_read_wait(NETSOCKET sock, int time)\n{\n\tstruct timeval tv;\n\tfd_set readfds;\n\tint sockid;\n\n\ttv.tv_sec = 0;\n\ttv.tv_usec = 1000*time;\n\tsockid = 0;\n\n\tFD_ZERO(&readfds);\n\tif(sock.ipv4sock >= 0)\n\t{\n\t\tFD_SET(sock.ipv4sock, &readfds);\n\t\tsockid = sock.ipv4sock;\n\t}\n\tif(sock.ipv6sock >= 0)\n\t{\n\t\tFD_SET(sock.ipv6sock, &readfds);\n\t\tif(sock.ipv6sock > sockid)\n\t\t\tsockid = sock.ipv6sock;\n\t}\n\n\t/* don't care about writefds and exceptfds */\n\tselect(sockid+1, &readfds, NULL, NULL, &tv);\n\n\tif(sock.ipv4sock >= 0 && FD_ISSET(sock.ipv4sock, &readfds))\n\t\treturn 1;\n\n\tif(sock.ipv6sock >= 0 && FD_ISSET(sock.ipv6sock, &readfds))\n\t\treturn 1;\n\n\treturn 0;\n}\n\nint time_timestamp()\n{\n\treturn time(0);\n}\n\nvoid str_append(char *dst, const char *src, int dst_size)\n{\n\tint s = strlen(dst);\n\tint i = 0;\n\twhile(s < dst_size)\n\t{\n\t\tdst[s] = src[i];\n\t\tif(!src[i]) /* check for null termination */\n\t\t\tbreak;\n\t\ts++;\n\t\ti++;\n\t}\n\n\tdst[dst_size-1] = 0; /* assure null termination */\n}\n\nvoid str_copy(char *dst, const char *src, int dst_size)\n{\n\tstrncpy(dst, src, dst_size);\n\tdst[dst_size-1] = 0; /* assure null termination */\n}\n\nint str_length(const char *str)\n{\n\treturn (int)strlen(str);\n}\n\nvoid str_format(char *buffer, int buffer_size, const char *format, ...)\n{\n#if defined(CONF_FAMILY_WINDOWS)\n\tva_list ap;\n\tva_start(ap, format);\n\t_vsnprintf(buffer, buffer_size, format, ap);\n\tva_end(ap);\n#else\n\tva_list ap;\n\tva_start(ap, format);\n\tvsnprintf(buffer, buffer_size, format, ap);\n\tva_end(ap);\n#endif\n\n\tbuffer[buffer_size-1] = 0; /* assure null termination */\n}\n\n\n\n/* makes sure that the string only contains the characters between 32 and 127 */\nvoid str_sanitize_strong(char *str_in)\n{\n\tunsigned char *str = (unsigned char *)str_in;\n\twhile(*str)\n\t{\n\t\t*str &= 0x7f;\n\t\tif(*str < 32)\n\t\t\t*str = 32;\n\t\tstr++;\n\t}\n}\n\n/* makes sure that the string only contains the characters between 32 and 255 */\nvoid str_sanitize_cc(char *str_in)\n{\n\tunsigned char *str = (unsigned char *)str_in;\n\twhile(*str)\n\t{\n\t\tif(*str < 32)\n\t\t\t*str = ' ';\n\t\tstr++;\n\t}\n}\n\n/* makes sure that the string only contains the characters between 32 and 255 + \\r\\n\\t */\nvoid str_sanitize(char *str_in)\n{\n\tunsigned char *str = (unsigned char *)str_in;\n\twhile(*str)\n\t{\n\t\tif(*str < 32 && !(*str == '\\r') && !(*str == '\\n') && !(*str == '\\t'))\n\t\t\t*str = ' ';\n\t\tstr++;\n\t}\n}\n\nchar *str_skip_to_whitespace(char *str)\n{\n\twhile(*str && (*str != ' ' && *str != '\\t' && *str != '\\n'))\n\t\tstr++;\n\treturn str;\n}\n\nchar *str_skip_whitespaces(char *str)\n{\n\twhile(*str && (*str == ' ' || *str == '\\t' || *str == '\\n' || *str == '\\r'))\n\t\tstr++;\n\treturn str;\n}\n\n/* case */\nint str_comp_nocase(const char *a, const char *b)\n{\n#if defined(CONF_FAMILY_WINDOWS)\n\treturn _stricmp(a,b);\n#else\n\treturn strcasecmp(a,b);\n#endif\n}\n\nint str_comp_nocase_num(const char *a, const char *b, const int num)\n{\n#if defined(CONF_FAMILY_WINDOWS)\n\treturn _strnicmp(a, b, num);\n#else\n\treturn strncasecmp(a, b, num);\n#endif\n}\n\nint str_comp(const char *a, const char *b)\n{\n\treturn strcmp(a, b);\n}\n\nint str_comp_num(const char *a, const char *b, const int num)\n{\n\treturn strncmp(a, b, num);\n}\n\nint str_comp_filenames(const char *a, const char *b)\n{\n\tint result;\n\n\tfor(; *a && *b; ++a, ++b)\n\t{\n\t\tif(*a >= '0' && *a <= '9' && *b >= '0' && *b <= '9')\n\t\t{\n\t\t\tresult = 0;\n\t\t\tdo\n\t\t\t{\n\t\t\t\tif(!result)\n\t\t\t\t\tresult = *a - *b;\n\t\t\t\t++a; ++b;\n\t\t\t}\n\t\t\twhile(*a >= '0' && *a <= '9' && *b >= '0' && *b <= '9');\n\n\t\t\tif(*a >= '0' && *a <= '9')\n\t\t\t\treturn 1;\n\t\t\telse if(*b >= '0' && *b <= '9')\n\t\t\t\treturn -1;\n\t\t\telse if(result)\n\t\t\t\treturn result;\n\t\t}\n\n\t\tif(tolower(*a) != tolower(*b))\n\t\t\tbreak;\n\t}\n\treturn tolower(*a) - tolower(*b);\n}\n\nconst char *str_find_nocase(const char *haystack, const char *needle)\n{\n\twhile(*haystack) /* native implementation */\n\t{\n\t\tconst char *a = haystack;\n\t\tconst char *b = needle;\n\t\twhile(*a && *b && tolower(*a) == tolower(*b))\n\t\t{\n\t\t\ta++;\n\t\t\tb++;\n\t\t}\n\t\tif(!(*b))\n\t\t\treturn haystack;\n\t\thaystack++;\n\t}\n\n\treturn 0;\n}\n\n\nconst char *str_find(const char *haystack, const char *needle)\n{\n\twhile(*haystack) /* native implementation */\n\t{\n\t\tconst char *a = haystack;\n\t\tconst char *b = needle;\n\t\twhile(*a && *b && *a == *b)\n\t\t{\n\t\t\ta++;\n\t\t\tb++;\n\t\t}\n\t\tif(!(*b))\n\t\t\treturn haystack;\n\t\thaystack++;\n\t}\n\n\treturn 0;\n}\n\nvoid str_hex(char *dst, int dst_size, const void *data, int data_size)\n{\n\tstatic const char hex[] = \"0123456789ABCDEF\";\n\tint b;\n\n\tfor(b = 0; b < data_size && b < dst_size/4-4; b++)\n\t{\n\t\tdst[b*3] = hex[((const unsigned char *)data)[b]>>4];\n\t\tdst[b*3+1] = hex[((const unsigned char *)data)[b]&0xf];\n\t\tdst[b*3+2] = ' ';\n\t\tdst[b*3+3] = 0;\n\t}\n}\n\nvoid str_timestamp(char *buffer, int buffer_size)\n{\n\ttime_t time_data;\n\tstruct tm *time_info;\n\n\ttime(&time_data);\n\ttime_info = localtime(&time_data);\n\tstrftime(buffer, buffer_size, \"%Y-%m-%d_%H-%M-%S\", time_info);\n\tbuffer[buffer_size-1] = 0;\t/* assure null termination */\n}\n\nint mem_comp(const void *a, const void *b, int size)\n{\n\treturn memcmp(a,b,size);\n}\n\nconst MEMSTATS *mem_stats()\n{\n\treturn &memory_stats;\n}\n\nvoid net_stats(NETSTATS *stats_inout)\n{\n\t*stats_inout = network_stats;\n}\n\nvoid gui_messagebox(const char *title, const char *message)\n{\n#if defined(CONF_PLATFORM_MACOSX)\n\tDialogRef theItem;\n\tDialogItemIndex itemIndex;\n\n\t/* FIXME: really needed? can we rely on glfw? */\n\t/* HACK - get events without a bundle */\n\tProcessSerialNumber psn;\n\tGetCurrentProcess(&psn);\n\tTransformProcessType(&psn,kProcessTransformToForegroundApplication);\n\tSetFrontProcess(&psn);\n\t/* END HACK */\n\n\tCreateStandardAlert(kAlertStopAlert,\n\t\t\tCFStringCreateWithCString(NULL, title, kCFStringEncodingASCII),\n\t\t\tCFStringCreateWithCString(NULL, message, kCFStringEncodingASCII),\n\t\t\tNULL,\n\t\t\t&theItem);\n\n\tRunStandardAlert(theItem, NULL, &itemIndex);\n#elif defined(CONF_FAMILY_UNIX)\n\tstatic char cmd[1024];\n\tint err;\n\t/* use xmessage which is available on nearly every X11 system */\n\tsnprintf(cmd, sizeof(cmd), \"xmessage -center -title '%s' '%s'\",\n\t\ttitle,\n\t\tmessage);\n\n\terr = system(cmd);\n\tdbg_msg(\"gui/msgbox\", \"result = %i\", err);\n#elif defined(CONF_FAMILY_WINDOWS)\n\tMessageBox(NULL,\n\t\tmessage,\n\t\ttitle,\n\t\tMB_ICONEXCLAMATION | MB_OK);\n#else\n\t/* this is not critical */\n\t#warning not implemented\n#endif\n}\n\nint str_isspace(char c) { return c == ' ' || c == '\\n' || c == '\\t'; }\n\nchar str_uppercase(char c)\n{\n\tif(c >= 'a' && c <= 'z')\n\t\treturn 'A' + (c-'a');\n\treturn c;\n}\n\nint str_toint(const char *str) { return atoi(str); }\nfloat str_tofloat(const char *str) { return atof(str); }\n\n\n\nstatic int str_utf8_isstart(char c)\n{\n\tif((c&0xC0) == 0x80) /* 10xxxxxx */\n\t\treturn 0;\n\treturn 1;\n}\n\nint str_utf8_rewind(const char *str, int cursor)\n{\n\twhile(cursor)\n\t{\n\t\tcursor--;\n\t\tif(str_utf8_isstart(*(str + cursor)))\n\t\t\tbreak;\n\t}\n\treturn cursor;\n}\n\nint str_utf8_forward(const char *str, int cursor)\n{\n\tconst char *buf = str + cursor;\n\tif(!buf[0])\n\t\treturn cursor;\n\n\tif((*buf&0x80) == 0x0)  /* 0xxxxxxx */\n\t\treturn cursor+1;\n\telse if((*buf&0xE0) == 0xC0) /* 110xxxxx */\n\t{\n\t\tif(!buf[1]) return cursor+1;\n\t\treturn cursor+2;\n\t}\n\telse  if((*buf & 0xF0) == 0xE0)\t/* 1110xxxx */\n\t{\n\t\tif(!buf[1]) return cursor+1;\n\t\tif(!buf[2]) return cursor+2;\n\t\treturn cursor+3;\n\t}\n\telse if((*buf & 0xF8) == 0xF0)\t/* 11110xxx */\n\t{\n\t\tif(!buf[1]) return cursor+1;\n\t\tif(!buf[2]) return cursor+2;\n\t\tif(!buf[3]) return cursor+3;\n\t\treturn cursor+4;\n\t}\n\n\t/* invalid */\n\treturn cursor+1;\n}\n\nint str_utf8_encode(char *ptr, int chr)\n{\n\t/* encode */\n\tif(chr <= 0x7F)\n\t{\n\t\tptr[0] = (char)chr;\n\t\treturn 1;\n\t}\n\telse if(chr <= 0x7FF)\n\t{\n\t\tptr[0] = 0xC0|((chr>>6)&0x1F);\n\t\tptr[1] = 0x80|(chr&0x3F);\n\t\treturn 2;\n\t}\n\telse if(chr <= 0xFFFF)\n\t{\n\t\tptr[0] = 0xE0|((chr>>12)&0x0F);\n\t\tptr[1] = 0x80|((chr>>6)&0x3F);\n\t\tptr[2] = 0x80|(chr&0x3F);\n\t\treturn 3;\n\t}\n\telse if(chr <= 0x10FFFF)\n\t{\n\t\tptr[0] = 0xF0|((chr>>18)&0x07);\n\t\tptr[1] = 0x80|((chr>>12)&0x3F);\n\t\tptr[2] = 0x80|((chr>>6)&0x3F);\n\t\tptr[3] = 0x80|(chr&0x3F);\n\t\treturn 4;\n\t}\n\n\treturn 0;\n}\n\nint str_utf8_decode(const char **ptr)\n{\n\tconst char *buf = *ptr;\n\tint ch = 0;\n\n\tdo\n\t{\n\t\tif((*buf&0x80) == 0x0)  /* 0xxxxxxx */\n\t\t{\n\t\t\tch = *buf;\n\t\t\tbuf++;\n\t\t}\n\t\telse if((*buf&0xE0) == 0xC0) /* 110xxxxx */\n\t\t{\n\t\t\tch  = (*buf++ & 0x3F) << 6; if(!(*buf)) break;\n\t\t\tch += (*buf++ & 0x3F);\n\t\t\tif(ch == 0) ch = -1;\n\t\t}\n\t\telse  if((*buf & 0xF0) == 0xE0)\t/* 1110xxxx */\n\t\t{\n\t\t\tch  = (*buf++ & 0x1F) << 12; if(!(*buf)) break;\n\t\t\tch += (*buf++ & 0x3F) <<  6; if(!(*buf)) break;\n\t\t\tch += (*buf++ & 0x3F);\n\t\t\tif(ch == 0) ch = -1;\n\t\t}\n\t\telse if((*buf & 0xF8) == 0xF0)\t/* 11110xxx */\n\t\t{\n\t\t\tch  = (*buf++ & 0x0F) << 18; if(!(*buf)) break;\n\t\t\tch += (*buf++ & 0x3F) << 12; if(!(*buf)) break;\n\t\t\tch += (*buf++ & 0x3F) <<  6; if(!(*buf)) break;\n\t\t\tch += (*buf++ & 0x3F);\n\t\t\tif(ch == 0) ch = -1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t/* invalid */\n\t\t\tbuf++;\n\t\t\tbreak;\n\t\t}\n\n\t\t*ptr = buf;\n\t\treturn ch;\n\t} while(0);\n\n\t/* out of bounds */\n\t*ptr = buf;\n\treturn -1;\n\n}\n\nint str_utf8_check(const char *str)\n{\n\twhile(*str)\n\t{\n\t\tif((*str&0x80) == 0x0)\n\t\t\tstr++;\n\t\telse if((*str&0xE0) == 0xC0 && (*(str+1)&0xC0) == 0x80)\n\t\t\tstr += 2;\n\t\telse if((*str&0xF0) == 0xE0 && (*(str+1)&0xC0) == 0x80 && (*(str+2)&0xC0) == 0x80)\n\t\t\tstr += 3;\n\t\telse if((*str&0xF8) == 0xF0 && (*(str+1)&0xC0) == 0x80 && (*(str+2)&0xC0) == 0x80 && (*(str+3)&0xC0) == 0x80)\n\t\t\tstr += 4;\n\t\telse\n\t\t\treturn 0;\n\t}\n\treturn 1;\n}\n\n\nunsigned str_quickhash(const char *str)\n{\n\tunsigned hash = 5381;\n\tfor(; *str; str++)\n\t\thash = ((hash << 5) + hash) + (*str); /* hash * 33 + c */\n\treturn hash;\n}\n\n\n#if defined(__cplusplus)\n}\n#endif\n"
  },
  {
    "path": "src/base/system.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n\n/*\n\tTitle: OS Abstraction\n*/\n\n#ifndef BASE_SYSTEM_H\n#define BASE_SYSTEM_H\n\n#include \"detect.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/* Group: Debug */\n/*\n\tFunction: dbg_assert\n\t\tBreaks into the debugger based on a test.\n\n\tParameters:\n\t\ttest - Result of the test.\n\t\tmsg - Message that should be printed if the test fails.\n\n\tRemarks:\n\t\tDoes nothing in release version of the library.\n\n\tSee Also:\n\t\t<dbg_break>\n*/\nvoid dbg_assert(int test, const char *msg);\n#define dbg_assert(test,msg) dbg_assert_imp(__FILE__, __LINE__, test, msg)\nvoid dbg_assert_imp(const char *filename, int line, int test, const char *msg);\n\n\n#ifdef __clang_analyzer__\n#include <assert.h>\n#undef dbg_assert\n#define dbg_assert(test,msg) assert(test)\n#endif\n\n/*\n\tFunction: dbg_break\n\t\tBreaks into the debugger.\n\n\tRemarks:\n\t\tDoes nothing in release version of the library.\n\n\tSee Also:\n\t\t<dbg_assert>\n*/\nvoid dbg_break();\n\n/*\n\tFunction: dbg_msg\n\n\tPrints a debug message.\n\n\tParameters:\n\t\tsys - A string that describes what system the message belongs to\n\t\tfmt - A printf styled format string.\n\n\tRemarks:\n\t\tDoes nothing in release version of the library.\n\n\tSee Also:\n\t\t<dbg_assert>\n*/\nvoid dbg_msg(const char *sys, const char *fmt, ...);\n\n/* Group: Memory */\n\n/*\n\tFunction: mem_alloc\n\t\tAllocates memory.\n\n\tParameters:\n\t\tsize - Size of the needed block.\n\t\talignment - Alignment for the block.\n\n\tReturns:\n\t\tReturns a pointer to the newly allocated block. Returns a\n\t\tnull pointer if the memory couldn't be allocated.\n\n\tRemarks:\n\t\t- Passing 0 to size will allocated the smallest amount possible\n\t\tand return a unique pointer.\n\n\tSee Also:\n\t\t<mem_free>\n*/\nvoid *mem_alloc_debug(const char *filename, int line, unsigned size, unsigned alignment);\n#define mem_alloc(s,a) mem_alloc_debug(__FILE__, __LINE__, (s), (a))\n\n/*\n\tFunction: mem_free\n\t\tFrees a block allocated through <mem_alloc>.\n\n\tRemarks:\n\t\t- In the debug version of the library the function will assert if\n\t\ta non-valid block is passed, like a null pointer or a block that\n\t\tisn't allocated.\n\n\tSee Also:\n\t\t<mem_alloc>\n*/\nvoid mem_free(void *block);\n\n/*\n\tFunction: mem_copy\n\t\tCopies a a memory block.\n\n\tParameters:\n\t\tdest - Destination.\n\t\tsource - Source to copy.\n\t\tsize - Size of the block to copy.\n\n\tRemarks:\n\t\t- This functions DOES NOT handles cases where source and\n\t\tdestination is overlapping.\n\n\tSee Also:\n\t\t<mem_move>\n*/\nvoid mem_copy(void *dest, const void *source, unsigned size);\n\n/*\n\tFunction: mem_move\n\t\tCopies a a memory block\n\n\tParameters:\n\t\tdest - Destination\n\t\tsource - Source to copy\n\t\tsize - Size of the block to copy\n\n\tRemarks:\n\t\t- This functions handles cases where source and destination\n\t\tis overlapping\n\n\tSee Also:\n\t\t<mem_copy>\n*/\nvoid mem_move(void *dest, const void *source, unsigned size);\n\n/*\n\tFunction: mem_zero\n\t\tSets a complete memory block to 0\n\n\tParameters:\n\t\tblock - Pointer to the block to zero out\n\t\tsize - Size of the block\n*/\nvoid mem_zero(void *block, unsigned size);\n\n/*\n\tFunction: mem_comp\n\t\tCompares two blocks of memory\n\n\tParameters:\n\t\ta - First block of data\n\t\tb - Second block of data\n\t\tsize - Size of the data to compare\n\n\tReturns:\n\t\t<0 - Block a is lesser then block b\n\t\t0 - Block a is equal to block b\n\t\t>0 - Block a is greater then block b\n*/\nint mem_comp(const void *a, const void *b, int size);\n\n/*\n\tFunction: mem_check\n\t\tValidates the heap\n\t\tWill trigger a assert if memory has failed.\n*/\nint mem_check_imp();\n#define mem_check() dbg_assert_imp(__FILE__, __LINE__, mem_check_imp(), \"Memory check failed\")\n\n/* Group: File IO */\nenum {\n\tIOFLAG_READ = 1,\n\tIOFLAG_WRITE = 2,\n\tIOFLAG_RANDOM = 4,\n\n\tIOSEEK_START = 0,\n\tIOSEEK_CUR = 1,\n\tIOSEEK_END = 2\n};\n\ntypedef struct IOINTERNAL *IOHANDLE;\n\n/*\n\tFunction: io_open\n\t\tOpens a file.\n\n\tParameters:\n\t\tfilename - File to open.\n\t\tflags - A set of flags. IOFLAG_READ, IOFLAG_WRITE, IOFLAG_RANDOM.\n\n\tReturns:\n\t\tReturns a handle to the file on success and 0 on failure.\n\n*/\nIOHANDLE io_open(const char *filename, int flags);\n\n/*\n\tFunction: io_read\n\t\tReads data into a buffer from a file.\n\n\tParameters:\n\t\tio - Handle to the file to read data from.\n\t\tbuffer - Pointer to the buffer that will recive the data.\n\t\tsize - Number of bytes to read from the file.\n\n\tReturns:\n\t\tNumber of bytes read.\n\n*/\nunsigned io_read(IOHANDLE io, void *buffer, unsigned size);\n\n/*\n\tFunction: io_skip\n\t\tSkips data in a file.\n\n\tParameters:\n\t\tio - Handle to the file.\n\t\tsize - Number of bytes to skip.\n\n\tReturns:\n\t\tNumber of bytes skipped.\n*/\nunsigned io_skip(IOHANDLE io, int size);\n\n/*\n\tFunction: io_write\n\t\tWrites data from a buffer to file.\n\n\tParameters:\n\t\tio - Handle to the file.\n\t\tbuffer - Pointer to the data that should be written.\n\t\tsize - Number of bytes to write.\n\n\tReturns:\n\t\tNumber of bytes written.\n*/\nunsigned io_write(IOHANDLE io, const void *buffer, unsigned size);\n\n/*\n\tFunction: io_write_newline\n\t\tWrites newline to file.\n\n\tParameters:\n\t\tio - Handle to the file.\n\n\tReturns:\n\t\tNumber of bytes written.\n*/\nunsigned io_write_newline(IOHANDLE io);\n\n/*\n\tFunction: io_seek\n\t\tSeeks to a specified offset in the file.\n\n\tParameters:\n\t\tio - Handle to the file.\n\t\toffset - Offset from pos to stop.\n\t\torigin - Position to start searching from.\n\n\tReturns:\n\t\tReturns 0 on success.\n*/\nint io_seek(IOHANDLE io, int offset, int origin);\n\n/*\n\tFunction: io_tell\n\t\tGets the current position in the file.\n\n\tParameters:\n\t\tio - Handle to the file.\n\n\tReturns:\n\t\tReturns the current position. -1L if an error occured.\n*/\nlong int io_tell(IOHANDLE io);\n\n/*\n\tFunction: io_length\n\t\tGets the total length of the file. Resetting cursor to the beginning\n\n\tParameters:\n\t\tio - Handle to the file.\n\n\tReturns:\n\t\tReturns the total size. -1L if an error occured.\n*/\nlong int io_length(IOHANDLE io);\n\n/*\n\tFunction: io_close\n\t\tCloses a file.\n\n\tParameters:\n\t\tio - Handle to the file.\n\n\tReturns:\n\t\tReturns 0 on success.\n*/\nint io_close(IOHANDLE io);\n\n/*\n\tFunction: io_flush\n\t\tEmpties all buffers and writes all pending data.\n\n\tParameters:\n\t\tio - Handle to the file.\n\n\tReturns:\n\t\tReturns 0 on success.\n*/\nint io_flush(IOHANDLE io);\n\n\n/*\n\tFunction: io_stdin\n\t\tReturns an <IOHANDLE> to the standard input.\n*/\nIOHANDLE io_stdin();\n\n/*\n\tFunction: io_stdout\n\t\tReturns an <IOHANDLE> to the standard output.\n*/\nIOHANDLE io_stdout();\n\n/*\n\tFunction: io_stderr\n\t\tReturns an <IOHANDLE> to the standard error.\n*/\nIOHANDLE io_stderr();\n\n\n/* Group: Threads */\n\n/*\n\tFunction: thread_sleep\n\t\tSuspends the current thread for a given period.\n\n\tParameters:\n\t\tmilliseconds - Number of milliseconds to sleep.\n*/\nvoid thread_sleep(int milliseconds);\n\n/*\n\tFunction: thread_create\n\t\tCreates a new thread.\n\n\tParameters:\n\t\tthreadfunc - Entry point for the new thread.\n\t\tuser - Pointer to pass to the thread.\n\n*/\nvoid *thread_create(void (*threadfunc)(void *), void *user);\n\n/*\n\tFunction: thread_wait\n\t\tWaits for a thread to be done or destroyed.\n\n\tParameters:\n\t\tthread - Thread to wait for.\n*/\nvoid thread_wait(void *thread);\n\n/*\n\tFunction: thread_destroy\n\t\tDestroys a thread.\n\n\tParameters:\n\t\tthread - Thread to destroy.\n*/\nvoid thread_destroy(void *thread);\n\n/*\n\tFunction: thread_yeild\n\t\tYeild the current threads execution slice.\n*/\nvoid thread_yield();\n\n/*\n\tFunction: thread_detach\n\t\tPuts the thread in the detached thread, guaranteeing that\n\t\tresources of the thread will be freed immediately when the\n\t\tthread terminates.\n\n\tParameters:\n\t\tthread - Thread to detach\n*/\nvoid thread_detach(void *thread);\n\n/* Group: Locks */\ntypedef void* LOCK;\n\nLOCK lock_create();\nvoid lock_destroy(LOCK lock);\n\nint lock_try(LOCK lock);\nvoid lock_wait(LOCK lock);\nvoid lock_release(LOCK lock);\n\n\n/* Group: Semaphores */\n\n#if !defined(CONF_PLATFORM_MACOSX)\n\t#if defined(CONF_FAMILY_UNIX)\n\t\t#include <semaphore.h>\n\t\ttypedef sem_t SEMAPHORE;\n\t#elif defined(CONF_FAMILY_WINDOWS)\n\t\ttypedef void* SEMAPHORE;\n\t#else\n\t\t#error missing sempahore implementation\n\t#endif\n\n\tvoid semaphore_init(SEMAPHORE *sem);\n\tvoid semaphore_wait(SEMAPHORE *sem);\n\tvoid semaphore_signal(SEMAPHORE *sem);\n\tvoid semaphore_destroy(SEMAPHORE *sem);\n#endif\n\n/* Group: Timer */\n#ifdef __GNUC__\n/* if compiled with -pedantic-errors it will complain about long\n\tnot being a C90 thing.\n*/\n__extension__ typedef long long int64;\n#else\ntypedef long long int64;\n#endif\n/*\n\tFunction: time_get\n\t\tFetches a sample from a high resolution timer.\n\n\tReturns:\n\t\tCurrent value of the timer.\n\n\tRemarks:\n\t\tTo know how fast the timer is ticking, see <time_freq>.\n*/\nint64 time_get();\n\n/*\n\tFunction: time_freq\n\t\tReturns the frequency of the high resolution timer.\n\n\tReturns:\n\t\tReturns the frequency of the high resolution timer.\n*/\nint64 time_freq();\n\n/*\n\tFunction: time_timestamp\n\t\tRetrives the current time as a UNIX timestamp\n\n\tReturns:\n\t\tThe time as a UNIX timestamp\n*/\nint time_timestamp();\n\n/* Group: Network General */\ntypedef struct\n{\n\tint type;\n\tint ipv4sock;\n\tint ipv6sock;\n} NETSOCKET;\n\nenum\n{\n\tNETADDR_MAXSTRSIZE = 1+(8*4+7)+1+1+5+1, // [XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX]:XXXXX\n\n\tNETTYPE_INVALID = 0,\n\tNETTYPE_IPV4 = 1,\n\tNETTYPE_IPV6 = 2,\n\tNETTYPE_LINK_BROADCAST = 4,\n\tNETTYPE_ALL = NETTYPE_IPV4|NETTYPE_IPV6\n};\n\ntypedef struct\n{\n\tunsigned int type;\n\tunsigned char ip[16];\n\tunsigned short port;\n} NETADDR;\n\n/*\n\tFunction: net_init\n\t\tInitiates network functionallity.\n\n\tReturns:\n\t\tReturns 0 on success,\n\n\tRemarks:\n\t\tYou must call this function before using any other network\n\t\tfunctions.\n*/\nint net_init();\n\n/*\n\tFunction: net_host_lookup\n\t\tDoes a hostname lookup by name and fills out the passed\n\t\tNETADDR struct with the recieved details.\n\n\tReturns:\n\t\t0 on success.\n*/\nint net_host_lookup(const char *hostname, NETADDR *addr, int types);\n\n/*\n\tFunction: net_addr_comp\n\t\tCompares two network addresses.\n\n\tParameters:\n\t\ta - Address to compare\n\t\tb - Address to compare to.\n\n\tReturns:\n\t\t<0 - Address a is lesser then address b\n\t\t0 - Address a is equal to address b\n\t\t>0 - Address a is greater then address b\n*/\nint net_addr_comp(const NETADDR *a, const NETADDR *b);\n\n/*\n\tFunction: net_addr_str\n\t\tTurns a network address into a representive string.\n\n\tParameters:\n\t\taddr - Address to turn into a string.\n\t\tstring - Buffer to fill with the string.\n\t\tmax_length - Maximum size of the string.\n\t\tadd_port - add port to string or not\n\n\tRemarks:\n\t\t- The string will always be zero terminated\n\n*/\nvoid net_addr_str(const NETADDR *addr, char *string, int max_length, int add_port);\n\n/*\n\tFunction: net_addr_from_str\n\t\tTurns string into a network address.\n\n\tReturns:\n\t\t0 on success\n\n\tParameters:\n\t\taddr - Address to fill in.\n\t\tstring - String to parse.\n*/\nint net_addr_from_str(NETADDR *addr, const char *string);\n\n/* Group: Network UDP */\n\n/*\n\tFunction: net_udp_create\n\t\tCreates a UDP socket and binds it to a port.\n\n\tParameters:\n\t\tbindaddr - Address to bind the socket to.\n\n\tReturns:\n\t\tOn success it returns an handle to the socket. On failure it\n\t\treturns NETSOCKET_INVALID.\n*/\nNETSOCKET net_udp_create(NETADDR bindaddr);\n\n/*\n\tFunction: net_udp_send\n\t\tSends a packet over an UDP socket.\n\n\tParameters:\n\t\tsock - Socket to use.\n\t\taddr - Where to send the packet.\n\t\tdata - Pointer to the packet data to send.\n\t\tsize - Size of the packet.\n\n\tReturns:\n\t\tOn success it returns the number of bytes sent. Returns -1\n\t\ton error.\n*/\nint net_udp_send(NETSOCKET sock, const NETADDR *addr, const void *data, int size);\n\n/*\n\tFunction: net_udp_recv\n\t\tRecives a packet over an UDP socket.\n\n\tParameters:\n\t\tsock - Socket to use.\n\t\taddr - Pointer to an NETADDR that will recive the address.\n\t\tdata - Pointer to a buffer that will recive the data.\n\t\tmaxsize - Maximum size to recive.\n\n\tReturns:\n\t\tOn success it returns the number of bytes recived. Returns -1\n\t\ton error.\n*/\nint net_udp_recv(NETSOCKET sock, NETADDR *addr, void *data, int maxsize);\n\n/*\n\tFunction: net_udp_close\n\t\tCloses an UDP socket.\n\n\tParameters:\n\t\tsock - Socket to close.\n\n\tReturns:\n\t\tReturns 0 on success. -1 on error.\n*/\nint net_udp_close(NETSOCKET sock);\n\n\n/* Group: Network TCP */\n\n/*\n\tFunction: net_tcp_create\n\t\tCreates a TCP socket.\n\n\tParameters:\n\t\tbindaddr - Address to bind the socket to.\n\n\tReturns:\n\t\tOn success it returns an handle to the socket. On failure it returns NETSOCKET_INVALID.\n*/\nNETSOCKET net_tcp_create(NETADDR bindaddr);\n\n/*\n\tFunction: net_tcp_listen\n\t\tMakes the socket start listening for new connections.\n\n\tParameters:\n\t\tsock - Socket to start listen to.\n\t\tbacklog - Size of the queue of incomming connections to keep.\n\n\tReturns:\n\t\tReturns 0 on success.\n*/\nint net_tcp_listen(NETSOCKET sock, int backlog);\n\n/*\n\tFunction: net_tcp_accept\n\t\tPolls a listning socket for a new connection.\n\n\tParameters:\n\t\tsock - Listning socket to poll.\n\t\tnew_sock - Pointer to a socket to fill in with the new socket.\n\t\taddr - Pointer to an address that will be filled in the remote address (optional, can be NULL).\n\n\tReturns:\n\t\tReturns a non-negative integer on success. Negative integer on failure.\n*/\nint net_tcp_accept(NETSOCKET sock, NETSOCKET *new_sock, NETADDR *addr);\n\n/*\n\tFunction: net_tcp_connect\n\t\tConnects one socket to another.\n\n\tParameters:\n\t\tsock - Socket to connect.\n\t\taddr - Address to connect to.\n\n\tReturns:\n\t\tReturns 0 on success.\n\n*/\nint net_tcp_connect(NETSOCKET sock, const NETADDR *addr);\n\n/*\n\tFunction: net_tcp_send\n\t\tSends data to a TCP stream.\n\n\tParameters:\n\t\tsock - Socket to send data to.\n\t\tdata - Pointer to the data to send.\n\t\tsize - Size of the data to send.\n\n\tReturns:\n\t\tNumber of bytes sent. Negative value on failure.\n*/\nint net_tcp_send(NETSOCKET sock, const void *data, int size);\n\n/*\n\tFunction: net_tcp_recv\n\t\tRecvives data from a TCP stream.\n\n\tParameters:\n\t\tsock - Socket to recvive data from.\n\t\tdata - Pointer to a buffer to write the data to\n\t\tmax_size - Maximum of data to write to the buffer.\n\n\tReturns:\n\t\tNumber of bytes recvived. Negative value on failure. When in\n\t\tnon-blocking mode, it returns 0 when there is no more data to\n\t\tbe fetched.\n*/\nint net_tcp_recv(NETSOCKET sock, void *data, int maxsize);\n\n/*\n\tFunction: net_tcp_close\n\t\tCloses a TCP socket.\n\n\tParameters:\n\t\tsock - Socket to close.\n\n\tReturns:\n\t\tReturns 0 on success. Negative value on failure.\n*/\nint net_tcp_close(NETSOCKET sock);\n\n/* Group: Strings */\n\n/*\n\tFunction: str_append\n\t\tAppends a string to another.\n\n\tParameters:\n\t\tdst - Pointer to a buffer that contains a string.\n\t\tsrc - String to append.\n\t\tdst_size - Size of the buffer of the dst string.\n\n\tRemarks:\n\t\t- The strings are treated as zero-termineted strings.\n\t\t- Garantees that dst string will contain zero-termination.\n*/\nvoid str_append(char *dst, const char *src, int dst_size);\n\n/*\n\tFunction: str_copy\n\t\tCopies a string to another.\n\n\tParameters:\n\t\tdst - Pointer to a buffer that shall recive the string.\n\t\tsrc - String to be copied.\n\t\tdst_size - Size of the buffer dst.\n\n\tRemarks:\n\t\t- The strings are treated as zero-termineted strings.\n\t\t- Garantees that dst string will contain zero-termination.\n*/\nvoid str_copy(char *dst, const char *src, int dst_size);\n\n/*\n\tFunction: str_length\n\t\tReturns the length of a zero terminated string.\n\n\tParameters:\n\t\tstr - Pointer to the string.\n\n\tReturns:\n\t\tLength of string in bytes excluding the zero termination.\n*/\nint str_length(const char *str);\n\n/*\n\tFunction: str_format\n\t\tPerforms printf formating into a buffer.\n\n\tParameters:\n\t\tbuffer - Pointer to the buffer to recive the formated string.\n\t\tbuffer_size - Size of the buffer.\n\t\tformat - printf formating string.\n\t\t... - Parameters for the formating.\n\n\tRemarks:\n\t\t- See the C manual for syntax for the printf formating string.\n\t\t- The strings are treated as zero-termineted strings.\n\t\t- Garantees that dst string will contain zero-termination.\n*/\nvoid str_format(char *buffer, int buffer_size, const char *format, ...);\n\n/*\n\tFunction: str_sanitize_strong\n\t\tReplaces all characters below 32 and above 127 with whitespace.\n\n\tParameters:\n\t\tstr - String to sanitize.\n\n\tRemarks:\n\t\t- The strings are treated as zero-termineted strings.\n*/\nvoid str_sanitize_strong(char *str);\n\n/*\n\tFunction: str_sanitize_cc\n\t\tReplaces all characters below 32 with whitespace.\n\n\tParameters:\n\t\tstr - String to sanitize.\n\n\tRemarks:\n\t\t- The strings are treated as zero-termineted strings.\n*/\nvoid str_sanitize_cc(char *str);\n\n/*\n\tFunction: str_sanitize\n\t\tReplaces all characters below 32 with whitespace with\n\t\texception to \\t, \\n and \\r.\n\n\tParameters:\n\t\tstr - String to sanitize.\n\n\tRemarks:\n\t\t- The strings are treated as zero-termineted strings.\n*/\nvoid str_sanitize(char *str);\n\n/*\n\tFunction: str_skip_to_whitespace\n\t\tSkips leading non-whitespace characters(all but ' ', '\\t', '\\n', '\\r').\n\n\tParameters:\n\t\tstr - Pointer to the string.\n\n\tReturns:\n\t\tPointer to the first whitespace character found\n\t\twithin the string.\n\n\tRemarks:\n\t\t- The strings are treated as zero-termineted strings.\n*/\nchar *str_skip_to_whitespace(char *str);\n\n/*\n\tFunction: str_skip_whitespaces\n\t\tSkips leading whitespace characters(' ', '\\t', '\\n', '\\r').\n\n\tParameters:\n\t\tstr - Pointer to the string.\n\n\tReturns:\n\t\tPointer to the first non-whitespace character found\n\t\twithin the string.\n\n\tRemarks:\n\t\t- The strings are treated as zero-termineted strings.\n*/\nchar *str_skip_whitespaces(char *str);\n\n/*\n\tFunction: str_comp_nocase\n\t\tCompares to strings case insensitive.\n\n\tParameters:\n\t\ta - String to compare.\n\t\tb - String to compare.\n\n\tReturns:\n\t\t<0 - String a is lesser then string b\n\t\t0 - String a is equal to string b\n\t\t>0 - String a is greater then string b\n\n\tRemarks:\n\t\t- Only garanted to work with a-z/A-Z.\n\t\t- The strings are treated as zero-termineted strings.\n*/\nint str_comp_nocase(const char *a, const char *b);\n\n/*\n\tFunction: str_comp_nocase_num\n\t\tCompares up to num characters of two strings case insensitive.\n\n\tParameters:\n\t\ta - String to compare.\n\t\tb - String to compare.\n\t\tnum - Maximum characters to compare\n\n\tReturns:\n\t\t<0 - String a is lesser than string b\n\t\t0 - String a is equal to string b\n\t\t>0 - String a is greater than string b\n\n\tRemarks:\n\t\t- Only garanted to work with a-z/A-Z.\n\t\t- The strings are treated as zero-termineted strings.\n*/\nint str_comp_nocase_num(const char *a, const char *b, const int num);\n\n/*\n\tFunction: str_comp\n\t\tCompares to strings case sensitive.\n\n\tParameters:\n\t\ta - String to compare.\n\t\tb - String to compare.\n\n\tReturns:\n\t\t<0 - String a is lesser then string b\n\t\t0 - String a is equal to string b\n\t\t>0 - String a is greater then string b\n\n\tRemarks:\n\t\t- The strings are treated as zero-termineted strings.\n*/\nint str_comp(const char *a, const char *b);\n\n/*\n\tFunction: str_comp_num\n\t\tCompares up to num characters of two strings case sensitive.\n\n\tParameters:\n\t\ta - String to compare.\n\t\tb - String to compare.\n\t\tnum - Maximum characters to compare\n\n\tReturns:\n\t\t<0 - String a is lesser then string b\n\t\t0 - String a is equal to string b\n\t\t>0 - String a is greater then string b\n\n\tRemarks:\n\t\t- The strings are treated as zero-termineted strings.\n*/\nint str_comp_num(const char *a, const char *b, const int num);\n\n/*\n\tFunction: str_comp_filenames\n\t\tCompares two strings case sensitive, digit chars will be compared as numbers.\n\n\tParameters:\n\t\ta - String to compare.\n\t\tb - String to compare.\n\n\tReturns:\n\t\t<0 - String a is lesser then string b\n\t\t0 - String a is equal to string b\n\t\t>0 - String a is greater then string b\n\n\tRemarks:\n\t\t- The strings are treated as zero-termineted strings.\n*/\nint str_comp_filenames(const char *a, const char *b);\n\n/*\n\tFunction: str_find_nocase\n\t\tFinds a string inside another string case insensitive.\n\n\tParameters:\n\t\thaystack - String to search in\n\t\tneedle - String to search for\n\n\tReturns:\n\t\tA pointer into haystack where the needle was found.\n\t\tReturns NULL of needle could not be found.\n\n\tRemarks:\n\t\t- Only garanted to work with a-z/A-Z.\n\t\t- The strings are treated as zero-termineted strings.\n*/\nconst char *str_find_nocase(const char *haystack, const char *needle);\n\n/*\n\tFunction: str_find\n\t\tFinds a string inside another string case sensitive.\n\n\tParameters:\n\t\thaystack - String to search in\n\t\tneedle - String to search for\n\n\tReturns:\n\t\tA pointer into haystack where the needle was found.\n\t\tReturns NULL of needle could not be found.\n\n\tRemarks:\n\t\t- The strings are treated as zero-termineted strings.\n*/\nconst char *str_find(const char *haystack, const char *needle);\n\n/*\n\tFunction: str_hex\n\t\tTakes a datablock and generates a hexstring of it.\n\n\tParameters:\n\t\tdst - Buffer to fill with hex data\n\t\tdst_size - size of the buffer\n\t\tdata - Data to turn into hex\n\t\tdata - Size of the data\n\n\tRemarks:\n\t\t- The desination buffer will be zero-terminated\n*/\nvoid str_hex(char *dst, int dst_size, const void *data, int data_size);\n\n/*\n\tFunction: str_timestamp\n\t\tCopies a time stamp in the format year-month-day_hour-minute-second to the string.\n\n\tParameters:\n\t\tbuffer - Pointer to a buffer that shall receive the time stamp string.\n\t\tbuffer_size - Size of the buffer.\n\n\tRemarks:\n\t\t- Guarantees that buffer string will contain zero-termination.\n*/\nvoid str_timestamp(char *buffer, int buffer_size);\n\n/* Group: Filesystem */\n\n/*\n\tFunction: fs_listdir\n\t\tLists the files in a directory\n\n\tParameters:\n\t\tdir - Directory to list\n\t\tcb - Callback function to call for each entry\n\t\ttype - Type of the directory\n\t\tuser - Pointer to give to the callback\n\n\tReturns:\n\t\tAlways returns 0.\n*/\ntypedef int (*FS_LISTDIR_CALLBACK)(const char *name, int is_dir, int dir_type, void *user);\nint fs_listdir(const char *dir, FS_LISTDIR_CALLBACK cb, int type, void *user);\n\n/*\n\tFunction: fs_makedir\n\t\tCreates a directory\n\n\tParameters:\n\t\tpath - Directory to create\n\n\tReturns:\n\t\tReturns 0 on success. Negative value on failure.\n\n\tRemarks:\n\t\tDoes not create several directories if needed. \"a/b/c\" will result\n\t\tin a failure if b or a does not exist.\n*/\nint fs_makedir(const char *path);\n\n/*\n\tFunction: fs_storage_path\n\t\tFetches per user configuration directory.\n\n\tReturns:\n\t\tReturns 0 on success. Negative value on failure.\n\n\tRemarks:\n\t\t- Returns ~/.appname on UNIX based systems\n\t\t- Returns ~/Library/Applications Support/appname on Mac OS X\n\t\t- Returns %APPDATA%/Appname on Windows based systems\n*/\nint fs_storage_path(const char *appname, char *path, int max);\n\n/*\n\tFunction: fs_is_dir\n\t\tChecks if directory exists\n\n\tReturns:\n\t\tReturns 1 on success, 0 on failure.\n*/\nint fs_is_dir(const char *path);\n\n/*\n\tFunction: fs_chdir\n\t\tChanges current working directory\n\n\tReturns:\n\t\tReturns 0 on success, 1 on failure.\n*/\nint fs_chdir(const char *path);\n\n/*\n\tFunction: fs_getcwd\n\t\tGets the current working directory.\n\n\tReturns:\n\t\tReturns a pointer to the buffer on success, 0 on failure.\n*/\nchar *fs_getcwd(char *buffer, int buffer_size);\n\n/*\n\tFunction: fs_parent_dir\n\t\tGet the parent directory of a directory\n\n\tParameters:\n\t\tpath - The directory string\n\n\tReturns:\n\t\tReturns 0 on success, 1 on failure.\n\n\tRemarks:\n\t\t- The string is treated as zero-termineted string.\n*/\nint fs_parent_dir(char *path);\n\n/*\n\tFunction: fs_remove\n\t\tDeletes the file with the specified name.\n\n\tParameters:\n\t\tfilename - The file to delete\n\n\tReturns:\n\t\tReturns 0 on success, 1 on failure.\n\n\tRemarks:\n\t\t- The strings are treated as zero-terminated strings.\n*/\nint fs_remove(const char *filename);\n\n/*\n\tFunction: fs_rename\n\t\tRenames the file or directory. If the paths differ the file will be moved.\n\n\tParameters:\n\t\toldname - The actual name\n\t\tnewname - The new name\n\n\tReturns:\n\t\tReturns 0 on success, 1 on failure.\n\n\tRemarks:\n\t\t- The strings are treated as zero-terminated strings.\n*/\nint fs_rename(const char *oldname, const char *newname);\n\n/*\n\tGroup: Undocumented\n*/\n\n\n/*\n\tFunction: net_tcp_connect_non_blocking\n\n\tDOCTODO: serp\n*/\nint net_tcp_connect_non_blocking(NETSOCKET sock, NETADDR bindaddr);\n\n/*\n\tFunction: net_set_non_blocking\n\n\tDOCTODO: serp\n*/\nint net_set_non_blocking(NETSOCKET sock);\n\n/*\n\tFunction: net_set_non_blocking\n\n\tDOCTODO: serp\n*/\nint net_set_blocking(NETSOCKET sock);\n\n/*\n\tFunction: net_errno\n\n\tDOCTODO: serp\n*/\nint net_errno();\n\n/*\n\tFunction: net_would_block\n\n\tDOCTODO: serp\n*/\nint net_would_block();\n\nint net_socket_read_wait(NETSOCKET sock, int time);\n\nvoid mem_debug_dump(IOHANDLE file);\n\nvoid swap_endian(void *data, unsigned elem_size, unsigned num);\n\n\ntypedef void (*DBG_LOGGER)(const char *line);\nvoid dbg_logger(DBG_LOGGER logger);\n\nvoid dbg_logger_stdout();\nvoid dbg_logger_debugger();\nvoid dbg_logger_file(const char *filename);\n\ntypedef struct\n{\n\tint allocated;\n\tint active_allocations;\n\tint total_allocations;\n} MEMSTATS;\n\nconst MEMSTATS *mem_stats();\n\ntypedef struct\n{\n\tint sent_packets;\n\tint sent_bytes;\n\tint recv_packets;\n\tint recv_bytes;\n} NETSTATS;\n\n\nvoid net_stats(NETSTATS *stats);\n\nint str_toint(const char *str);\nfloat str_tofloat(const char *str);\nint str_isspace(char c);\nchar str_uppercase(char c);\nunsigned str_quickhash(const char *str);\n\n/*\n\tFunction: gui_messagebox\n\t\tDisplay plain OS-dependent message box\n\n\tParameters:\n\t\ttitle - title of the message box\n\t\tmessage - text to display\n*/\nvoid gui_messagebox(const char *title, const char *message);\n\n\n/*\n\tFunction: str_utf8_rewind\n\t\tMoves a cursor backwards in an utf8 string\n\n\tParameters:\n\t\tstr - utf8 string\n\t\tcursor - position in the string\n\n\tReturns:\n\t\tNew cursor position.\n\n\tRemarks:\n\t\t- Won't move the cursor less then 0\n*/\nint str_utf8_rewind(const char *str, int cursor);\n\n/*\n\tFunction: str_utf8_forward\n\t\tMoves a cursor forwards in an utf8 string\n\n\tParameters:\n\t\tstr - utf8 string\n\t\tcursor - position in the string\n\n\tReturns:\n\t\tNew cursor position.\n\n\tRemarks:\n\t\t- Won't move the cursor beyond the zero termination marker\n*/\nint str_utf8_forward(const char *str, int cursor);\n\n/*\n\tFunction: str_utf8_decode\n\t\tDecodes an utf8 character\n\n\tParameters:\n\t\tptr - pointer to an utf8 string. this pointer will be moved forward\n\n\tReturns:\n\t\tUnicode value for the character. -1 for invalid characters and 0 for end of string.\n\n\tRemarks:\n\t\t- This function will also move the pointer forward.\n*/\nint str_utf8_decode(const char **ptr);\n\n/*\n\tFunction: str_utf8_encode\n\t\tEncode an utf8 character\n\n\tParameters:\n\t\tptr - Pointer to a buffer that should recive the data. Should be able to hold at least 4 bytes.\n\n\tReturns:\n\t\tNumber of bytes put into the buffer.\n\n\tRemarks:\n\t\t- Does not do zero termination of the string.\n*/\nint str_utf8_encode(char *ptr, int chr);\n\n/*\n\tFunction: str_utf8_check\n\t\tChecks if a strings contains just valid utf8 characters.\n\n\tParameters:\n\t\tstr - Pointer to a possible utf8 string.\n\n\tReturns:\n\t\t0 - invalid characters found.\n\t\t1 - only valid characters found.\n\n\tRemarks:\n\t\t- The string is treated as zero-terminated utf8 string.\n*/\nint str_utf8_check(const char *str);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "src/base/tl/algorithm.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef BASE_TL_ALGORITHM_H\n#define BASE_TL_ALGORITHM_H\n\n#include \"range.h\"\n\n\n/*\n\tinsert 4\n\t\tv\n\t1 2 3 4 5 6\n\n*/\n\n\ntemplate<class R, class T>\nR partition_linear(R range, T value)\n{\n\tconcept_empty::check(range);\n\tconcept_forwarditeration::check(range);\n\tconcept_sorted::check(range);\n\n\tfor(; !range.empty(); range.pop_front())\n\t{\n\t\tif(!(range.front() < value))\n\t\t\treturn range;\n\t}\n\treturn range;\n}\n\n\ntemplate<class R, class T>\nR partition_binary(R range, T value)\n{\n\tconcept_empty::check(range);\n\tconcept_index::check(range);\n\tconcept_size::check(range);\n\tconcept_slice::check(range);\n\tconcept_sorted::check(range);\n\n\tif(range.empty())\n\t\treturn range;\n\tif(range.back() < value)\n\t\treturn R();\n\n\twhile(range.size() > 1)\n\t{\n\t\tunsigned pivot = (range.size()-1)/2;\n\t\tif(range.index(pivot) < value)\n\t\t\trange = range.slice(pivot+1, range.size()-1);\n\t\telse\n\t\t\trange = range.slice(0, pivot+1);\n\t}\n\treturn range;\n}\n\ntemplate<class R, class T>\nR find_linear(R range, T value)\n{\n\tconcept_empty::check(range);\n\tconcept_forwarditeration::check(range);\n\tfor(; !range.empty(); range.pop_front())\n\t\tif(value == range.front())\n\t\t\tbreak;\n\treturn range;\n}\n\ntemplate<class R, class T>\nR find_binary(R range, T value)\n{\n\trange = partition_linear(range, value);\n\tif(range.empty()) return range;\n\tif(range.front() == value) return range;\n\treturn R();\n}\n\n\ntemplate<class R>\nvoid sort_bubble(R range)\n{\n\tconcept_empty::check(range);\n\tconcept_forwarditeration::check(range);\n\tconcept_backwarditeration::check(range);\n\n\t// slow bubblesort :/\n\tfor(; !range.empty(); range.pop_back())\n\t{\n\t\tR section = range;\n\t\ttypename R::type *prev = &section.front();\n\t\tsection.pop_front();\n\t\tfor(; !section.empty(); section.pop_front())\n\t\t{\n\t\t\ttypename R::type *cur = &section.front();\n\t\t\tif(*cur < *prev)\n\t\t\t\tswap(*cur, *prev);\n\t\t\tprev = cur;\n\t\t}\n\t}\n}\n\n/*\ntemplate<class R>\nvoid sort_quick(R range)\n{\n\tconcept_index::check(range);\n}*/\n\n\ntemplate<class R>\nvoid sort(R range)\n{\n\tsort_bubble(range);\n}\n\n\ntemplate<class R>\nbool sort_verify(R range)\n{\n\tconcept_empty::check(range);\n\tconcept_forwarditeration::check(range);\n\n\ttypename R::type *prev = &range.front();\n\trange.pop_front();\n\tfor(; !range.empty(); range.pop_front())\n\t{\n\t\ttypename R::type *cur = &range.front();\n\n\t\tif(*cur < *prev)\n\t\t\treturn false;\n\t\tprev = cur;\n\t}\n\n\treturn true;\n}\n\n#endif // TL_FILE_ALGORITHMS_HPP\n"
  },
  {
    "path": "src/base/tl/allocator.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef BASE_TL_ALLOCATOR_H\n#define BASE_TL_ALLOCATOR_H\n\ntemplate <class T>\nclass allocator_default\n{\npublic:\n\tstatic T *alloc() { return new T; }\n\tstatic void free(T *p) { delete p; }\n\n\tstatic T *alloc_array(int size) { return new T [size]; }\n\tstatic void free_array(T *p) { delete [] p; }\n};\n\n#endif // TL_FILE_ALLOCATOR_HPP\n"
  },
  {
    "path": "src/base/tl/array.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef BASE_TL_ARRAY_H\n#define BASE_TL_ARRAY_H\n\n#include \"range.h\"\n#include \"allocator.h\"\n\n\n/*\n\tClass: array\n\t\tNormal dynamic array class\n\n\tRemarks:\n\t\t- Grows 50% each time it needs to fit new items\n\t\t- Use set_size() if you know how many elements\n\t\t- Use optimize() to reduce the needed space.\n*/\ntemplate <class T, class ALLOCATOR = allocator_default<T> >\nclass array : private ALLOCATOR\n{\n\tvoid init()\n\t{\n\t\tlist = 0x0;\n\t\tclear();\n\t}\n\npublic:\n\ttypedef plain_range<T> range;\n\n\t/*\n\t\tFunction: array constructor\n\t*/\n\tarray()\n\t{\n\t\tinit();\n\t}\n\n\t/*\n\t\tFunction: array copy constructor\n\t*/\n\tarray(const array &other)\n\t{\n\t\tinit();\n\t\tset_size(other.size());\n\t\tfor(int i = 0; i < size(); i++)\n\t\t\t(*this)[i] = other[i];\n\t}\n\n\n\t/*\n\t\tFunction: array destructor\n\t*/\n\t~array()\n\t{\n\t\tALLOCATOR::free_array(list);\n\t\tlist = 0x0;\n\t}\n\n\n\t/*\n\t\tFunction: delete_all\n\n\t\tRemarks:\n\t\t\t- Invalidates ranges\n\t*/\n\tvoid delete_all()\n\t{\n\t\tfor(int i = 0; i < size(); i++)\n\t\t\tdelete list[i];\n\t\tclear();\n\t}\n\n\n\t/*\n\t\tFunction: clear\n\n\t\tRemarks:\n\t\t\t- Invalidates ranges\n\t*/\n\tvoid clear()\n\t{\n\t\tALLOCATOR::free_array(list);\n\t\tlist_size = 1;\n\t\tlist = ALLOCATOR::alloc_array(list_size);\n\t\tnum_elements = 0;\n\t}\n\n\t/*\n\t\tFunction: size\n\t*/\n\tint size() const\n\t{\n\t\treturn num_elements;\n\t}\n\n\t/*\n\t\tFunction: remove_index_fast\n\n\t\tRemarks:\n\t\t\t- Invalidates ranges\n\t*/\n\tvoid remove_index_fast(int index)\n\t{\n\t\tlist[index] = list[num_elements-1];\n\t\tset_size(size()-1);\n\t}\n\n\t/*\n\t\tFunction: remove_fast\n\n\t\tRemarks:\n\t\t\t- Invalidates ranges\n\t*/\n\tvoid remove_fast(const T& item)\n\t{\n\t\tfor(int i = 0; i < size(); i++)\n\t\t\tif(list[i] == item)\n\t\t\t{\n\t\t\t\tremove_index_fast(i);\n\t\t\t\treturn;\n\t\t\t}\n\t}\n\n\t/*\n\t\tFunction: remove_index\n\n\t\tRemarks:\n\t\t\t- Invalidates ranges\n\t*/\n\tvoid remove_index(int index)\n\t{\n\t\tfor(int i = index+1; i < num_elements; i++)\n\t\t\tlist[i-1] = list[i];\n\n\t\tset_size(size()-1);\n\t}\n\n\t/*\n\t\tFunction: remove\n\n\t\tRemarks:\n\t\t\t- Invalidates ranges\n\t*/\n\tbool remove(const T& item)\n\t{\n\t\tfor(int i = 0; i < size(); i++)\n\t\t\tif(list[i] == item)\n\t\t\t{\n\t\t\t\tremove_index(i);\n\t\t\t\treturn true;\n\t\t\t}\n\t\treturn false;\n\t}\n\n\t/*\n\t\tFunction: add\n\t\t\tAdds an item to the array.\n\n\t\tArguments:\n\t\t\titem - Item to add.\n\n\t\tRemarks:\n\t\t\t- Invalidates ranges\n\t\t\t- See remarks about <array> how the array grows.\n\t*/\n\tint add(const T& item)\n\t{\n\t\tincsize();\n\t\tset_size(size()+1);\n\t\tlist[num_elements-1] = item;\n\t\treturn num_elements-1;\n\t}\n\n\t/*\n\t\tFunction: insert\n\t\t\tInserts an item into the array at a specified location.\n\n\t\tArguments:\n\t\t\titem - Item to insert.\n\t\t\tr - Range where to insert the item\n\n\t\tRemarks:\n\t\t\t- Invalidates ranges\n\t\t\t- See remarks about <array> how the array grows.\n\t*/\n\tint insert(const T& item, range r)\n\t{\n\t\tif(r.empty())\n\t\t\treturn add(item);\n\n\t\tint index = (int)(&r.front()-list);\n\t\tincsize();\n\t\tset_size(size()+1);\n\n\t\tfor(int i = num_elements-1; i > index; i--)\n\t\t\tlist[i] = list[i-1];\n\n\t\tlist[index] = item;\n\n\t\treturn num_elements-1;\n\t}\n\n\t/*\n\t\tFunction: operator[]\n\t*/\n\tT& operator[] (int index)\n\t{\n\t\treturn list[index];\n\t}\n\n\t/*\n\t\tFunction: const operator[]\n\t*/\n\tconst T& operator[] (int index) const\n\t{\n\t\treturn list[index];\n\t}\n\n\t/*\n\t\tFunction: base_ptr\n\t*/\n\tT *base_ptr()\n\t{\n\t\treturn list;\n\t}\n\n\t/*\n\t\tFunction: base_ptr\n\t*/\n\tconst T *base_ptr() const\n\t{\n\t\treturn list;\n\t}\n\n\t/*\n\t\tFunction: set_size\n\t\t\tResizes the array to the specified size.\n\n\t\tArguments:\n\t\t\tnew_size - The new size for the array.\n\t*/\n\tvoid set_size(int new_size)\n\t{\n\t\tif(list_size < new_size)\n\t\t\talloc(new_size);\n\t\tnum_elements = new_size;\n\t}\n\n\t/*\n\t\tFunction: hint_size\n\t\t\tAllocates the number of elements wanted but\n\t\t\tdoes not increase the list size.\n\n\t\tArguments:\n\t\t\thint - Size to allocate.\n\n\t\tRemarks:\n\t\t\t- If the hint is smaller then the number of elements, nothing will be done.\n\t\t\t- Invalidates ranges\n\t*/\n\tvoid hint_size(int hint)\n\t{\n\t\tif(num_elements < hint)\n\t\t\talloc(hint);\n\t}\n\n\n\t/*\n\t\tFunction: optimize\n\t\t\tRemoves unnessasary data, returns how many bytes was earned.\n\n\t\tRemarks:\n\t\t\t- Invalidates ranges\n\t*/\n\tint optimize()\n\t{\n\t\tint before = memusage();\n\t\talloc(num_elements);\n\t\treturn before - memusage();\n\t}\n\n\t/*\n\t\tFunction: memusage\n\t\t\tReturns how much memory this dynamic array is using\n\t*/\n\tint memusage()\n\t{\n\t\treturn sizeof(array) + sizeof(T)*list_size;\n\t}\n\n\t/*\n\t\tFunction: operator=(array)\n\n\t\tRemarks:\n\t\t\t- Invalidates ranges\n\t*/\n\tarray &operator = (const array &other)\n\t{\n\t\tset_size(other.size());\n\t\tfor(int i = 0; i < size(); i++)\n\t\t\t(*this)[i] = other[i];\n\t\treturn *this;\n\t}\n\n\t/*\n\t\tFunction: all\n\t\t\tReturns a range that contains the whole array.\n\t*/\n\trange all() { return range(list, list+num_elements); }\nprotected:\n\n\tvoid incsize()\n\t{\n\t\tif(num_elements == list_size)\n\t\t{\n\t\t\tif(list_size < 2)\n\t\t\t\talloc(list_size+1);\n\t\t\telse\n\t\t\t\talloc(list_size+list_size/2);\n\t\t}\n\t}\n\n\tvoid alloc(int new_len)\n\t{\n\t\tlist_size = new_len;\n\t\tT *new_list = ALLOCATOR::alloc_array(list_size);\n\n\t\tint end = num_elements < list_size ? num_elements : list_size;\n\t\tfor(int i = 0; i < end; i++)\n\t\t\tnew_list[i] = list[i];\n\n\t\tALLOCATOR::free_array(list);\n\n\t\tnum_elements = num_elements < list_size ? num_elements : list_size;\n\t\tlist = new_list;\n\t}\n\n\tT *list;\n\tint list_size;\n\tint num_elements;\n};\n\n#endif // TL_FILE_ARRAY_HPP\n"
  },
  {
    "path": "src/base/tl/base.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef BASE_TL_BASE_H\n#define BASE_TL_BASE_H\n\n#include <base/system.h>\n\ninline void tl_assert(bool statement)\n{\n\tdbg_assert(statement, \"assert!\");\n}\n\ntemplate<class T>\ninline void swap(T &a, T &b)\n{\n\tT c = b;\n\tb = a;\n\ta = c;\n}\n\n#endif\n"
  },
  {
    "path": "src/base/tl/range.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef BASE_TL_RANGE_H\n#define BASE_TL_RANGE_H\n\n#include \"base.h\"\n\n/*\n\tGroup: Range concepts\n*/\n\n/*\n\tConcept: concept_empty\n\n\t\ttemplate<class T>\n\t\tstruct range\n\t\t{\n\t\t\tbool empty() const;\n\t\t};\n*/\nstruct concept_empty\n{\n\ttemplate<typename T> static void check(T &t) { if(0) t.empty(); };\n};\n\n/*\n\tConcept: concept_index\n\n\t\ttemplate<class T>\n\t\tstruct range\n\t\t{\n\t\t\tT &index(size_t);\n\t\t};\n*/\nstruct concept_index\n{\n\ttemplate<typename T> static void check(T &t) { if(0) t.index(0); };\n};\n\n/*\n\tConcept: concept_size\n\n\t\ttemplate<class T>\n\t\tstruct range\n\t\t{\n\t\t\tsize_t size();\n\t\t};\n*/\nstruct concept_size\n{\n\ttemplate<typename T> static void check(T &t) { if(0) t.size(); };\n};\n\n/*\n\tConcept: concept_slice\n\n\t\ttemplate<class T>\n\t\tstruct range\n\t\t{\n\t\t\trange slice(size_t start, size_t count);\n\t\t};\n*/\nstruct concept_slice\n{\n\ttemplate<typename T> static void check(T &t) { if(0) t.slice(0, 0); };\n};\n\n/*\n\tConcept: concept_sorted\n\n\t\ttemplate<class T>\n\t\tstruct range\n\t\t{\n\t\t\tvoid sorted();\n\t\t};\n*/\nstruct concept_sorted\n{\n\ttemplate<typename T> static void check(T &t) { if(0) t.sorted(); };\n};\n\n/*\n\tConcept: concept_forwarditeration\n\t\tChecks for the front and pop_front methods\n\n\t\ttemplate<class T>\n\t\tstruct range\n\t\t{\n\t\t\tvoid pop_front();\n\t\t\tT &front() const;\n\t\t};\n*/\nstruct concept_forwarditeration\n{\n\ttemplate<typename T> static void check(T &t) { if(0) { t.front(); t.pop_front(); } };\n};\n\n/*\n\tConcept: concept_backwarditeration\n\t\tChecks for the back and pop_back methods\n\n\t\ttemplate<class T>\n\t\tstruct range\n\t\t{\n\t\t\tvoid pop_back();\n\t\t\tT &back() const;\n\t\t};\n*/\nstruct concept_backwarditeration\n{\n\ttemplate<typename T> static void check(T &t) { if(0) { t.back(); t.pop_back(); } };\n};\n\n\n/*\n\tGroup: Range classes\n*/\n\n\n/*\n\tClass: plain_range\n\n\tConcepts:\n\t\t<concept_empty>\n\t\t<concept_index>\n\t\t<concept_slice>\n\t\t<concept_forwardinteration>\n\t\t<concept_backwardinteration>\n*/\ntemplate<class T>\nclass plain_range\n{\npublic:\n\ttypedef T type;\n\tplain_range()\n\t{\n\t\tbegin = 0x0;\n\t\tend = 0x0;\n\t}\n\n\tplain_range(const plain_range &r)\n\t{\n\t\t*this = r;\n\t}\n\n\tplain_range(T *b, T *e)\n\t{\n\t\tbegin = b;\n\t\tend = e;\n\t}\n\n\tbool empty() const { return begin >= end; }\n\tvoid pop_front() { tl_assert(!empty()); begin++; }\n\tvoid pop_back() { tl_assert(!empty()); end--; }\n\tT& front() { tl_assert(!empty()); return *begin; }\n\tT& back() { tl_assert(!empty()); return *(end-1); }\n\tT& index(unsigned i) { tl_assert(i < (unsigned)(end-begin)); return begin[i]; }\n\tunsigned size() const { return (unsigned)(end-begin); }\n\tplain_range slice(unsigned startindex, unsigned endindex)\n\t{\n\t\treturn plain_range(begin+startindex, begin+endindex);\n\t}\n\nprotected:\n\tT *begin;\n\tT *end;\n};\n\n/*\n\tClass: plain_range_sorted\n\n\tConcepts:\n\t\tSame as <plain_range> but with these additions:\n\t\t<concept_sorted>\n*/\ntemplate<class T>\nclass plain_range_sorted : public plain_range<T>\n{\n\ttypedef plain_range<T> parent;\npublic:\n\t/* sorted concept */\n\tvoid sorted() const { }\n\n\tplain_range_sorted()\n\t{}\n\n\tplain_range_sorted(const plain_range_sorted &r)\n\t{\n\t\t*this = r;\n\t}\n\n\tplain_range_sorted(T *b, T *e)\n\t: parent(b, e)\n\t{}\n\n\tplain_range_sorted slice(unsigned start, unsigned count)\n\t{\n\t\treturn plain_range_sorted(parent::begin+start, parent::begin+start+count);\n\t}\n};\n\ntemplate<class R>\nclass reverse_range\n{\nprivate:\n\treverse_range() {}\npublic:\n\ttypedef typename R::type type;\n\n\treverse_range(R r)\n\t{\n\t\trange = r;\n\t}\n\n\treverse_range(const reverse_range &other) { range = other.range; }\n\n\n\tbool empty() const { return range.empty(); }\n\tvoid pop_front() { range.pop_back(); }\n\tvoid pop_back() { range.pop_front(); }\n\ttype& front() { return range.back(); }\n\ttype& back() { return range.front(); }\n\n\tR range;\n};\n\ntemplate<class R> reverse_range<R> reverse(R range) {\n\treturn reverse_range<R>(range);\n}\ntemplate<class R> R reverse(reverse_range<R> range) {\n\treturn range.range;\n}\n\n#endif // TL_FILE_RANGE_HPP\n"
  },
  {
    "path": "src/base/tl/sorted_array.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef BASE_TL_SORTED_ARRAY_H\n#define BASE_TL_SORTED_ARRAY_H\n\n#include \"algorithm.h\"\n#include \"array.h\"\n\ntemplate <class T, class ALLOCATOR = allocator_default<T> >\nclass sorted_array : public array<T, ALLOCATOR>\n{\n\ttypedef array<T, ALLOCATOR> parent;\n\n\t// insert and size is not allowed\n\tint insert(const T& item, typename parent::range r) { dbg_break(); return 0; }\n\tint set_size(int new_size) { dbg_break(); return 0; }\n\npublic:\n\ttypedef plain_range_sorted<T> range;\n\n\tint add(const T& item)\n\t{\n\t\treturn parent::insert(item, partition_binary(all(), item));\n\t}\n\n\tint add_unsorted(const T& item)\n\t{\n\t\treturn parent::add(item);\n\t}\n\n\tvoid sort_range()\n\t{\n\t\tsort(all());\n\t}\n\n\n\t/*\n\t\tFunction: all\n\t\t\tReturns a sorted range that contains the whole array.\n\t*/\n\trange all() { return range(parent::list, parent::list+parent::num_elements); }\n};\n\n#endif // TL_FILE_SORTED_ARRAY_HPP\n"
  },
  {
    "path": "src/base/tl/string.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef BASE_TL_STRING_H\n#define BASE_TL_STRING_H\n\n#include \"base.h\"\n#include \"allocator.h\"\n\ntemplate<class ALLOCATOR >\nclass string_base : private ALLOCATOR\n{\n\tchar *str;\n\tint length;\n\n\tvoid reset()\n\t{\n\t\tstr = 0; length = 0;\n\t}\n\n\tvoid free()\n\t{\n\t\tALLOCATOR::free_array(str);\n\t\treset();\n\t}\n\n\tvoid copy(const char *other_str, int other_length)\n\t{\n\t\tlength = other_length;\n\t\tstr = ALLOCATOR::alloc_array(length+1);\n\t\tmem_copy(str, other_str, length+1);\n\t}\n\n\tvoid copy(const string_base &other)\n\t{\n\t\tif(!other.str)\n\t\t\treturn;\n\t\tcopy(other.str, other.length);\n\t}\n\npublic:\n\tstring_base() { reset(); }\n\tstring_base(const char *other_str) { copy(other_str, str_length(other_str)); }\n\tstring_base(const string_base &other) { reset(); copy(other); }\n\t~string_base() { free(); }\n\n\tstring_base &operator = (const char *other)\n\t{\n\t\tfree();\n\t\tif(other)\n\t\t\tcopy(other, str_length(other));\n\t\treturn *this;\n\t}\n\n\tstring_base &operator = (const string_base &other)\n\t{\n\t\tfree();\n\t\tcopy(other);\n\t\treturn *this;\n\t}\n\n\tbool operator < (const char *other_str) const { return str_comp(str, other_str) < 0; }\n\toperator const char *() const { return str; }\n\n\tconst char *cstr() const { return str; }\n};\n\n/* normal allocated string */\ntypedef string_base<allocator_default<char> > string;\n\n#endif // TL_FILE_STRING_HPP\n"
  },
  {
    "path": "src/base/tl/threading.h",
    "content": "\n#pragma once\n\n#include \"../system.h\"\n\n/*\n\tatomic_inc - should return the value after increment\n\tatomic_dec - should return the value after decrement\n\tatomic_compswap - should return the value before the eventual swap\n\tsync_barrier - creates a full hardware fence\n*/\n\n#if defined(__GNUC__)\n\n\tinline unsigned atomic_inc(volatile unsigned *pValue)\n\t{\n\t\treturn __sync_add_and_fetch(pValue, 1);\n\t}\n\n\tinline unsigned atomic_dec(volatile unsigned *pValue)\n\t{\n\t\treturn __sync_add_and_fetch(pValue, -1);\n\t}\n\n\tinline unsigned atomic_compswap(volatile unsigned *pValue, unsigned comperand, unsigned value)\n\t{\n\t\treturn __sync_val_compare_and_swap(pValue, comperand, value);\n\t}\n\n\tinline void sync_barrier()\n\t{\n\t\t__sync_synchronize();\n\t}\n\n#elif defined(_MSC_VER)\n\t#include <intrin.h>\n\n\t#define WIN32_LEAN_AND_MEAN\n\t#include <windows.h>\n\n\tinline unsigned atomic_inc(volatile unsigned *pValue)\n\t{\n\t\treturn _InterlockedIncrement((volatile long *)pValue);\n\t}\n\t\n\tinline unsigned atomic_dec(volatile unsigned *pValue)\n\t{\n\t\treturn _InterlockedDecrement((volatile long *)pValue);\n\t}\n\n\tinline unsigned atomic_compswap(volatile unsigned *pValue, unsigned comperand, unsigned value)\n\t{\n\t\treturn _InterlockedCompareExchange((volatile long *)pValue, (long)value, (long)comperand);\n\t}\n\n\tinline void sync_barrier()\n\t{\n\t\tMemoryBarrier();\n\t}\n#else\n\t#error missing atomic implementation for this compiler\n#endif\n\n#if defined(CONF_PLATFORM_MACOSX)\n\t/*\n\t\tuse semaphore provided by SDL on macosx\n\t*/\n#else\n\tclass semaphore\n\t{\n\t\tSEMAPHORE sem;\n\tpublic:\n\t\tsemaphore() { semaphore_init(&sem); }\n\t\t~semaphore() { semaphore_destroy(&sem); }\n\t\tvoid wait() { semaphore_wait(&sem); }\n\t\tvoid signal() { semaphore_signal(&sem); }\n\t};\n#endif\n\nclass lock\n{\n\tfriend class scope_lock;\n\n\tLOCK var;\n\n\tvoid take() { lock_wait(var); }\n\tvoid release() { lock_release(var); }\n\npublic:\n\tlock()\n\t{\n\t\tvar = lock_create();\n\t}\n\n\t~lock()\n\t{\n\t\tlock_destroy(var);\n\t}\n};\n\nclass scope_lock\n{\n\tlock *var;\npublic:\n\tscope_lock(lock *l)\n\t{\n\t\tvar = l;\n\t\tvar->take();\n\t}\n\n\t~scope_lock()\n\t{\n\t\tvar->release();\n\t}\n};\n"
  },
  {
    "path": "src/base/vmath.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef BASE_VMATH_H\n#define BASE_VMATH_H\n\n#include <math.h>\n\n#include \"math.h\"\t// mix\n\n// ------------------------------------\n\ntemplate<typename T>\nclass vector2_base\n{\npublic:\n\tunion { T x,u; };\n\tunion { T y,v; };\n\n\tvector2_base() {}\n\tvector2_base(float nx, float ny)\n\t{\n\t\tx = nx;\n\t\ty = ny;\n\t}\n\n\tvector2_base operator -() const { return vector2_base(-x, -y); }\n\tvector2_base operator -(const vector2_base &v) const { return vector2_base(x-v.x, y-v.y); }\n\tvector2_base operator +(const vector2_base &v) const { return vector2_base(x+v.x, y+v.y); }\n\tvector2_base operator *(const T v) const { return vector2_base(x*v, y*v); }\n\tvector2_base operator *(const vector2_base &v) const { return vector2_base(x*v.x, y*v.y); }\n\tvector2_base operator /(const T v) const { return vector3_base(x/v, y/v); }\n\tvector2_base operator /(const vector2_base &v) const { return vector2_base(x/v.x, y/v.y); }\n\n\tconst vector2_base &operator =(const vector2_base &v) { x = v.x; y = v.y; return *this; }\n\n\tconst vector2_base &operator +=(const vector2_base &v) { x += v.x; y += v.y; return *this; }\n\tconst vector2_base &operator -=(const vector2_base &v) { x -= v.x; y -= v.y; return *this; }\n\tconst vector2_base &operator *=(const T v) { x *= v; y *= v; return *this;\t}\n\tconst vector2_base &operator *=(const vector2_base &v) { x *= v.x; y *= v.y; return *this; }\n\tconst vector2_base &operator /=(const T v) { x /= v; y /= v; return *this;\t}\n\tconst vector2_base &operator /=(const vector2_base &v) { x /= v.x; y /= v.y; return *this; }\n\n\tbool operator ==(const vector2_base &v) const { return x == v.x && y == v.y; } //TODO: do this with an eps instead\n\n\toperator const T* () { return &x; }\n};\n\ntemplate<typename T>\ninline vector2_base<T> rotate(const vector2_base<T> &a, float angle)\n{\n\tangle = angle * pi / 180.0f;\n\tfloat s = sin(angle);\n\tfloat c = cos(angle);\n\treturn vector2_base<T>((T)(c*a.x - s*a.y), (T)(s*a.x + c*a.y));\n}\n\ntemplate<typename T>\ninline T length(const vector2_base<T> &a)\n{\n\treturn sqrtf(a.x*a.x + a.y*a.y);\n}\n\ntemplate<typename T>\ninline T distance(const vector2_base<T> a, const vector2_base<T> &b)\n{\n\treturn length(a-b);\n}\n\ntemplate<typename T>\ninline T dot(const vector2_base<T> a, const vector2_base<T> &b)\n{\n\treturn a.x*b.x + a.y*b.y;\n}\n\ntemplate<typename T>\ninline vector2_base<T> normalize(const vector2_base<T> &v)\n{\n\tT l = (T)(1.0f/sqrtf(v.x*v.x + v.y*v.y));\n\treturn vector2_base<T>(v.x*l, v.y*l);\n}\n\ntypedef vector2_base<float> vec2;\ntypedef vector2_base<bool> bvec2;\ntypedef vector2_base<int> ivec2;\n\ntemplate<typename T>\ninline vector2_base<T> closest_point_on_line(vector2_base<T> line_point0, vector2_base<T> line_point1, vector2_base<T> target_point)\n{\n\tvector2_base<T> c = target_point - line_point0;\n\tvector2_base<T> v = (line_point1 - line_point0);\n\tv = normalize(v);\n\tT d = length(line_point0-line_point1);\n\tT t = dot(v, c)/d;\n\treturn mix(line_point0, line_point1, clamp(t, (T)0, (T)1));\n\t/*\n\tif (t < 0) t = 0;\n\tif (t > 1.0f) return 1.0f;\n\treturn t;*/\n}\n\n// ------------------------------------\ntemplate<typename T>\nclass vector3_base\n{\npublic:\n\tunion { T x,r,h; };\n\tunion { T y,g,s; };\n\tunion { T z,b,v,l; };\n\n\tvector3_base() {}\n\tvector3_base(float nx, float ny, float nz)\n\t{\n\t\tx = nx;\n\t\ty = ny;\n\t\tz = nz;\n\t}\n\n\tconst vector3_base &operator =(const vector3_base &v) { x = v.x; y = v.y; z = v.z; return *this; }\n\n\tvector3_base operator -(const vector3_base &v) const { return vector3_base(x-v.x, y-v.y, z-v.z); }\n\tvector3_base operator -() const { return vector3_base(-x, -y, -z); }\n\tvector3_base operator +(const vector3_base &v) const { return vector3_base(x+v.x, y+v.y, z+v.z); }\n\tvector3_base operator *(const T v) const { return vector3_base(x*v, y*v, z*v); }\n\tvector3_base operator *(const vector3_base &v) const { return vector3_base(x*v.x, y*v.y, z*v.z); }\n\tvector3_base operator /(const T v) const { return vector3_base(x/v, y/v, z/v); }\n\tvector3_base operator /(const vector3_base &v) const { return vector3_base(x/v.x, y/v.y, z/v.z); }\n\n\tconst vector3_base &operator +=(const vector3_base &v) { x += v.x; y += v.y; z += v.z; return *this; }\n\tconst vector3_base &operator -=(const vector3_base &v) { x -= v.x; y -= v.y; z -= v.z; return *this; }\n\tconst vector3_base &operator *=(const T v) { x *= v; y *= v; z *= v; return *this;\t}\n\tconst vector3_base &operator *=(const vector3_base &v) { x *= v.x; y *= v.y; z *= v.z; return *this; }\n\tconst vector3_base &operator /=(const T v) { x /= v; y /= v; z /= v; return *this;\t}\n\tconst vector3_base &operator /=(const vector3_base &v) { x /= v.x; y /= v.y; z /= v.z; return *this; }\n\n\tbool operator ==(const vector3_base &v) const { return x == v.x && y == v.y && z == v.z; } //TODO: do this with an eps instead\n\n\toperator const T* () { return &x; }\n};\n\ntemplate<typename T>\ninline T length(const vector3_base<T> &a)\n{\n\treturn sqrtf(a.x*a.x + a.y*a.y + a.z*a.z);\n}\n\ntemplate<typename T>\ninline T distance(const vector3_base<T> &a, const vector3_base<T> &b)\n{\n\treturn length(a-b);\n}\n\ntemplate<typename T>\ninline T dot(const vector3_base<T> &a, const vector3_base<T> &b)\n{\n\treturn a.x*b.x + a.y*b.y + a.z*b.z;\n}\n\ntemplate<typename T>\ninline vector3_base<T> normalize(const vector3_base<T> &v)\n{\n\tT l = (T)(1.0f/sqrtf(v.x*v.x + v.y*v.y + v.z*v.z));\n\treturn vector3_base<T>(v.x*l, v.y*l, v.z*l);\n}\n\ntemplate<typename T>\ninline vector3_base<T> cross(const vector3_base<T> &a, const vector3_base<T> &b)\n{\n\treturn vector3_base<T>(\n\t\ta.y*b.z - a.z*b.y,\n\t\ta.z*b.x - a.x*b.z,\n\t\ta.x*b.y - a.y*b.x);\n}\n\ntypedef vector3_base<float> vec3;\ntypedef vector3_base<bool> bvec3;\ntypedef vector3_base<int> ivec3;\n\n// ------------------------------------\n\ntemplate<typename T>\nclass vector4_base\n{\npublic:\n\tunion { T x,r; };\n\tunion { T y,g; };\n\tunion { T z,b; };\n\tunion { T w,a; };\n\n\tvector4_base() {}\n\tvector4_base(float nx, float ny, float nz, float nw)\n\t{\n\t\tx = nx;\n\t\ty = ny;\n\t\tz = nz;\n\t\tw = nw;\n\t}\n\n\tvector4_base operator +(const vector4_base &v) const { return vector4_base(x+v.x, y+v.y, z+v.z, w+v.w); }\n\tvector4_base operator -(const vector4_base &v) const { return vector4_base(x-v.x, y-v.y, z-v.z, w-v.w); }\n\tvector4_base operator -() const { return vector4_base(-x, -y, -z, -w); }\n\tvector4_base operator *(const vector4_base &v) const { return vector4_base(x*v.x, y*v.y, z*v.z, w*v.w); }\n\tvector4_base operator *(const T v) const { return vector4_base(x*v, y*v, z*v, w*v); }\n\tvector4_base operator /(const vector4_base &v) const { return vector4_base(x/v.x, y/v.y, z/v.z, w/v.w); }\n\tvector4_base operator /(const T v) const { return vector4_base(x/v, y/v, z/v, w/v); }\n\n\tconst vector4_base &operator =(const vector4_base &v) { x = v.x; y = v.y; z = v.z; w = v.w; return *this; }\n\n\tconst vector4_base &operator +=(const vector4_base &v) { x += v.x; y += v.y; z += v.z; w += v.w; return *this; }\n\tconst vector4_base &operator -=(const vector4_base &v) { x -= v.x; y -= v.y; z -= v.z; w -= v.w; return *this; }\n\tconst vector4_base &operator *=(const T v) { x *= v; y *= v; z *= v; w *= v; return *this;\t}\n\tconst vector4_base &operator *=(const vector4_base &v) { x *= v.x; y *= v.y; z *= v.z; w *= v.w; return *this; }\n\tconst vector4_base &operator /=(const T v) { x /= v; y /= v; z /= v; w /= v; return *this;\t}\n\tconst vector4_base &operator /=(const vector4_base &v) { x /= v.x; y /= v.y; z /= v.z; w /= v.w; return *this; }\n\n\tbool operator ==(const vector4_base &v) const { return x == v.x && y == v.y && z == v.z && w == v.w; } //TODO: do this with an eps instead\n\n\toperator const T* () { return &x; }\n};\n\ntypedef vector4_base<float> vec4;\ntypedef vector4_base<bool> bvec4;\ntypedef vector4_base<int> ivec4;\n\n#endif\n"
  },
  {
    "path": "src/engine/client/backend_sdl.cpp",
    "content": "\n#include \"SDL.h\"\n#include \"SDL_opengl.h\"\n\n#include <base/tl/threading.h>\n\n#include \"graphics_threaded.h\"\n#include \"backend_sdl.h\"\n\n// ------------ CGraphicsBackend_Threaded\n\nvoid CGraphicsBackend_Threaded::ThreadFunc(void *pUser)\n{\n\t#ifdef CONF_PLATFORM_MACOSX\n\t\tCAutoreleasePool AutoreleasePool;\n\t#endif\n\tCGraphicsBackend_Threaded *pThis = (CGraphicsBackend_Threaded *)pUser;\n\n\twhile(!pThis->m_Shutdown)\n\t{\n\t\tpThis->m_Activity.wait();\n\t\tif(pThis->m_pBuffer)\n\t\t{\n\t\t\tpThis->m_pProcessor->RunBuffer(pThis->m_pBuffer);\n\t\t\tsync_barrier();\n\t\t\tpThis->m_pBuffer = 0x0;\n\t\t\tpThis->m_BufferDone.signal();\n\t\t}\n\t}\n}\n\nCGraphicsBackend_Threaded::CGraphicsBackend_Threaded()\n{\n\tm_pBuffer = 0x0;\n\tm_pProcessor = 0x0;\n\tm_pThread = 0x0;\n}\n\nvoid CGraphicsBackend_Threaded::StartProcessor(ICommandProcessor *pProcessor)\n{\n\tm_Shutdown = false;\n\tm_pProcessor = pProcessor;\n\tm_pThread = thread_create(ThreadFunc, this);\n\tm_BufferDone.signal();\n}\n\nvoid CGraphicsBackend_Threaded::StopProcessor()\n{\n\tm_Shutdown = true;\n\tm_Activity.signal();\n\tthread_wait(m_pThread);\n\tthread_destroy(m_pThread);\n}\n\nvoid CGraphicsBackend_Threaded::RunBuffer(CCommandBuffer *pBuffer)\n{\n\tWaitForIdle();\n\tm_pBuffer = pBuffer;\n\tm_Activity.signal();\n}\n\nbool CGraphicsBackend_Threaded::IsIdle() const\n{\n\treturn m_pBuffer == 0x0;\n}\n\nvoid CGraphicsBackend_Threaded::WaitForIdle()\n{\n\twhile(m_pBuffer != 0x0)\n\t\tm_BufferDone.wait();\n}\n\n\n// ------------ CCommandProcessorFragment_General\n\nvoid CCommandProcessorFragment_General::Cmd_Signal(const CCommandBuffer::SCommand_Signal *pCommand)\n{\n\tpCommand->m_pSemaphore->signal();\n}\n\nbool CCommandProcessorFragment_General::RunCommand(const CCommandBuffer::SCommand * pBaseCommand)\n{\n\tswitch(pBaseCommand->m_Cmd)\n\t{\n\tcase CCommandBuffer::CMD_NOP: break;\n\tcase CCommandBuffer::CMD_SIGNAL: Cmd_Signal(static_cast<const CCommandBuffer::SCommand_Signal *>(pBaseCommand)); break;\n\tdefault: return false;\n\t}\n\n\treturn true;\n}\n\n// ------------ CCommandProcessorFragment_OpenGL\n\nint CCommandProcessorFragment_OpenGL::TexFormatToOpenGLFormat(int TexFormat)\n{\n\tif(TexFormat == CCommandBuffer::TEXFORMAT_RGB) return GL_RGB;\n\tif(TexFormat == CCommandBuffer::TEXFORMAT_ALPHA) return GL_ALPHA;\n\tif(TexFormat == CCommandBuffer::TEXFORMAT_RGBA) return GL_RGBA;\n\treturn GL_RGBA;\n}\n\nunsigned char CCommandProcessorFragment_OpenGL::Sample(int w, int h, const unsigned char *pData, int u, int v, int Offset, int ScaleW, int ScaleH, int Bpp)\n{\n\tint Value = 0;\n\tfor(int x = 0; x < ScaleW; x++)\n\t\tfor(int y = 0; y < ScaleH; y++)\n\t\t\tValue += pData[((v+y)*w+(u+x))*Bpp+Offset];\n\treturn Value/(ScaleW*ScaleH);\n}\n\nvoid *CCommandProcessorFragment_OpenGL::Rescale(int Width, int Height, int NewWidth, int NewHeight, int Format, const unsigned char *pData)\n{\n\tunsigned char *pTmpData;\n\tint ScaleW = Width/NewWidth;\n\tint ScaleH = Height/NewHeight;\n\n\tint Bpp = 3;\n\tif(Format == CCommandBuffer::TEXFORMAT_RGBA)\n\t\tBpp = 4;\n\n\tpTmpData = (unsigned char *)mem_alloc(NewWidth*NewHeight*Bpp, 1);\n\n\tint c = 0;\n\tfor(int y = 0; y < NewHeight; y++)\n\t\tfor(int x = 0; x < NewWidth; x++, c++)\n\t\t{\n\t\t\tpTmpData[c*Bpp] = Sample(Width, Height, pData, x*ScaleW, y*ScaleH, 0, ScaleW, ScaleH, Bpp);\n\t\t\tpTmpData[c*Bpp+1] = Sample(Width, Height, pData, x*ScaleW, y*ScaleH, 1, ScaleW, ScaleH, Bpp);\n\t\t\tpTmpData[c*Bpp+2] = Sample(Width, Height, pData, x*ScaleW, y*ScaleH, 2, ScaleW, ScaleH, Bpp);\n\t\t\tif(Bpp == 4)\n\t\t\t\tpTmpData[c*Bpp+3] = Sample(Width, Height, pData, x*ScaleW, y*ScaleH, 3, ScaleW, ScaleH, Bpp);\n\t\t}\n\n\treturn pTmpData;\n}\n\nvoid CCommandProcessorFragment_OpenGL::SetState(const CCommandBuffer::SState &State)\n{\n\t// blend\n\tswitch(State.m_BlendMode)\n\t{\n\tcase CCommandBuffer::BLEND_NONE:\n\t\tglDisable(GL_BLEND);\n\t\tbreak;\n\tcase CCommandBuffer::BLEND_ALPHA:\n\t\tglEnable(GL_BLEND);\n\t\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\t\tbreak;\n\tcase CCommandBuffer::BLEND_ADDITIVE:\n\t\tglEnable(GL_BLEND);\n\t\tglBlendFunc(GL_SRC_ALPHA, GL_ONE);\n\t\tbreak;\n\tdefault:\n\t\tdbg_msg(\"render\", \"unknown blendmode %d\\n\", State.m_BlendMode);\n\t};\n\n\t// clip\n\tif(State.m_ClipEnable)\n\t{\n\t\tglScissor(State.m_ClipX, State.m_ClipY, State.m_ClipW, State.m_ClipH);\n\t\tglEnable(GL_SCISSOR_TEST);\n\t}\n\telse\n\t\tglDisable(GL_SCISSOR_TEST);\n\t\n\t// texture\n\tif(State.m_Texture >= 0 && State.m_Texture < CCommandBuffer::MAX_TEXTURES)\n\t{\n\t\tglEnable(GL_TEXTURE_2D);\n\t\tglBindTexture(GL_TEXTURE_2D, m_aTextures[State.m_Texture].m_Tex);\n\t}\n\telse\n\t\tglDisable(GL_TEXTURE_2D);\n\n\tswitch(State.m_WrapMode)\n\t{\n\tcase CCommandBuffer::WRAP_REPEAT:\n\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\n\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\n\t\tbreak;\n\tcase CCommandBuffer::WRAP_CLAMP:\n\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n\t\tbreak;\n\tdefault:\n\t\tdbg_msg(\"render\", \"unknown wrapmode %d\\n\", State.m_WrapMode);\n\t};\n\n\t// screen mapping\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tglOrtho(State.m_ScreenTL.x, State.m_ScreenBR.x, State.m_ScreenBR.y, State.m_ScreenTL.y, 1.0f, 10.f);\n}\n\nvoid CCommandProcessorFragment_OpenGL::Cmd_Init(const SCommand_Init *pCommand)\n{\n\tm_pTextureMemoryUsage = pCommand->m_pTextureMemoryUsage;\n}\n\nvoid CCommandProcessorFragment_OpenGL::Cmd_Texture_Update(const CCommandBuffer::SCommand_Texture_Update *pCommand)\n{\n\tglBindTexture(GL_TEXTURE_2D, m_aTextures[pCommand->m_Slot].m_Tex);\n\tglTexSubImage2D(GL_TEXTURE_2D, 0, pCommand->m_X, pCommand->m_Y, pCommand->m_Width, pCommand->m_Height,\n\t\tTexFormatToOpenGLFormat(pCommand->m_Format), GL_UNSIGNED_BYTE, pCommand->m_pData);\n\tmem_free(pCommand->m_pData);\n}\n\nvoid CCommandProcessorFragment_OpenGL::Cmd_Texture_Destroy(const CCommandBuffer::SCommand_Texture_Destroy *pCommand)\n{\n\tglDeleteTextures(1, &m_aTextures[pCommand->m_Slot].m_Tex);\n\t*m_pTextureMemoryUsage -= m_aTextures[pCommand->m_Slot].m_MemSize;\n}\n\nvoid CCommandProcessorFragment_OpenGL::Cmd_Texture_Create(const CCommandBuffer::SCommand_Texture_Create *pCommand)\n{\n\tint Width = pCommand->m_Width;\n\tint Height = pCommand->m_Height;\n\tvoid *pTexData = pCommand->m_pData;\n\n\t// resample if needed\n\tif(pCommand->m_Format == CCommandBuffer::TEXFORMAT_RGBA || pCommand->m_Format == CCommandBuffer::TEXFORMAT_RGB)\n\t{\n\t\tint MaxTexSize;\n\t\tglGetIntegerv(GL_MAX_TEXTURE_SIZE, &MaxTexSize);\n\t\tif(Width > MaxTexSize || Height > MaxTexSize)\n\t\t{\n\t\t\tdo\n\t\t\t{\n\t\t\t\tWidth>>=1;\n\t\t\t\tHeight>>=1;\n\t\t\t}\n\t\t\twhile(Width > MaxTexSize || Height > MaxTexSize);\n\n\t\t\tvoid *pTmpData = Rescale(pCommand->m_Width, pCommand->m_Height, Width, Height, pCommand->m_Format, static_cast<const unsigned char *>(pCommand->m_pData));\n\t\t\tmem_free(pTexData);\n\t\t\tpTexData = pTmpData;\n\t\t}\n\t\telse if(Width > 16 && Height > 16 && (pCommand->m_Flags&CCommandBuffer::TEXFLAG_QUALITY) == 0)\n\t\t{\n\t\t\tWidth>>=1;\n\t\t\tHeight>>=1;\n\n\t\t\tvoid *pTmpData = Rescale(pCommand->m_Width, pCommand->m_Height, Width, Height, pCommand->m_Format, static_cast<const unsigned char *>(pCommand->m_pData));\n\t\t\tmem_free(pTexData);\n\t\t\tpTexData = pTmpData;\n\t\t}\n\t}\n\n\tint Oglformat = TexFormatToOpenGLFormat(pCommand->m_Format);\n\tint StoreOglformat = TexFormatToOpenGLFormat(pCommand->m_StoreFormat);\n\n\tif(pCommand->m_Flags&CCommandBuffer::TEXFLAG_COMPRESSED)\n\t{\n\t\tswitch(StoreOglformat)\n\t\t{\n\t\t\tcase GL_RGB: StoreOglformat = GL_COMPRESSED_RGB_ARB; break;\n\t\t\tcase GL_ALPHA: StoreOglformat = GL_COMPRESSED_ALPHA_ARB; break;\n\t\t\tcase GL_RGBA: StoreOglformat = GL_COMPRESSED_RGBA_ARB; break;\n\t\t\tdefault: StoreOglformat = GL_COMPRESSED_RGBA_ARB;\n\t\t}\n\t}\n\tglGenTextures(1, &m_aTextures[pCommand->m_Slot].m_Tex);\n\tglBindTexture(GL_TEXTURE_2D, m_aTextures[pCommand->m_Slot].m_Tex);\n\n\tif(pCommand->m_Flags&CCommandBuffer::TEXFLAG_NOMIPMAPS)\n\t{\n\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\t\tglTexImage2D(GL_TEXTURE_2D, 0, StoreOglformat, Width, Height, 0, Oglformat, GL_UNSIGNED_BYTE, pTexData);\n\t}\n\telse\n\t{\n\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);\n\t\tgluBuild2DMipmaps(GL_TEXTURE_2D, StoreOglformat, Width, Height, Oglformat, GL_UNSIGNED_BYTE, pTexData);\n\t}\n\n\t// calculate memory usage\n\tm_aTextures[pCommand->m_Slot].m_MemSize = Width*Height*pCommand->m_PixelSize;\n\twhile(Width > 2 && Height > 2)\n\t{\n\t\tWidth>>=1;\n\t\tHeight>>=1;\n\t\tm_aTextures[pCommand->m_Slot].m_MemSize += Width*Height*pCommand->m_PixelSize;\n\t}\n\t*m_pTextureMemoryUsage += m_aTextures[pCommand->m_Slot].m_MemSize;\n\n\tmem_free(pTexData);\n}\n\nvoid CCommandProcessorFragment_OpenGL::Cmd_Clear(const CCommandBuffer::SCommand_Clear *pCommand)\n{\n\tglClearColor(pCommand->m_Color.r, pCommand->m_Color.g, pCommand->m_Color.b, 0.0f);\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n}\n\nvoid CCommandProcessorFragment_OpenGL::Cmd_Render(const CCommandBuffer::SCommand_Render *pCommand)\n{\n\tSetState(pCommand->m_State);\n\t\n\tglVertexPointer(3, GL_FLOAT, sizeof(CCommandBuffer::SVertex), (char*)pCommand->m_pVertices);\n\tglTexCoordPointer(2, GL_FLOAT, sizeof(CCommandBuffer::SVertex), (char*)pCommand->m_pVertices + sizeof(float)*3);\n\tglColorPointer(4, GL_FLOAT, sizeof(CCommandBuffer::SVertex), (char*)pCommand->m_pVertices + sizeof(float)*5);\n\tglEnableClientState(GL_VERTEX_ARRAY);\n\tglEnableClientState(GL_TEXTURE_COORD_ARRAY);\n\tglEnableClientState(GL_COLOR_ARRAY);\n\n\tswitch(pCommand->m_PrimType)\n\t{\n\tcase CCommandBuffer::PRIMTYPE_QUADS:\n\t\tglDrawArrays(GL_QUADS, 0, pCommand->m_PrimCount*4);\n\t\tbreak;\n\tcase CCommandBuffer::PRIMTYPE_LINES:\n\t\tglDrawArrays(GL_LINES, 0, pCommand->m_PrimCount*2);\n\t\tbreak;\n\tdefault:\n\t\tdbg_msg(\"render\", \"unknown primtype %d\\n\", pCommand->m_Cmd);\n\t};\n}\n\nvoid CCommandProcessorFragment_OpenGL::Cmd_Screenshot(const CCommandBuffer::SCommand_Screenshot *pCommand)\n{\n\t// fetch image data\n\tGLint aViewport[4] = {0,0,0,0};\n\tglGetIntegerv(GL_VIEWPORT, aViewport);\n\n\tint w = aViewport[2];\n\tint h = aViewport[3];\n\n\t// we allocate one more row to use when we are flipping the texture\n\tunsigned char *pPixelData = (unsigned char *)mem_alloc(w*(h+1)*3, 1);\n\tunsigned char *pTempRow = pPixelData+w*h*3;\n\n\t// fetch the pixels\n\tGLint Alignment;\n\tglGetIntegerv(GL_PACK_ALIGNMENT, &Alignment);\n\tglPixelStorei(GL_PACK_ALIGNMENT, 1);\n\tglReadPixels(0,0, w, h, GL_RGB, GL_UNSIGNED_BYTE, pPixelData);\n\tglPixelStorei(GL_PACK_ALIGNMENT, Alignment);\n\n\t// flip the pixel because opengl works from bottom left corner\n\tfor(int y = 0; y < h/2; y++)\n\t{\n\t\tmem_copy(pTempRow, pPixelData+y*w*3, w*3);\n\t\tmem_copy(pPixelData+y*w*3, pPixelData+(h-y-1)*w*3, w*3);\n\t\tmem_copy(pPixelData+(h-y-1)*w*3, pTempRow,w*3);\n\t}\n\n\t// fill in the information\n\tpCommand->m_pImage->m_Width = w;\n\tpCommand->m_pImage->m_Height = h;\n\tpCommand->m_pImage->m_Format = CImageInfo::FORMAT_RGB;\n\tpCommand->m_pImage->m_pData = pPixelData;\n}\n\nCCommandProcessorFragment_OpenGL::CCommandProcessorFragment_OpenGL()\n{\n\tmem_zero(m_aTextures, sizeof(m_aTextures));\n\tm_pTextureMemoryUsage = 0;\n}\n\nbool CCommandProcessorFragment_OpenGL::RunCommand(const CCommandBuffer::SCommand * pBaseCommand)\n{\n\tswitch(pBaseCommand->m_Cmd)\n\t{\n\tcase CMD_INIT: Cmd_Init(static_cast<const SCommand_Init *>(pBaseCommand)); break;\n\tcase CCommandBuffer::CMD_TEXTURE_CREATE: Cmd_Texture_Create(static_cast<const CCommandBuffer::SCommand_Texture_Create *>(pBaseCommand)); break;\n\tcase CCommandBuffer::CMD_TEXTURE_DESTROY: Cmd_Texture_Destroy(static_cast<const CCommandBuffer::SCommand_Texture_Destroy *>(pBaseCommand)); break;\n\tcase CCommandBuffer::CMD_TEXTURE_UPDATE: Cmd_Texture_Update(static_cast<const CCommandBuffer::SCommand_Texture_Update *>(pBaseCommand)); break;\n\tcase CCommandBuffer::CMD_CLEAR: Cmd_Clear(static_cast<const CCommandBuffer::SCommand_Clear *>(pBaseCommand)); break;\n\tcase CCommandBuffer::CMD_RENDER: Cmd_Render(static_cast<const CCommandBuffer::SCommand_Render *>(pBaseCommand)); break;\n\tcase CCommandBuffer::CMD_SCREENSHOT: Cmd_Screenshot(static_cast<const CCommandBuffer::SCommand_Screenshot *>(pBaseCommand)); break;\n\tdefault: return false;\n\t}\n\n\treturn true;\n}\n\n\n// ------------ CCommandProcessorFragment_SDL\n\nvoid CCommandProcessorFragment_SDL::Cmd_Init(const SCommand_Init *pCommand)\n{\n\tm_GLContext = pCommand->m_Context;\n\tGL_MakeCurrent(m_GLContext);\n\n\t// set some default settings\n\tglEnable(GL_BLEND);\n\tglDisable(GL_CULL_FACE);\n\tglDisable(GL_DEPTH_TEST);\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\n\tglAlphaFunc(GL_GREATER, 0);\n\tglEnable(GL_ALPHA_TEST);\n\tglDepthMask(0);\n}\n\nvoid CCommandProcessorFragment_SDL::Cmd_Shutdown(const SCommand_Shutdown *pCommand)\n{\n\tGL_ReleaseContext(m_GLContext);\n}\n\nvoid CCommandProcessorFragment_SDL::Cmd_Swap(const CCommandBuffer::SCommand_Swap *pCommand)\n{\n\tGL_SwapBuffers(m_GLContext);\n\n\tif(pCommand->m_Finish)\n\t\tglFinish();\n}\n\nvoid CCommandProcessorFragment_SDL::Cmd_VideoModes(const CCommandBuffer::SCommand_VideoModes *pCommand)\n{\n\t// TODO: fix this code on osx or windows\n\tSDL_Rect **ppModes = SDL_ListModes(NULL, SDL_OPENGL|SDL_GL_DOUBLEBUFFER|SDL_FULLSCREEN);\n\tif(ppModes == NULL)\n\t{\n\t\t// no modes\n\t\t*pCommand->m_pNumModes = 0;\n\t}\n\telse if(ppModes == (SDL_Rect**)-1)\n\t{\n\t\t// no modes\n\t\t*pCommand->m_pNumModes = 0;\n\t}\n\telse\n\t{\n\t\tint NumModes = 0;\n\t\tfor(int i = 0; ppModes[i]; ++i)\n\t\t{\n\t\t\tif(NumModes == pCommand->m_MaxModes)\n\t\t\t\tbreak;\n\t\t\tpCommand->m_pModes[NumModes].m_Width = ppModes[i]->w;\n\t\t\tpCommand->m_pModes[NumModes].m_Height = ppModes[i]->h;\n\t\t\tpCommand->m_pModes[NumModes].m_Red = 8;\n\t\t\tpCommand->m_pModes[NumModes].m_Green = 8;\n\t\t\tpCommand->m_pModes[NumModes].m_Blue = 8;\n\t\t\tNumModes++;\n\t\t}\n\n\t\t*pCommand->m_pNumModes = NumModes;\n\t}\n}\n\nCCommandProcessorFragment_SDL::CCommandProcessorFragment_SDL()\n{\n}\n\nbool CCommandProcessorFragment_SDL::RunCommand(const CCommandBuffer::SCommand *pBaseCommand)\n{\n\tswitch(pBaseCommand->m_Cmd)\n\t{\n\tcase CCommandBuffer::CMD_SWAP: Cmd_Swap(static_cast<const CCommandBuffer::SCommand_Swap *>(pBaseCommand)); break;\n\tcase CCommandBuffer::CMD_VIDEOMODES: Cmd_VideoModes(static_cast<const CCommandBuffer::SCommand_VideoModes *>(pBaseCommand)); break;\n\tcase CMD_INIT: Cmd_Init(static_cast<const SCommand_Init *>(pBaseCommand)); break;\n\tcase CMD_SHUTDOWN: Cmd_Shutdown(static_cast<const SCommand_Shutdown *>(pBaseCommand)); break;\n\tdefault: return false;\n\t}\n\n\treturn true;\n}\n\n// ------------ CCommandProcessor_SDL_OpenGL\n\nvoid CCommandProcessor_SDL_OpenGL::RunBuffer(CCommandBuffer *pBuffer)\n{\n\tunsigned CmdIndex = 0;\n\twhile(1)\n\t{\n\t\tconst CCommandBuffer::SCommand *pBaseCommand = pBuffer->GetCommand(&CmdIndex);\n\t\tif(pBaseCommand == 0x0)\n\t\t\tbreak;\n\t\t\n\t\tif(m_OpenGL.RunCommand(pBaseCommand))\n\t\t\tcontinue;\n\t\t\n\t\tif(m_SDL.RunCommand(pBaseCommand))\n\t\t\tcontinue;\n\n\t\tif(m_General.RunCommand(pBaseCommand))\n\t\t\tcontinue;\n\t\t\n\t\tdbg_msg(\"graphics\", \"unknown command %d\", pBaseCommand->m_Cmd);\n\t}\n}\n\n// ------------ CGraphicsBackend_SDL_OpenGL\n\nint CGraphicsBackend_SDL_OpenGL::Init(const char *pName, int *Width, int *Height, int FsaaSamples, int Flags, int *pDesktopWidth, int *pDesktopHeight)\n{\n\tif(!SDL_WasInit(SDL_INIT_VIDEO))\n\t{\n\t\tif(SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)\n\t\t{\n\t\t\tdbg_msg(\"gfx\", \"unable to init SDL video: %s\", SDL_GetError());\n\t\t\treturn -1;\n\t\t}\n\n\t\t#ifdef CONF_FAMILY_WINDOWS\n\t\t\tif(!getenv(\"SDL_VIDEO_WINDOW_POS\") && !getenv(\"SDL_VIDEO_CENTERED\")) // ignore_convention\n\t\t\t\tputenv(\"SDL_VIDEO_WINDOW_POS=8,27\"); // ignore_convention\n\t\t#endif\n\t}\n\n\tconst SDL_VideoInfo *pInfo = SDL_GetVideoInfo();\n\tSDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE); // prevent stuck mouse cursor sdl-bug when loosing fullscreen focus in windows\n\n\t// use current resolution as default\n\tif(*Width == 0 || *Height == 0)\n\t{\n\t\t*Width = pInfo->current_w;\n\t\t*Height = pInfo->current_h;\n\t}\n\n\t// store desktop resolution for settings reset button\n\t*pDesktopWidth = pInfo->current_w;\n\t*pDesktopHeight = pInfo->current_h;\n\n\t// set flags\n\tint SdlFlags = SDL_OPENGL;\n\tif(Flags&IGraphicsBackend::INITFLAG_RESIZABLE)\n\t\tSdlFlags |= SDL_RESIZABLE;\n\n\tif(pInfo->hw_available) // ignore_convention\n\t\tSdlFlags |= SDL_HWSURFACE;\n\telse\n\t\tSdlFlags |= SDL_SWSURFACE;\n\n\tif(pInfo->blit_hw) // ignore_convention\n\t\tSdlFlags |= SDL_HWACCEL;\n\n\tdbg_assert(!(Flags&IGraphicsBackend::INITFLAG_BORDERLESS)\n\t\t|| !(Flags&IGraphicsBackend::INITFLAG_FULLSCREEN),\n\t\t\"only one of borderless and fullscreen may be activated at the same time\");\n\n\tif(Flags&IGraphicsBackend::INITFLAG_BORDERLESS)\n\t\tSdlFlags |= SDL_NOFRAME;\n\n\tif(Flags&IGraphicsBackend::INITFLAG_FULLSCREEN)\n\t\tSdlFlags |= SDL_FULLSCREEN;\n\n\t// set gl attributes\n\tif(FsaaSamples)\n\t{\n\t\tSDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);\n\t\tSDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, FsaaSamples);\n\t}\n\telse\n\t{\n\t\tSDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);\n\t\tSDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);\n\t}\n\n\tSDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);\n\tSDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, Flags&IGraphicsBackend::INITFLAG_VSYNC ? 1 : 0);\n\n\t// set caption\n\tSDL_WM_SetCaption(pName, pName);\n\n\t// create window\n\tm_pScreenSurface = SDL_SetVideoMode(*Width, *Height, 0, SdlFlags);\n\tif(!m_pScreenSurface)\n\t{\n\t\tdbg_msg(\"gfx\", \"unable to set video mode: %s\", SDL_GetError());\n\t\t//*pCommand->m_pResult = -1;\n\t\treturn -1;\n\t}\t\t\n\n\tSDL_ShowCursor(0);\n\n\t// fetch gl contexts and release the context from this thread\n\tm_GLContext = GL_GetCurrentContext();\n\tGL_ReleaseContext(m_GLContext);\n\n\t// start the command processor\n\tm_pProcessor = new CCommandProcessor_SDL_OpenGL;\n\tStartProcessor(m_pProcessor);\n\n\t// issue init commands for OpenGL and SDL\n\tCCommandBuffer CmdBuffer(1024, 512);\n\tCCommandProcessorFragment_OpenGL::SCommand_Init CmdOpenGL;\n\tCmdOpenGL.m_pTextureMemoryUsage = &m_TextureMemoryUsage;\n\tCmdBuffer.AddCommand(CmdOpenGL);\n\tCCommandProcessorFragment_SDL::SCommand_Init CmdSDL;\n\tCmdSDL.m_Context = m_GLContext;\n\tCmdBuffer.AddCommand(CmdSDL);\n\tRunBuffer(&CmdBuffer);\n\tWaitForIdle();\n\n\t// return\n\treturn 0;\n}\n\nint CGraphicsBackend_SDL_OpenGL::Shutdown()\n{\n\t// issue a shutdown command\n\tCCommandBuffer CmdBuffer(1024, 512);\n\tCCommandProcessorFragment_SDL::SCommand_Shutdown Cmd;\n\tCmdBuffer.AddCommand(Cmd);\n\tRunBuffer(&CmdBuffer);\n\tWaitForIdle();\n\t\t\t\n\t// stop and delete the processor\n\tStopProcessor();\n\tdelete m_pProcessor;\n\tm_pProcessor = 0;\n\n\tSDL_QuitSubSystem(SDL_INIT_VIDEO);\n\treturn 0;\n}\n\nint CGraphicsBackend_SDL_OpenGL::MemoryUsage() const\n{\n\treturn m_TextureMemoryUsage;\n}\n\nvoid CGraphicsBackend_SDL_OpenGL::Minimize()\n{\n\tSDL_WM_IconifyWindow();\n}\n\nvoid CGraphicsBackend_SDL_OpenGL::Maximize()\n{\n\t// TODO: SDL\n}\n\nint CGraphicsBackend_SDL_OpenGL::WindowActive()\n{\n\treturn SDL_GetAppState()&SDL_APPINPUTFOCUS;\n}\n\nint CGraphicsBackend_SDL_OpenGL::WindowOpen()\n{\n\treturn SDL_GetAppState()&SDL_APPACTIVE;\n\n}\n\n\nIGraphicsBackend *CreateGraphicsBackend() { return new CGraphicsBackend_SDL_OpenGL; }\n"
  },
  {
    "path": "src/engine/client/backend_sdl.h",
    "content": "#pragma once\n\n#include \"graphics_threaded.h\"\n\n\n// platform dependent implementations for transfering render context from the main thread to the graphics thread\n// TODO: when SDL 1.3 comes, this can be removed\n#if defined(CONF_FAMILY_WINDOWS)\n\tstruct SGLContext\n\t{\n\t\tHDC m_hDC;\n\t\tHGLRC m_hGLRC;\n\t};\n\n\tstatic SGLContext GL_GetCurrentContext()\n\t{\n\t\tSGLContext Context;\n\t\tContext.m_hDC = wglGetCurrentDC();\n\t\tContext.m_hGLRC = wglGetCurrentContext();\n\t\treturn Context;\n\t}\n\n\tstatic void GL_MakeCurrent(const SGLContext &Context) { wglMakeCurrent(Context.m_hDC, Context.m_hGLRC); }\n\tstatic void GL_ReleaseContext(const SGLContext &Context) { wglMakeCurrent(NULL, NULL); }\n\tstatic void GL_SwapBuffers(const SGLContext &Context) { SwapBuffers(Context.m_hDC); }\n#elif defined(CONF_PLATFORM_MACOSX)\n\n\t#include <objc/objc-runtime.h>\n\n\tclass semaphore\n\t{\n\t\tSDL_sem *sem;\n\tpublic:\n\t\tsemaphore() { sem = SDL_CreateSemaphore(0); }\n\t\t~semaphore() { SDL_DestroySemaphore(sem); }\n\t\tvoid wait() { SDL_SemWait(sem); }\n\t\tvoid signal() { SDL_SemPost(sem); }\n\t};\n\n\tstruct SGLContext\n\t{\n\t\tid m_Context;\n\t};\n\n\tstatic SGLContext GL_GetCurrentContext()\n\t{\n\t\tSGLContext Context;\n\t\tClass NSOpenGLContextClass = (Class) objc_getClass(\"NSOpenGLContext\");\n\t\tSEL selector = sel_registerName(\"currentContext\");\n\t\tContext.m_Context = objc_msgSend((objc_object*) NSOpenGLContextClass, selector);\n\t\treturn Context;\n\t}\n\n\tstatic void GL_MakeCurrent(const SGLContext &Context)\n\t{\n\t\tSEL selector = sel_registerName(\"makeCurrentContext\");\n\t\tobjc_msgSend(Context.m_Context, selector);\n\t}\n\n\tstatic void GL_ReleaseContext(const SGLContext &Context)\n\t{\n\t\tClass NSOpenGLContextClass = (Class) objc_getClass(\"NSOpenGLContext\");\n\t\tSEL selector = sel_registerName(\"clearCurrentContext\");\n\t\tobjc_msgSend((objc_object*) NSOpenGLContextClass, selector);\n\t}\n\n\tstatic void GL_SwapBuffers(const SGLContext &Context)\n\t{\n\t\tSEL selector = sel_registerName(\"flushBuffer\");\n\t\tobjc_msgSend(Context.m_Context, selector);\n\t}\n\n\tclass CAutoreleasePool\n\t{\n\tprivate:\n\t\tid m_Pool;\n\n\tpublic:\n\t\tCAutoreleasePool()\n\t\t{\n\t\t\tClass NSAutoreleasePoolClass = (Class) objc_getClass(\"NSAutoreleasePool\");\n\t\t\tm_Pool = class_createInstance(NSAutoreleasePoolClass, 0);\n\t\t\tSEL selector = sel_registerName(\"init\");\n\t\t\tobjc_msgSend(m_Pool, selector);\n\t\t}\n\n\t\t~CAutoreleasePool()\n\t\t{\n\t\t\tSEL selector = sel_registerName(\"drain\");\n\t\t\tobjc_msgSend(m_Pool, selector);\n\t\t}\n\t};\t\t\t\t\t\t\t\n\n#elif defined(CONF_FAMILY_UNIX)\n\n\t#include <GL/glx.h>\n\n\tstruct SGLContext\n\t{\n\t\tDisplay *m_pDisplay;\n\t\tGLXDrawable m_Drawable;\n\t\tGLXContext m_Context;\n\t};\n\n\tstatic SGLContext GL_GetCurrentContext()\n\t{\n\t\tSGLContext Context;\n\t\tContext.m_pDisplay = glXGetCurrentDisplay();\n\t\tContext.m_Drawable = glXGetCurrentDrawable();\n\t\tContext.m_Context = glXGetCurrentContext();\n\t\treturn Context;\n\t}\n\n\tstatic void GL_MakeCurrent(const SGLContext &Context) { glXMakeCurrent(Context.m_pDisplay, Context.m_Drawable, Context.m_Context); }\n\tstatic void GL_ReleaseContext(const SGLContext &Context) { glXMakeCurrent(Context.m_pDisplay, None, 0x0); }\n\tstatic void GL_SwapBuffers(const SGLContext &Context) { glXSwapBuffers(Context.m_pDisplay, Context.m_Drawable); }\n#else\n\t#error missing implementation\n#endif\n\n\n// basic threaded backend, abstract, missing init and shutdown functions\nclass CGraphicsBackend_Threaded : public IGraphicsBackend\n{\npublic:\n\t// constructed on the main thread, the rest of the functions is runned on the render thread\n\tclass ICommandProcessor\n\t{\n\tpublic:\n\t\tvirtual ~ICommandProcessor() {}\n\t\tvirtual void RunBuffer(CCommandBuffer *pBuffer) = 0;\n\t};\n\n\tCGraphicsBackend_Threaded();\n\n\tvirtual void RunBuffer(CCommandBuffer *pBuffer);\n\tvirtual bool IsIdle() const;\n\tvirtual void WaitForIdle();\n\t\t\nprotected:\n\tvoid StartProcessor(ICommandProcessor *pProcessor);\n\tvoid StopProcessor();\n\nprivate:\n\tICommandProcessor *m_pProcessor;\n\tCCommandBuffer * volatile m_pBuffer;\n\tvolatile bool m_Shutdown;\n\tsemaphore m_Activity;\n\tsemaphore m_BufferDone;\n\tvoid *m_pThread;\n\n\tstatic void ThreadFunc(void *pUser);\n};\n\n// takes care of implementation independent operations\nclass CCommandProcessorFragment_General\n{\n\tvoid Cmd_Nop();\n\tvoid Cmd_Signal(const CCommandBuffer::SCommand_Signal *pCommand);\npublic:\n\tbool RunCommand(const CCommandBuffer::SCommand * pBaseCommand);\n};\n\n// takes care of opengl related rendering\nclass CCommandProcessorFragment_OpenGL\n{\n\tstruct CTexture\n\t{\n\t\tGLuint m_Tex;\n\t\tint m_MemSize;\n\t};\n\tCTexture m_aTextures[CCommandBuffer::MAX_TEXTURES];\n\tvolatile int *m_pTextureMemoryUsage;\n\npublic:\n\tenum\n\t{\n\t\tCMD_INIT = CCommandBuffer::CMDGROUP_PLATFORM_OPENGL,\n\t};\n\n\tstruct SCommand_Init : public CCommandBuffer::SCommand\n\t{\n\t\tSCommand_Init() : SCommand(CMD_INIT) {}\n\t\tvolatile int *m_pTextureMemoryUsage;\n\t};\n\nprivate:\n\tstatic int TexFormatToOpenGLFormat(int TexFormat);\n\tstatic unsigned char Sample(int w, int h, const unsigned char *pData, int u, int v, int Offset, int ScaleW, int ScaleH, int Bpp);\n\tstatic void *Rescale(int Width, int Height, int NewWidth, int NewHeight, int Format, const unsigned char *pData);\n\n\tvoid SetState(const CCommandBuffer::SState &State);\n\n\tvoid Cmd_Init(const SCommand_Init *pCommand);\n\tvoid Cmd_Texture_Update(const CCommandBuffer::SCommand_Texture_Update *pCommand);\n\tvoid Cmd_Texture_Destroy(const CCommandBuffer::SCommand_Texture_Destroy *pCommand);\n\tvoid Cmd_Texture_Create(const CCommandBuffer::SCommand_Texture_Create *pCommand);\n\tvoid Cmd_Clear(const CCommandBuffer::SCommand_Clear *pCommand);\n\tvoid Cmd_Render(const CCommandBuffer::SCommand_Render *pCommand);\n\tvoid Cmd_Screenshot(const CCommandBuffer::SCommand_Screenshot *pCommand);\n\npublic:\n\tCCommandProcessorFragment_OpenGL();\n\n\tbool RunCommand(const CCommandBuffer::SCommand * pBaseCommand);\n};\n\n// takes care of sdl related commands\nclass CCommandProcessorFragment_SDL\n{\n\t// SDL stuff\n\tSGLContext m_GLContext;\npublic:\n\tenum\n\t{\n\t\tCMD_INIT = CCommandBuffer::CMDGROUP_PLATFORM_SDL,\n\t\tCMD_SHUTDOWN,\n\t};\n\n\tstruct SCommand_Init : public CCommandBuffer::SCommand\n\t{\n\t\tSCommand_Init() : SCommand(CMD_INIT) {}\n\t\tSGLContext m_Context;\n\t};\n\n\tstruct SCommand_Shutdown : public CCommandBuffer::SCommand\n\t{\n\t\tSCommand_Shutdown() : SCommand(CMD_SHUTDOWN) {}\n\t};\n\nprivate:\n\tvoid Cmd_Init(const SCommand_Init *pCommand);\n\tvoid Cmd_Shutdown(const SCommand_Shutdown *pCommand);\n\tvoid Cmd_Swap(const CCommandBuffer::SCommand_Swap *pCommand);\n\tvoid Cmd_VideoModes(const CCommandBuffer::SCommand_VideoModes *pCommand);\npublic:\n\tCCommandProcessorFragment_SDL();\n\n\tbool RunCommand(const CCommandBuffer::SCommand *pBaseCommand);\n};\n\n// command processor impelementation, uses the fragments to combine into one processor\nclass CCommandProcessor_SDL_OpenGL : public CGraphicsBackend_Threaded::ICommandProcessor\n{\n \tCCommandProcessorFragment_OpenGL m_OpenGL;\n \tCCommandProcessorFragment_SDL m_SDL;\n \tCCommandProcessorFragment_General m_General;\n public:\n\tvirtual void RunBuffer(CCommandBuffer *pBuffer);\n};\n\n// graphics backend implemented with SDL and OpenGL\nclass CGraphicsBackend_SDL_OpenGL : public CGraphicsBackend_Threaded\n{\n\tSDL_Surface *m_pScreenSurface;\n\tICommandProcessor *m_pProcessor;\n\tSGLContext m_GLContext;\n\tvolatile int m_TextureMemoryUsage;\npublic:\n\tvirtual int Init(const char *pName, int *Width, int *Height, int FsaaSamples, int Flags, int *pDesktopWidth, int *pDesktopHeight);\n\tvirtual int Shutdown();\n\n\tvirtual int MemoryUsage() const;\n\n\tvirtual void Minimize();\n\tvirtual void Maximize();\n\tvirtual int WindowActive();\n\tvirtual int WindowOpen();\n};\n"
  },
  {
    "path": "src/engine/client/client.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <new>\n\n#include <stdlib.h> // qsort\n#include <stdarg.h>\n\n#include <base/math.h>\n#include <base/system.h>\n\n#include <engine/client.h>\n#include <engine/config.h>\n#include <engine/console.h>\n#include <engine/editor.h>\n#include <engine/engine.h>\n#include <engine/graphics.h>\n#include <engine/input.h>\n#include <engine/keys.h>\n#include <engine/map.h>\n#include <engine/masterserver.h>\n#include <engine/serverbrowser.h>\n#include <engine/sound.h>\n#include <engine/storage.h>\n#include <engine/textrender.h>\n\n#include <engine/shared/config.h>\n#include <engine/shared/compression.h>\n#include <engine/shared/datafile.h>\n#include <engine/shared/demo.h>\n#include <engine/shared/filecollection.h>\n#include <engine/shared/mapchecker.h>\n#include <engine/shared/network.h>\n#include <engine/shared/packer.h>\n#include <engine/shared/protocol.h>\n#include <engine/shared/ringbuffer.h>\n#include <engine/shared/snapshot.h>\n\n#include <game/version.h>\n\n#include <mastersrv/mastersrv.h>\n#include <versionsrv/versionsrv.h>\n\n#include \"friends.h\"\n#include \"serverbrowser.h\"\n#include \"client.h\"\n\n#if defined(CONF_FAMILY_WINDOWS)\n\t#define _WIN32_WINNT 0x0501\n\t#define WIN32_LEAN_AND_MEAN\n\t#include <windows.h>\n#endif\n\n#include \"SDL.h\"\n#ifdef main\n#undef main\n#endif\n\nvoid CGraph::Init(float Min, float Max)\n{\n\tm_Min = Min;\n\tm_Max = Max;\n\tm_Index = 0;\n}\n\nvoid CGraph::ScaleMax()\n{\n\tint i = 0;\n\tm_Max = 0;\n\tfor(i = 0; i < MAX_VALUES; i++)\n\t{\n\t\tif(m_aValues[i] > m_Max)\n\t\t\tm_Max = m_aValues[i];\n\t}\n}\n\nvoid CGraph::ScaleMin()\n{\n\tint i = 0;\n\tm_Min = m_Max;\n\tfor(i = 0; i < MAX_VALUES; i++)\n\t{\n\t\tif(m_aValues[i] < m_Min)\n\t\t\tm_Min = m_aValues[i];\n\t}\n}\n\nvoid CGraph::Add(float v, float r, float g, float b)\n{\n\tm_Index = (m_Index+1)&(MAX_VALUES-1);\n\tm_aValues[m_Index] = v;\n\tm_aColors[m_Index][0] = r;\n\tm_aColors[m_Index][1] = g;\n\tm_aColors[m_Index][2] = b;\n}\n\nvoid CGraph::Render(IGraphics *pGraphics, IGraphics::CTextureHandle FontTexture, float x, float y, float w, float h, const char *pDescription)\n{\n\t//m_pGraphics->BlendNormal();\n\n\n\tpGraphics->TextureClear();\n\n\tpGraphics->QuadsBegin();\n\tpGraphics->SetColor(0, 0, 0, 0.75f);\n\tIGraphics::CQuadItem QuadItem(x, y, w, h);\n\tpGraphics->QuadsDrawTL(&QuadItem, 1);\n\tpGraphics->QuadsEnd();\n\n\tpGraphics->LinesBegin();\n\tpGraphics->SetColor(0.95f, 0.95f, 0.95f, 1.00f);\n\tIGraphics::CLineItem LineItem(x, y+h/2, x+w, y+h/2);\n\tpGraphics->LinesDraw(&LineItem, 1);\n\tpGraphics->SetColor(0.5f, 0.5f, 0.5f, 0.75f);\n\tIGraphics::CLineItem Array[2] = {\n\t\tIGraphics::CLineItem(x, y+(h*3)/4, x+w, y+(h*3)/4),\n\t\tIGraphics::CLineItem(x, y+h/4, x+w, y+h/4)};\n\tpGraphics->LinesDraw(Array, 2);\n\tfor(int i = 1; i < MAX_VALUES; i++)\n\t{\n\t\tfloat a0 = (i-1)/(float)MAX_VALUES;\n\t\tfloat a1 = i/(float)MAX_VALUES;\n\t\tint i0 = (m_Index+i-1)&(MAX_VALUES-1);\n\t\tint i1 = (m_Index+i)&(MAX_VALUES-1);\n\n\t\tfloat v0 = (m_aValues[i0]-m_Min) / (m_Max-m_Min);\n\t\tfloat v1 = (m_aValues[i1]-m_Min) / (m_Max-m_Min);\n\n\t\tIGraphics::CColorVertex Array[2] = {\n\t\t\tIGraphics::CColorVertex(0, m_aColors[i0][0], m_aColors[i0][1], m_aColors[i0][2], 0.75f),\n\t\t\tIGraphics::CColorVertex(1, m_aColors[i1][0], m_aColors[i1][1], m_aColors[i1][2], 0.75f)};\n\t\tpGraphics->SetColorVertex(Array, 2);\n\t\tIGraphics::CLineItem LineItem(x+a0*w, y+h-v0*h, x+a1*w, y+h-v1*h);\n\t\tpGraphics->LinesDraw(&LineItem, 1);\n\n\t}\n\tpGraphics->LinesEnd();\n\n\tpGraphics->TextureSet(FontTexture);\n\tpGraphics->QuadsBegin();\n\tpGraphics->QuadsText(x+2, y+h-16, 16, pDescription);\n\n\tchar aBuf[32];\n\tstr_format(aBuf, sizeof(aBuf), \"%.2f\", m_Max);\n\tpGraphics->QuadsText(x+w-8*str_length(aBuf)-8, y+2, 16, aBuf);\n\n\tstr_format(aBuf, sizeof(aBuf), \"%.2f\", m_Min);\n\tpGraphics->QuadsText(x+w-8*str_length(aBuf)-8, y+h-16, 16, aBuf);\n\tpGraphics->QuadsEnd();\n}\n\n\nvoid CSmoothTime::Init(int64 Target)\n{\n\tm_Snap = time_get();\n\tm_Current = Target;\n\tm_Target = Target;\n\tm_aAdjustSpeed[0] = 0.3f;\n\tm_aAdjustSpeed[1] = 0.3f;\n\tm_Graph.Init(0.0f, 0.5f);\n}\n\nvoid CSmoothTime::SetAdjustSpeed(int Direction, float Value)\n{\n\tm_aAdjustSpeed[Direction] = Value;\n}\n\nint64 CSmoothTime::Get(int64 Now)\n{\n\tint64 c = m_Current + (Now - m_Snap);\n\tint64 t = m_Target + (Now - m_Snap);\n\n\t// it's faster to adjust upward instead of downward\n\t// we might need to adjust these abit\n\n\tfloat AdjustSpeed = m_aAdjustSpeed[0];\n\tif(t > c)\n\t\tAdjustSpeed = m_aAdjustSpeed[1];\n\n\tfloat a = ((Now-m_Snap)/(float)time_freq()) * AdjustSpeed;\n\tif(a > 1.0f)\n\t\ta = 1.0f;\n\n\tint64 r = c + (int64)((t-c)*a);\n\n\tm_Graph.Add(a+0.5f,1,1,1);\n\n\treturn r;\n}\n\nvoid CSmoothTime::UpdateInt(int64 Target)\n{\n\tint64 Now = time_get();\n\tm_Current = Get(Now);\n\tm_Snap = Now;\n\tm_Target = Target;\n}\n\nvoid CSmoothTime::Update(CGraph *pGraph, int64 Target, int TimeLeft, int AdjustDirection)\n{\n\tint UpdateTimer = 1;\n\n\tif(TimeLeft < 0)\n\t{\n\t\tint IsSpike = 0;\n\t\tif(TimeLeft < -50)\n\t\t{\n\t\t\tIsSpike = 1;\n\n\t\t\tm_SpikeCounter += 5;\n\t\t\tif(m_SpikeCounter > 50)\n\t\t\t\tm_SpikeCounter = 50;\n\t\t}\n\n\t\tif(IsSpike && m_SpikeCounter < 15)\n\t\t{\n\t\t\t// ignore this ping spike\n\t\t\tUpdateTimer = 0;\n\t\t\tpGraph->Add(TimeLeft, 1,1,0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpGraph->Add(TimeLeft, 1,0,0);\n\t\t\tif(m_aAdjustSpeed[AdjustDirection] < 30.0f)\n\t\t\t\tm_aAdjustSpeed[AdjustDirection] *= 2.0f;\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(m_SpikeCounter)\n\t\t\tm_SpikeCounter--;\n\n\t\tpGraph->Add(TimeLeft, 0,1,0);\n\n\t\tm_aAdjustSpeed[AdjustDirection] *= 0.95f;\n\t\tif(m_aAdjustSpeed[AdjustDirection] < 2.0f)\n\t\t\tm_aAdjustSpeed[AdjustDirection] = 2.0f;\n\t}\n\n\tif(UpdateTimer)\n\t\tUpdateInt(Target);\n}\n\n\nCClient::CClient() : m_DemoPlayer(&m_SnapshotDelta), m_DemoRecorder(&m_SnapshotDelta)\n{\n\tm_pEditor = 0;\n\tm_pInput = 0;\n\tm_pGraphics = 0;\n\tm_pSound = 0;\n\tm_pGameClient = 0;\n\tm_pMap = 0;\n\tm_pConsole = 0;\n\n\tm_RenderFrameTime = 0.0001f;\n\tm_RenderFrameTimeLow = 1.0f;\n\tm_RenderFrameTimeHigh = 0.0f;\n\tm_RenderFrames = 0;\n\tm_LastRenderTime = time_get();\n\n\tm_GameTickSpeed = SERVER_TICK_SPEED;\n\n\tm_WindowMustRefocus = 0;\n\tm_SnapCrcErrors = 0;\n\tm_AutoScreenshotRecycle = false;\n\tm_EditorActive = false;\n\n\tm_AckGameTick = -1;\n\tm_CurrentRecvTick = 0;\n\tm_RconAuthed = 0;\n\n\t// version-checking\n\tm_aVersionStr[0] = '0';\n\tm_aVersionStr[1] = 0;\n\n\t// pinging\n\tm_PingStartTime = 0;\n\n\t//\n\tm_aCurrentMap[0] = 0;\n\tm_CurrentMapCrc = 0;\n\n\t//\n\tm_aCmdConnect[0] = 0;\n\n\t// map download\n\tm_aMapdownloadFilename[0] = 0;\n\tm_aMapdownloadName[0] = 0;\n\tm_MapdownloadFile = 0;\n\tm_MapdownloadChunk = 0;\n\tm_MapdownloadCrc = 0;\n\tm_MapdownloadAmount = -1;\n\tm_MapdownloadTotalsize = -1;\n\n\tm_CurrentServerInfoRequestTime = -1;\n\n\tm_CurrentInput = 0;\n\n\tm_State = IClient::STATE_OFFLINE;\n\tm_aServerAddressStr[0] = 0;\n\n\tmem_zero(m_aSnapshots, sizeof(m_aSnapshots));\n\tm_SnapshotStorage.Init();\n\tm_RecivedSnapshots = 0;\n\n\tm_VersionInfo.m_State = CVersionInfo::STATE_INIT;\n}\n\n// ----- send functions -----\nint CClient::SendMsg(CMsgPacker *pMsg, int Flags)\n{\n\tCNetChunk Packet;\n\n\tif(State() == IClient::STATE_OFFLINE)\n\t\treturn 0;\n\n\tmem_zero(&Packet, sizeof(CNetChunk));\n\tPacket.m_ClientID = 0;\n\tPacket.m_pData = pMsg->Data();\n\tPacket.m_DataSize = pMsg->Size();\n\n\tif(Flags&MSGFLAG_VITAL)\n\t\tPacket.m_Flags |= NETSENDFLAG_VITAL;\n\tif(Flags&MSGFLAG_FLUSH)\n\t\tPacket.m_Flags |= NETSENDFLAG_FLUSH;\n\n\tif(Flags&MSGFLAG_RECORD)\n\t{\n\t\tif(m_DemoRecorder.IsRecording())\n\t\t\tm_DemoRecorder.RecordMessage(Packet.m_pData, Packet.m_DataSize);\n\t}\n\n\tif(!(Flags&MSGFLAG_NOSEND))\n\t\tm_NetClient.Send(&Packet);\n\treturn 0;\n}\n\nvoid CClient::SendInfo()\n{\n\tCMsgPacker Msg(NETMSG_INFO, true);\n\tMsg.AddString(GameClient()->NetVersion(), 128);\n\tMsg.AddString(g_Config.m_Password, 128);\n\tSendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH);\n}\n\n\nvoid CClient::SendEnterGame()\n{\n\tCMsgPacker Msg(NETMSG_ENTERGAME, true);\n\tSendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH);\n}\n\nvoid CClient::SendReady()\n{\n\tCMsgPacker Msg(NETMSG_READY, true);\n\tSendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH);\n}\n\nvoid CClient::RconAuth(const char *pName, const char *pPassword)\n{\n\tif(RconAuthed())\n\t\treturn;\n\n\tCMsgPacker Msg(NETMSG_RCON_AUTH, true);\n\tMsg.AddString(pPassword, 32);\n\tSendMsg(&Msg, MSGFLAG_VITAL);\n}\n\nvoid CClient::Rcon(const char *pCmd)\n{\n\tCMsgPacker Msg(NETMSG_RCON_CMD, true);\n\tMsg.AddString(pCmd, 256);\n\tSendMsg(&Msg, MSGFLAG_VITAL);\n}\n\nbool CClient::ConnectionProblems()\n{\n\treturn m_NetClient.GotProblems() != 0;\n}\n\nvoid CClient::DirectInput(int *pInput, int Size)\n{\n\tCMsgPacker Msg(NETMSG_INPUT, true);\n\tMsg.AddInt(m_AckGameTick);\n\tMsg.AddInt(m_PredTick);\n\tMsg.AddInt(Size);\n\n\tfor(int i = 0; i < Size/4; i++)\n\t\tMsg.AddInt(pInput[i]);\n\n\tSendMsg(&Msg, 0);\n}\n\n\nvoid CClient::SendInput()\n{\n\tint64 Now = time_get();\n\n\tif(m_PredTick <= 0)\n\t\treturn;\n\n\t// fetch input\n\tint Size = GameClient()->OnSnapInput(m_aInputs[m_CurrentInput].m_aData);\n\n\tif(!Size)\n\t\treturn;\n\n\t// pack input\n\tCMsgPacker Msg(NETMSG_INPUT, true);\n\tMsg.AddInt(m_AckGameTick);\n\tMsg.AddInt(m_PredTick);\n\tMsg.AddInt(Size);\n\n\tm_aInputs[m_CurrentInput].m_Tick = m_PredTick;\n\tm_aInputs[m_CurrentInput].m_PredictedTime = m_PredictedTime.Get(Now);\n\tm_aInputs[m_CurrentInput].m_Time = Now;\n\n\t// pack it\n\tfor(int i = 0; i < Size/4; i++)\n\t\tMsg.AddInt(m_aInputs[m_CurrentInput].m_aData[i]);\n\n\tm_CurrentInput++;\n\tm_CurrentInput%=200;\n\n\tSendMsg(&Msg, MSGFLAG_FLUSH);\n}\n\nconst char *CClient::LatestVersion()\n{\n\treturn m_aVersionStr;\n}\n\n// TODO: OPT: do this alot smarter!\nint *CClient::GetInput(int Tick)\n{\n\tint Best = -1;\n\tfor(int i = 0; i < 200; i++)\n\t{\n\t\tif(m_aInputs[i].m_Tick <= Tick && (Best == -1 || m_aInputs[Best].m_Tick < m_aInputs[i].m_Tick))\n\t\t\tBest = i;\n\t}\n\n\tif(Best != -1)\n\t\treturn (int *)m_aInputs[Best].m_aData;\n\treturn 0;\n}\n\n// ------ state handling -----\nvoid CClient::SetState(int s)\n{\n\tif(m_State == IClient::STATE_QUITING)\n\t\treturn;\n\n\tint Old = m_State;\n\tif(g_Config.m_Debug)\n\t{\n\t\tchar aBuf[128];\n\t\tstr_format(aBuf, sizeof(aBuf), \"state change. last=%d current=%d\", m_State, s);\n\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"client\", aBuf);\n\t}\n\tm_State = s;\n\tif(Old != s)\n\t\tGameClient()->OnStateChange(m_State, Old);\n}\n\n// called when the map is loaded and we should init for a new round\nvoid CClient::OnEnterGame()\n{\n\t// reset input\n\tint i;\n\tfor(i = 0; i < 200; i++)\n\t\tm_aInputs[i].m_Tick = -1;\n\tm_CurrentInput = 0;\n\n\t// reset snapshots\n\tm_aSnapshots[SNAP_CURRENT] = 0;\n\tm_aSnapshots[SNAP_PREV] = 0;\n\tm_SnapshotStorage.PurgeAll();\n\tm_RecivedSnapshots = 0;\n\tm_SnapshotParts = 0;\n\tm_PredTick = 0;\n\tm_CurrentRecvTick = 0;\n\tm_CurGameTick = 0;\n\tm_PrevGameTick = 0;\n\tm_CurMenuTick = 0;\n}\n\nvoid CClient::EnterGame()\n{\n\tif(State() == IClient::STATE_DEMOPLAYBACK)\n\t\treturn;\n\n\t// now we will wait for two snapshots\n\t// to finish the connection\n\tSendEnterGame();\n\tOnEnterGame();\n}\n\nvoid CClient::Connect(const char *pAddress)\n{\n\tchar aBuf[512];\n\tint Port = 8303;\n\n\tDisconnect();\n\n\tstr_copy(m_aServerAddressStr, pAddress, sizeof(m_aServerAddressStr));\n\n\tstr_format(aBuf, sizeof(aBuf), \"connecting to '%s'\", m_aServerAddressStr);\n\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"client\", aBuf);\n\n\tServerInfoRequest();\n\n\tif(net_addr_from_str(&m_ServerAddress, m_aServerAddressStr) != 0 && net_host_lookup(m_aServerAddressStr, &m_ServerAddress, m_NetClient.NetType()) != 0)\n\t{\n\t\tchar aBufMsg[256];\n\t\tstr_format(aBufMsg, sizeof(aBufMsg), \"could not find the address of %s, connecting to localhost\", aBuf);\n\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"client\", aBufMsg);\n\t\tnet_host_lookup(\"localhost\", &m_ServerAddress, m_NetClient.NetType());\n\t}\n\n\tm_RconAuthed = 0;\n\tif(m_ServerAddress.port == 0)\n\t\tm_ServerAddress.port = Port;\n\tm_NetClient.Connect(&m_ServerAddress);\n\tSetState(IClient::STATE_CONNECTING);\n\n\tif(m_DemoRecorder.IsRecording())\n\t\tDemoRecorder_Stop();\n\n\tm_InputtimeMarginGraph.Init(-150.0f, 150.0f);\n\tm_GametimeMarginGraph.Init(-150.0f, 150.0f);\n}\n\nvoid CClient::DisconnectWithReason(const char *pReason)\n{\n\tchar aBuf[512];\n\tstr_format(aBuf, sizeof(aBuf), \"disconnecting. reason='%s'\", pReason?pReason:\"unknown\");\n\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"client\", aBuf);\n\n\t// stop demo playback and recorder\n\tm_DemoPlayer.Stop();\n\tDemoRecorder_Stop();\n\n\t//\n\tm_RconAuthed = 0;\n\tm_UseTempRconCommands = 0;\n\tm_pConsole->DeregisterTempAll();\n\tm_NetClient.Disconnect(pReason);\n\tSetState(IClient::STATE_OFFLINE);\n\tm_pMap->Unload();\n\n\t// disable all downloads\n\tm_MapdownloadChunk = 0;\n\tif(m_MapdownloadFile)\n\t\tio_close(m_MapdownloadFile);\n\tm_MapdownloadFile = 0;\n\tm_MapdownloadCrc = 0;\n\tm_MapdownloadTotalsize = -1;\n\tm_MapdownloadAmount = 0;\n\n\t// clear the current server info\n\tmem_zero(&m_CurrentServerInfo, sizeof(m_CurrentServerInfo));\n\tmem_zero(&m_ServerAddress, sizeof(m_ServerAddress));\n\n\t// clear snapshots\n\tm_aSnapshots[SNAP_CURRENT] = 0;\n\tm_aSnapshots[SNAP_PREV] = 0;\n\tm_RecivedSnapshots = 0;\n}\n\nvoid CClient::Disconnect()\n{\n\tDisconnectWithReason(0);\n}\n\n\nvoid CClient::GetServerInfo(CServerInfo *pServerInfo)\n{\n\tmem_copy(pServerInfo, &m_CurrentServerInfo, sizeof(m_CurrentServerInfo));\n}\n\nvoid CClient::ServerInfoRequest()\n{\n\tmem_zero(&m_CurrentServerInfo, sizeof(m_CurrentServerInfo));\n\tm_CurrentServerInfoRequestTime = 0;\n}\n\nint CClient::LoadData()\n{\n\tm_DebugFont = Graphics()->LoadTexture(\"debug_font.png\", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, IGraphics::TEXLOAD_NORESAMPLE);\n\treturn 1;\n}\n\n// ---\n\nvoid *CClient::SnapGetItem(int SnapID, int Index, CSnapItem *pItem)\n{\n\tCSnapshotItem *i;\n\tdbg_assert(SnapID >= 0 && SnapID < NUM_SNAPSHOT_TYPES, \"invalid SnapID\");\n\ti = m_aSnapshots[SnapID]->m_pAltSnap->GetItem(Index);\n\tpItem->m_DataSize = m_aSnapshots[SnapID]->m_pAltSnap->GetItemSize(Index);\n\tpItem->m_Type = i->Type();\n\tpItem->m_ID = i->ID();\n\treturn (void *)i->Data();\n}\n\nvoid CClient::SnapInvalidateItem(int SnapID, int Index)\n{\n\tCSnapshotItem *i;\n\tdbg_assert(SnapID >= 0 && SnapID < NUM_SNAPSHOT_TYPES, \"invalid SnapID\");\n\ti = m_aSnapshots[SnapID]->m_pAltSnap->GetItem(Index);\n\tif(i)\n\t{\n\t\tif((char *)i < (char *)m_aSnapshots[SnapID]->m_pAltSnap || (char *)i > (char *)m_aSnapshots[SnapID]->m_pAltSnap + m_aSnapshots[SnapID]->m_SnapSize)\n\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"client\", \"snap invalidate problem\");\n\t\tif((char *)i >= (char *)m_aSnapshots[SnapID]->m_pSnap && (char *)i < (char *)m_aSnapshots[SnapID]->m_pSnap + m_aSnapshots[SnapID]->m_SnapSize)\n\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"client\", \"snap invalidate problem\");\n\t\ti->m_TypeAndID = -1;\n\t}\n}\n\nvoid *CClient::SnapFindItem(int SnapID, int Type, int ID)\n{\n\t// TODO: linear search. should be fixed.\n\tint i;\n\n\tif(!m_aSnapshots[SnapID])\n\t\treturn 0x0;\n\n\tfor(i = 0; i < m_aSnapshots[SnapID]->m_pSnap->NumItems(); i++)\n\t{\n\t\tCSnapshotItem *pItem = m_aSnapshots[SnapID]->m_pAltSnap->GetItem(i);\n\t\tif(pItem->Type() == Type && pItem->ID() == ID)\n\t\t\treturn (void *)pItem->Data();\n\t}\n\treturn 0x0;\n}\n\nint CClient::SnapNumItems(int SnapID)\n{\n\tdbg_assert(SnapID >= 0 && SnapID < NUM_SNAPSHOT_TYPES, \"invalid SnapID\");\n\tif(!m_aSnapshots[SnapID])\n\t\treturn 0;\n\treturn m_aSnapshots[SnapID]->m_pSnap->NumItems();\n}\n\nvoid *CClient::SnapNewItem(int Type, int ID, int Size)\n{\n\tdbg_assert(Type >= 0 && Type <=0xffff, \"incorrect type\");\n\tdbg_assert(ID >= 0 && ID <=0xffff, \"incorrect id\");\n\treturn ID < 0 ? 0 : m_DemoRecSnapshotBuilder.NewItem(Type, ID, Size);\n}\n\nvoid CClient::SnapSetStaticsize(int ItemType, int Size)\n{\n\tm_SnapshotDelta.SetStaticsize(ItemType, Size);\n}\n\n\nvoid CClient::DebugRender()\n{\n\tstatic NETSTATS Prev, Current;\n\tstatic int64 LastSnap = 0;\n\tstatic float FrameTimeAvg = 0;\n\tint64 Now = time_get();\n\tchar aBuffer[512];\n\n\tif(!g_Config.m_Debug)\n\t\treturn;\n\n\t//m_pGraphics->BlendNormal();\n\tGraphics()->TextureSet(m_DebugFont);\n\tGraphics()->MapScreen(0,0,Graphics()->ScreenWidth(),Graphics()->ScreenHeight());\n\tGraphics()->QuadsBegin();\n\n\tif(time_get()-LastSnap > time_freq())\n\t{\n\t\tLastSnap = time_get();\n\t\tPrev = Current;\n\t\tnet_stats(&Current);\n\t}\n\n\t/*\n\t\teth = 14\n\t\tip = 20\n\t\tudp = 8\n\t\ttotal = 42\n\t*/\n\tFrameTimeAvg = FrameTimeAvg*0.9f + m_RenderFrameTime*0.1f;\n\tstr_format(aBuffer, sizeof(aBuffer), \"ticks: %8d %8d mem %dk %d gfxmem: %dk fps: %3d\",\n\t\tm_CurGameTick, m_PredTick,\n\t\tmem_stats()->allocated/1024,\n\t\tmem_stats()->total_allocations,\n\t\tGraphics()->MemoryUsage()/1024,\n\t\t(int)(1.0f/FrameTimeAvg + 0.5f));\n\tGraphics()->QuadsText(2, 2, 16, aBuffer);\n\n\n\t{\n\t\tint SendPackets = (Current.sent_packets-Prev.sent_packets);\n\t\tint SendBytes = (Current.sent_bytes-Prev.sent_bytes);\n\t\tint SendTotal = SendBytes + SendPackets*42;\n\t\tint RecvPackets = (Current.recv_packets-Prev.recv_packets);\n\t\tint RecvBytes = (Current.recv_bytes-Prev.recv_bytes);\n\t\tint RecvTotal = RecvBytes + RecvPackets*42;\n\n\t\tif(!SendPackets) SendPackets++;\n\t\tif(!RecvPackets) RecvPackets++;\n\t\tstr_format(aBuffer, sizeof(aBuffer), \"send: %3d %5d+%4d=%5d (%3d kbps) avg: %5d\\nrecv: %3d %5d+%4d=%5d (%3d kbps) avg: %5d\",\n\t\t\tSendPackets, SendBytes, SendPackets*42, SendTotal, (SendTotal*8)/1024, SendBytes/SendPackets,\n\t\t\tRecvPackets, RecvBytes, RecvPackets*42, RecvTotal, (RecvTotal*8)/1024, RecvBytes/RecvPackets);\n\t\tGraphics()->QuadsText(2, 14, 16, aBuffer);\n\t}\n\n\t// render rates\n\t{\n\t\tint y = 0;\n\t\tint i;\n\t\tfor(i = 0; i < 256; i++)\n\t\t{\n\t\t\tif(m_SnapshotDelta.GetDataRate(i))\n\t\t\t{\n\t\t\t\tstr_format(aBuffer, sizeof(aBuffer), \"%4d %20s: %8d %8d %8d\", i, GameClient()->GetItemName(i), m_SnapshotDelta.GetDataRate(i)/8, m_SnapshotDelta.GetDataUpdates(i),\n\t\t\t\t\t(m_SnapshotDelta.GetDataRate(i)/m_SnapshotDelta.GetDataUpdates(i))/8);\n\t\t\t\tGraphics()->QuadsText(2, 100+y*12, 16, aBuffer);\n\t\t\t\ty++;\n\t\t\t}\n\t\t}\n\t}\n\n\tstr_format(aBuffer, sizeof(aBuffer), \"pred: %d ms\",\n\t\t(int)((m_PredictedTime.Get(Now)-m_GameTime.Get(Now))*1000/(float)time_freq()));\n\tGraphics()->QuadsText(2, 70, 16, aBuffer);\n\tGraphics()->QuadsEnd();\n\n\t// render graphs\n\tif(g_Config.m_DbgGraphs)\n\t{\n\t\t//Graphics()->MapScreen(0,0,400.0f,300.0f);\n\t\tfloat w = Graphics()->ScreenWidth()/4.0f;\n\t\tfloat h = Graphics()->ScreenHeight()/6.0f;\n\t\tfloat sp = Graphics()->ScreenWidth()/100.0f;\n\t\tfloat x = Graphics()->ScreenWidth()-w-sp;\n\n\t\tm_FpsGraph.ScaleMax();\n\t\tm_FpsGraph.ScaleMin();\n\t\tm_FpsGraph.Render(Graphics(), m_DebugFont, x, sp*5, w, h, \"FPS\");\n\t\tm_InputtimeMarginGraph.Render(Graphics(), m_DebugFont, x, sp*5+h+sp, w, h, \"Prediction Margin\");\n\t\tm_GametimeMarginGraph.Render(Graphics(), m_DebugFont, x, sp*5+h+sp+h+sp, w, h, \"Gametime Margin\");\n\t}\n}\n\nvoid CClient::Quit()\n{\n\tSetState(IClient::STATE_QUITING);\n}\n\nconst char *CClient::ErrorString()\n{\n\treturn m_NetClient.ErrorString();\n}\n\nvoid CClient::Render()\n{\n\tif(g_Config.m_GfxClear)\n\t\tGraphics()->Clear(1,1,0);\n\n\tGameClient()->OnRender();\n\tDebugRender();\n}\n\nconst char *CClient::LoadMap(const char *pName, const char *pFilename, unsigned WantedCrc)\n{\n\tstatic char aErrorMsg[128];\n\n\tSetState(IClient::STATE_LOADING);\n\n\tif(!m_pMap->Load(pFilename))\n\t{\n\t\tstr_format(aErrorMsg, sizeof(aErrorMsg), \"map '%s' not found\", pFilename);\n\t\treturn aErrorMsg;\n\t}\n\n\t// get the crc of the map\n\tif(m_pMap->Crc() != WantedCrc)\n\t{\n\t\tstr_format(aErrorMsg, sizeof(aErrorMsg), \"map differs from the server. %08x != %08x\", m_pMap->Crc(), WantedCrc);\n\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"client\", aErrorMsg);\n\t\tm_pMap->Unload();\n\t\treturn aErrorMsg;\n\t}\n\n\t// stop demo recording if we loaded a new map\n\tDemoRecorder_Stop();\n\n\tchar aBuf[256];\n\tstr_format(aBuf, sizeof(aBuf), \"loaded map '%s'\", pFilename);\n\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"client\", aBuf);\n\tm_RecivedSnapshots = 0;\n\n\tstr_copy(m_aCurrentMap, pName, sizeof(m_aCurrentMap));\n\tm_CurrentMapCrc = m_pMap->Crc();\n\n\treturn 0x0;\n}\n\n\n\nconst char *CClient::LoadMapSearch(const char *pMapName, int WantedCrc)\n{\n\tconst char *pError = 0;\n\tchar aBuf[512];\n\tstr_format(aBuf, sizeof(aBuf), \"loading map, map=%s wanted crc=%08x\", pMapName, WantedCrc);\n\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"client\", aBuf);\n\tSetState(IClient::STATE_LOADING);\n\n\t// try the normal maps folder\n\tstr_format(aBuf, sizeof(aBuf), \"maps/%s.map\", pMapName);\n\tpError = LoadMap(pMapName, aBuf, WantedCrc);\n\tif(!pError)\n\t\treturn pError;\n\n\t// try the downloaded maps\n\tstr_format(aBuf, sizeof(aBuf), \"downloadedmaps/%s_%08x.map\", pMapName, WantedCrc);\n\tpError = LoadMap(pMapName, aBuf, WantedCrc);\n\tif(!pError)\n\t\treturn pError;\n\n\t// search for the map within subfolders\n\tchar aFilename[128];\n\tstr_format(aFilename, sizeof(aFilename), \"%s.map\", pMapName);\n\tif(Storage()->FindFile(aFilename, \"maps\", IStorage::TYPE_ALL, aBuf, sizeof(aBuf)))\n\t\tpError = LoadMap(pMapName, aBuf, WantedCrc);\n\n\treturn pError;\n}\n\nint CClient::PlayerScoreComp(const void *a, const void *b)\n{\n\tCServerInfo::CClient *p0 = (CServerInfo::CClient *)a;\n\tCServerInfo::CClient *p1 = (CServerInfo::CClient *)b;\n\tif(p0->m_Player && !p1->m_Player)\n\t\treturn -1;\n\tif(!p0->m_Player && p1->m_Player)\n\t\treturn 1;\n\tif(p0->m_Score == p1->m_Score)\n\t\treturn 0;\n\tif(p0->m_Score < p1->m_Score)\n\t\treturn 1;\n\treturn -1;\n}\n\nvoid CClient::ProcessConnlessPacket(CNetChunk *pPacket)\n{\n\t// version server\n\tif(m_VersionInfo.m_State == CVersionInfo::STATE_READY && net_addr_comp(&pPacket->m_Address, &m_VersionInfo.m_VersionServeraddr.m_Addr) == 0)\n\t{\n\t\t// version info\n\t\tif(pPacket->m_DataSize == (int)(sizeof(VERSIONSRV_VERSION) + sizeof(GAME_RELEASE_VERSION)) &&\n\t\t\tmem_comp(pPacket->m_pData, VERSIONSRV_VERSION, sizeof(VERSIONSRV_VERSION)) == 0)\n\n\t\t{\n\t\t\tchar *pVersionData = (char*)pPacket->m_pData + sizeof(VERSIONSRV_VERSION);\n\t\t\tint VersionMatch = !mem_comp(pVersionData, GAME_RELEASE_VERSION, sizeof(GAME_RELEASE_VERSION));\n\n\t\t\tchar aVersion[sizeof(GAME_RELEASE_VERSION)];\n\t\t\tstr_copy(aVersion, pVersionData, sizeof(aVersion));\n\n\t\t\tchar aBuf[256];\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"version does %s (%s)\",\n\t\t\t\tVersionMatch ? \"match\" : \"NOT match\",\n\t\t\t\taVersion);\n\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"client/version\", aBuf);\n\n\t\t\t// assume version is out of date when version-data doesn't match\n\t\t\tif(!VersionMatch)\n\t\t\t{\n\t\t\t\tstr_copy(m_aVersionStr, aVersion, sizeof(m_aVersionStr));\n\t\t\t}\n\n\t\t\t// request the map version list now\n\t\t\tCNetChunk Packet;\n\t\t\tmem_zero(&Packet, sizeof(Packet));\n\t\t\tPacket.m_ClientID = -1;\n\t\t\tPacket.m_Address = m_VersionInfo.m_VersionServeraddr.m_Addr;\n\t\t\tPacket.m_pData = VERSIONSRV_GETMAPLIST;\n\t\t\tPacket.m_DataSize = sizeof(VERSIONSRV_GETMAPLIST);\n\t\t\tPacket.m_Flags = NETSENDFLAG_CONNLESS;\n\t\t\tm_NetClient.Send(&Packet);\n\t\t}\n\n\t\t// map version list\n\t\tif(pPacket->m_DataSize >= (int)sizeof(VERSIONSRV_MAPLIST) &&\n\t\t\tmem_comp(pPacket->m_pData, VERSIONSRV_MAPLIST, sizeof(VERSIONSRV_MAPLIST)) == 0)\n\t\t{\n\t\t\tint Size = pPacket->m_DataSize-sizeof(VERSIONSRV_MAPLIST);\n\t\t\tint Num = Size/sizeof(CMapVersion);\n\t\t\tm_MapChecker.AddMaplist((CMapVersion *)((char*)pPacket->m_pData+sizeof(VERSIONSRV_MAPLIST)), Num);\n\t\t}\n\t}\n\n\t// server list from master server\n\tif(pPacket->m_DataSize >= (int)sizeof(SERVERBROWSE_LIST) &&\n\t\tmem_comp(pPacket->m_pData, SERVERBROWSE_LIST, sizeof(SERVERBROWSE_LIST)) == 0)\n\t{\n\t\t// check for valid master server address\n\t\tbool Valid = false;\n\t\tfor(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; ++i)\n\t\t{\n\t\t\tif(m_pMasterServer->IsValid(i))\n\t\t\t{\n\t\t\t\tNETADDR Addr = m_pMasterServer->GetAddr(i);\n\t\t\t\tif(net_addr_comp(&pPacket->m_Address, &Addr) == 0)\n\t\t\t\t{\n\t\t\t\t\tValid = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(!Valid)\n\t\t\treturn;\n\n\t\tint Size = pPacket->m_DataSize-sizeof(SERVERBROWSE_LIST);\n\t\tint Num = Size/sizeof(CMastersrvAddr);\n\t\tCMastersrvAddr *pAddrs = (CMastersrvAddr *)((char*)pPacket->m_pData+sizeof(SERVERBROWSE_LIST));\n\t\tfor(int i = 0; i < Num; i++)\n\t\t{\n\t\t\tNETADDR Addr;\n\n\t\t\tstatic unsigned char s_aIPV4Mapping[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF};\n\n\t\t\t// copy address\n\t\t\tif(!mem_comp(s_aIPV4Mapping, pAddrs[i].m_aIp, sizeof(s_aIPV4Mapping)))\n\t\t\t{\n\t\t\t\tmem_zero(&Addr, sizeof(Addr));\n\t\t\t\tAddr.type = NETTYPE_IPV4;\n\t\t\t\tAddr.ip[0] = pAddrs[i].m_aIp[12];\n\t\t\t\tAddr.ip[1] = pAddrs[i].m_aIp[13];\n\t\t\t\tAddr.ip[2] = pAddrs[i].m_aIp[14];\n\t\t\t\tAddr.ip[3] = pAddrs[i].m_aIp[15];\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tAddr.type = NETTYPE_IPV6;\n\t\t\t\tmem_copy(Addr.ip, pAddrs[i].m_aIp, sizeof(Addr.ip));\n\t\t\t}\n\t\t\tAddr.port = (pAddrs[i].m_aPort[0]<<8) | pAddrs[i].m_aPort[1];\n\n\t\t\tm_ServerBrowser.Set(Addr, CServerBrowser::SET_MASTER_ADD, -1, 0x0);\n\t\t}\n\t}\n\n\t// server info\n\tif(pPacket->m_DataSize >= (int)sizeof(SERVERBROWSE_INFO) && mem_comp(pPacket->m_pData, SERVERBROWSE_INFO, sizeof(SERVERBROWSE_INFO)) == 0)\n\t{\n\t\t// we got ze info\n\t\tCUnpacker Up;\n\t\tCServerInfo Info = {0};\n\n\t\tUp.Reset((unsigned char*)pPacket->m_pData+sizeof(SERVERBROWSE_INFO), pPacket->m_DataSize-sizeof(SERVERBROWSE_INFO));\n\t\tint Token = Up.GetInt();\n\t\tstr_copy(Info.m_aVersion, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aVersion));\n\t\tstr_copy(Info.m_aName, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aName));\n\t\tstr_copy(Info.m_aHostname, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aHostname));\n\t\tstr_copy(Info.m_aMap, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aMap));\n\t\tstr_copy(Info.m_aGameType, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aGameType));\n\t\tInfo.m_Flags = (Up.GetInt()&SERVERINFO_FLAG_PASSWORD) ? IServerBrowser::FLAG_PASSWORD : 0;\n\t\tInfo.m_ServerLevel = clamp<int>(Up.GetInt(), SERVERINFO_LEVEL_MIN, SERVERINFO_LEVEL_MAX);\n\t\tInfo.m_NumPlayers = Up.GetInt();\n\t\tInfo.m_MaxPlayers = Up.GetInt();\n\t\tInfo.m_NumClients = Up.GetInt();\n\t\tInfo.m_MaxClients = Up.GetInt();\n\n\t\t// don't add invalid info to the server browser list\n\t\tif(Info.m_NumClients < 0 || Info.m_NumClients > MAX_CLIENTS || Info.m_MaxClients < 0 || Info.m_MaxClients > MAX_CLIENTS ||\n\t\t\tInfo.m_NumPlayers < 0 || Info.m_NumPlayers > Info.m_NumClients || Info.m_MaxPlayers < 0 || Info.m_MaxPlayers > Info.m_MaxClients)\n\t\t\treturn;\n\n\t\tnet_addr_str(&pPacket->m_Address, Info.m_aAddress, sizeof(Info.m_aAddress), true);\n\t\tif(Info.m_aHostname[0] == 0)\n\t\t\tstr_copy(Info.m_aHostname, Info.m_aAddress, sizeof(Info.m_aHostname));\n\n\t\tfor(int i = 0; i < Info.m_NumClients; i++)\n\t\t{\n\t\t\tstr_copy(Info.m_aClients[i].m_aName, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aClients[i].m_aName));\n\t\t\tstr_copy(Info.m_aClients[i].m_aClan, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aClients[i].m_aClan));\n\t\t\tInfo.m_aClients[i].m_Country = Up.GetInt();\n\t\t\tInfo.m_aClients[i].m_Score = Up.GetInt();\n\t\t\tInfo.m_aClients[i].m_Player = Up.GetInt() != 0 ? true : false;\n\t\t}\n\n\t\tif(!Up.Error())\n\t\t{\n\t\t\t// sort players\n\t\t\tqsort(Info.m_aClients, Info.m_NumClients, sizeof(*Info.m_aClients), PlayerScoreComp);\n\n\t\t\tif(net_addr_comp(&m_ServerAddress, &pPacket->m_Address) == 0)\n\t\t\t{\n\t\t\t\tmem_copy(&m_CurrentServerInfo, &Info, sizeof(m_CurrentServerInfo));\n\t\t\t\tm_CurrentServerInfo.m_NetAddr = m_ServerAddress;\n\t\t\t\tm_CurrentServerInfoRequestTime = -1;\n\t\t\t}\n\t\t\telse\n\t\t\t\tm_ServerBrowser.Set(pPacket->m_Address, CServerBrowser::SET_TOKEN, Token, &Info);\n\t\t}\n\t}\n}\n\nvoid CClient::ProcessServerPacket(CNetChunk *pPacket)\n{\n\tCUnpacker Unpacker;\n\tUnpacker.Reset(pPacket->m_pData, pPacket->m_DataSize);\n\n\t// unpack msgid and system flag\n\tint Msg = Unpacker.GetInt();\n\tint Sys = Msg&1;\n\tMsg >>= 1;\n\n\tif(Unpacker.Error())\n\t\treturn;\n\n\tif(Sys)\n\t{\n\t\t// system message\n\t\tif(Msg == NETMSG_MAP_CHANGE)\n\t\t{\n\t\t\tconst char *pMap = Unpacker.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);\n\t\t\tint MapCrc = Unpacker.GetInt();\n\t\t\tint MapSize = Unpacker.GetInt();\n\t\t\tint MapChunkNum = Unpacker.GetInt();\n\t\t\tint MapChunkSize = Unpacker.GetInt();\n\t\t\tconst char *pError = 0;\n\n\t\t\tif(Unpacker.Error())\n\t\t\t\treturn;\n\n\t\t\t// check for valid standard map\n\t\t\tif(!m_MapChecker.IsMapValid(pMap, MapCrc, MapSize))\n\t\t\t\tpError = \"invalid standard map\";\n\n\t\t\t// protect the player from nasty map names\n\t\t\tfor(int i = 0; pMap[i]; i++)\n\t\t\t{\n\t\t\t\tif(pMap[i] == '/' || pMap[i] == '\\\\')\n\t\t\t\t\tpError = \"strange character in map name\";\n\t\t\t}\n\n\t\t\tif(MapSize <= 0)\n\t\t\t\tpError = \"invalid map size\";\n\n\t\t\tif(pError)\n\t\t\t\tDisconnectWithReason(pError);\n\t\t\telse\n\t\t\t{\n\t\t\t\tpError = LoadMapSearch(pMap, MapCrc);\n\n\t\t\t\tif(!pError)\n\t\t\t\t{\n\t\t\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"client/network\", \"loading done\");\n\t\t\t\t\tSendReady();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// start map download\n\t\t\t\t\tstr_format(m_aMapdownloadFilename, sizeof(m_aMapdownloadFilename), \"downloadedmaps/%s_%08x.map\", pMap, MapCrc);\n\n\t\t\t\t\tchar aBuf[256];\n\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"starting to download map to '%s'\", m_aMapdownloadFilename);\n\t\t\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"client/network\", aBuf);\n\n\t\t\t\t\tstr_copy(m_aMapdownloadName, pMap, sizeof(m_aMapdownloadName));\n\t\t\t\t\tif(m_MapdownloadFile)\n\t\t\t\t\t\tio_close(m_MapdownloadFile);\n\t\t\t\t\tm_MapdownloadFile = Storage()->OpenFile(m_aMapdownloadFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE);\n\t\t\t\t\tm_MapdownloadChunk = 0;\n\t\t\t\t\tm_MapdownloadChunkNum = MapChunkNum;\n\t\t\t\t\tm_MapDownloadChunkSize = MapChunkSize;\n\t\t\t\t\tm_MapdownloadCrc = MapCrc;\n\t\t\t\t\tm_MapdownloadTotalsize = MapSize;\n\t\t\t\t\tm_MapdownloadAmount = 0;\n\n\t\t\t\t\t// request first chunk package of map data\n\t\t\t\t\tCMsgPacker Msg(NETMSG_REQUEST_MAP_DATA, true);\n\t\t\t\t\tSendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH);\n\n\t\t\t\t\tif(g_Config.m_Debug)\n\t\t\t\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"client/network\", \"requested first chunk package\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if(Msg == NETMSG_MAP_DATA)\n\t\t{\n\t\t\tif(!m_MapdownloadFile)\n\t\t\t\treturn;\n\n\t\t\tint Size = min(m_MapDownloadChunkSize, m_MapdownloadTotalsize-m_MapdownloadAmount);\n\t\t\tconst unsigned char *pData = Unpacker.GetRaw(Size);\n\t\t\tif(Unpacker.Error())\n\t\t\t\treturn;\n \n\t\t\tio_write(m_MapdownloadFile, pData, Size);\n\t\t\t++m_MapdownloadChunk;\n\t\t\tm_MapdownloadAmount += Size;\n\n\t\t\tif(m_MapdownloadAmount == m_MapdownloadTotalsize)\n\t\t\t{\n\t\t\t\t// map download complete\n\t\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"client/network\", \"download complete, loading map\");\n\n\t\t\t\tif(m_MapdownloadFile)\n\t\t\t\t\tio_close(m_MapdownloadFile);\n\t\t\t\tm_MapdownloadFile = 0;\n\t\t\t\tm_MapdownloadAmount = 0;\n\t\t\t\tm_MapdownloadTotalsize = -1;\n\n\t\t\t\t// load map\n\t\t\t\tconst char *pError = LoadMap(m_aMapdownloadName, m_aMapdownloadFilename, m_MapdownloadCrc);\n\t\t\t\tif(!pError)\n\t\t\t\t{\n\t\t\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"client/network\", \"loading done\");\n\t\t\t\t\tSendReady();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tDisconnectWithReason(pError);\n\t\t\t}\n\t\t\telse if(m_MapdownloadChunk%m_MapdownloadChunkNum == 0)\n\t\t\t{\n\t\t\t\t// request next chunk package of map data\n\t\t\t\tCMsgPacker Msg(NETMSG_REQUEST_MAP_DATA, true);\n\t\t\t\tSendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH);\n\n\t\t\t\tif(g_Config.m_Debug)\n\t\t\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"client/network\", \"requested next chunk package\");\n\t\t\t}\n\t\t}\n\t\telse if(Msg == NETMSG_CON_READY)\n\t\t{\n\t\t\tGameClient()->OnConnected();\n\t\t}\n\t\telse if(Msg == NETMSG_PING)\n\t\t{\n\t\t\tCMsgPacker Msg(NETMSG_PING_REPLY, true);\n\t\t\tSendMsg(&Msg, 0);\n\t\t}\n\t\telse if(Msg == NETMSG_RCON_CMD_ADD)\n\t\t{\n\t\t\tconst char *pName = Unpacker.GetString(CUnpacker::SANITIZE_CC);\n\t\t\tconst char *pHelp = Unpacker.GetString(CUnpacker::SANITIZE_CC);\n\t\t\tconst char *pParams = Unpacker.GetString(CUnpacker::SANITIZE_CC);\n\t\t\tif(Unpacker.Error() == 0)\n\t\t\t\tm_pConsole->RegisterTemp(pName, pParams, CFGFLAG_SERVER, pHelp);\n\t\t}\n\t\telse if(Msg == NETMSG_RCON_CMD_REM)\n\t\t{\n\t\t\tconst char *pName = Unpacker.GetString(CUnpacker::SANITIZE_CC);\n\t\t\tif(Unpacker.Error() == 0)\n\t\t\t\tm_pConsole->DeregisterTemp(pName);\n\t\t}\n\t\telse if(Msg == NETMSG_RCON_AUTH_ON)\n\t\t{\n\t\t\tm_RconAuthed = 1;\n\t\t\tm_UseTempRconCommands = 1;\n\t\t}\n\t\telse if(Msg == NETMSG_RCON_AUTH_OFF)\n\t\t{\n\t\t\tm_RconAuthed = 0;\n\t\t\tif(m_UseTempRconCommands)\n\t\t\t\tm_pConsole->DeregisterTempAll();\n\t\t\tm_UseTempRconCommands = 0;\n\t\t}\n\t\telse if(Msg == NETMSG_RCON_LINE)\n\t\t{\n\t\t\tconst char *pLine = Unpacker.GetString();\n\t\t\tif(Unpacker.Error() == 0)\n\t\t\t\tGameClient()->OnRconLine(pLine);\n\t\t}\n\t\telse if(Msg == NETMSG_PING_REPLY)\n\t\t{\n\t\t\tchar aBuf[256];\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"latency %.2f\", (time_get() - m_PingStartTime)*1000 / (float)time_freq());\n\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"client/network\", aBuf);\n\t\t}\n\t\telse if(Msg == NETMSG_INPUTTIMING)\n\t\t{\n\t\t\tint InputPredTick = Unpacker.GetInt();\n\t\t\tint TimeLeft = Unpacker.GetInt();\n\n\t\t\t// adjust our prediction time\n\t\t\tint64 Target = 0;\n\t\t\tfor(int k = 0; k < 200; k++)\n\t\t\t{\n\t\t\t\tif(m_aInputs[k].m_Tick == InputPredTick)\n\t\t\t\t{\n\t\t\t\t\tTarget = m_aInputs[k].m_PredictedTime + (time_get() - m_aInputs[k].m_Time);\n\t\t\t\t\tTarget = Target - (int64)(((TimeLeft-PREDICTION_MARGIN)/1000.0f)*time_freq());\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(Target)\n\t\t\t\tm_PredictedTime.Update(&m_InputtimeMarginGraph, Target, TimeLeft, 1);\n\t\t}\n\t\telse if(Msg == NETMSG_SNAP || Msg == NETMSG_SNAPSINGLE || Msg == NETMSG_SNAPEMPTY)\n\t\t{\n\t\t\tint NumParts = 1;\n\t\t\tint Part = 0;\n\t\t\tint GameTick = Unpacker.GetInt();\n\t\t\tint DeltaTick = GameTick-Unpacker.GetInt();\n\t\t\tint PartSize = 0;\n\t\t\tint Crc = 0;\n\t\t\tint CompleteSize = 0;\n\t\t\tconst char *pData = 0;\n\n\t\t\t// we are not allowed to process snapshot yet\n\t\t\tif(State() < IClient::STATE_LOADING)\n\t\t\t\treturn;\n\n\t\t\tif(Msg == NETMSG_SNAP)\n\t\t\t{\n\t\t\t\tNumParts = Unpacker.GetInt();\n\t\t\t\tPart = Unpacker.GetInt();\n\t\t\t}\n\n\t\t\tif(Msg != NETMSG_SNAPEMPTY)\n\t\t\t{\n\t\t\t\tCrc = Unpacker.GetInt();\n\t\t\t\tPartSize = Unpacker.GetInt();\n\t\t\t}\n\n\t\t\tpData = (const char *)Unpacker.GetRaw(PartSize);\n\n\t\t\tif(Unpacker.Error())\n\t\t\t\treturn;\n\n\t\t\tif(GameTick >= m_CurrentRecvTick)\n\t\t\t{\n\t\t\t\tif(GameTick != m_CurrentRecvTick)\n\t\t\t\t{\n\t\t\t\t\tm_SnapshotParts = 0;\n\t\t\t\t\tm_CurrentRecvTick = GameTick;\n\t\t\t\t}\n\n\t\t\t\t// TODO: clean this up abit\n\t\t\t\tmem_copy((char*)m_aSnapshotIncommingData + Part*MAX_SNAPSHOT_PACKSIZE, pData, PartSize);\n\t\t\t\tm_SnapshotParts |= 1<<Part;\n\n\t\t\t\tif(m_SnapshotParts == (unsigned)((1<<NumParts)-1))\n\t\t\t\t{\n\t\t\t\t\tstatic CSnapshot Emptysnap;\n\t\t\t\t\tCSnapshot *pDeltaShot = &Emptysnap;\n\t\t\t\t\tint PurgeTick;\n\t\t\t\t\tvoid *pDeltaData;\n\t\t\t\t\tint DeltaSize;\n\t\t\t\t\tunsigned char aTmpBuffer2[CSnapshot::MAX_SIZE];\n\t\t\t\t\tunsigned char aTmpBuffer3[CSnapshot::MAX_SIZE];\n\t\t\t\t\tCSnapshot *pTmpBuffer3 = (CSnapshot*)aTmpBuffer3;\t// Fix compiler warning for strict-aliasing\n\t\t\t\t\tint SnapSize;\n\n\t\t\t\t\tCompleteSize = (NumParts-1) * MAX_SNAPSHOT_PACKSIZE + PartSize;\n\n\t\t\t\t\t// reset snapshoting\n\t\t\t\t\tm_SnapshotParts = 0;\n\n\t\t\t\t\t// find snapshot that we should use as delta\n\t\t\t\t\tEmptysnap.Clear();\n\n\t\t\t\t\t// find delta\n\t\t\t\t\tif(DeltaTick >= 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tint DeltashotSize = m_SnapshotStorage.Get(DeltaTick, 0, &pDeltaShot, 0);\n\n\t\t\t\t\t\tif(DeltashotSize < 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// couldn't find the delta snapshots that the server used\n\t\t\t\t\t\t\t// to compress this snapshot. force the server to resync\n\t\t\t\t\t\t\tif(g_Config.m_Debug)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tchar aBuf[256];\n\t\t\t\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"error, couldn't find the delta snapshot\");\n\t\t\t\t\t\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"client\", aBuf);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// ack snapshot\n\t\t\t\t\t\t\t// TODO: combine this with the input message\n\t\t\t\t\t\t\tm_AckGameTick = -1;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// decompress snapshot\n\t\t\t\t\tpDeltaData = m_SnapshotDelta.EmptyDelta();\n\t\t\t\t\tDeltaSize = sizeof(int)*3;\n\n\t\t\t\t\tif(CompleteSize)\n\t\t\t\t\t{\n\t\t\t\t\t\tint IntSize = CVariableInt::Decompress(m_aSnapshotIncommingData, CompleteSize, aTmpBuffer2);\n\n\t\t\t\t\t\tif(IntSize < 0) // failure during decompression, bail\n\t\t\t\t\t\t\treturn;\n\n\t\t\t\t\t\tpDeltaData = aTmpBuffer2;\n\t\t\t\t\t\tDeltaSize = IntSize;\n\t\t\t\t\t}\n\n\t\t\t\t\t// unpack delta\n\t\t\t\t\tSnapSize = m_SnapshotDelta.UnpackDelta(pDeltaShot, pTmpBuffer3, pDeltaData, DeltaSize);\n\t\t\t\t\tif(SnapSize < 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"client\", \"delta unpack failed!\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(Msg != NETMSG_SNAPEMPTY && pTmpBuffer3->Crc() != Crc)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(g_Config.m_Debug)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tchar aBuf[256];\n\t\t\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"snapshot crc error #%d - tick=%d wantedcrc=%d gotcrc=%d compressed_size=%d delta_tick=%d\",\n\t\t\t\t\t\t\t\tm_SnapCrcErrors, GameTick, Crc, pTmpBuffer3->Crc(), CompleteSize, DeltaTick);\n\t\t\t\t\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"client\", aBuf);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tm_SnapCrcErrors++;\n\t\t\t\t\t\tif(m_SnapCrcErrors > 10)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// to many errors, send reset\n\t\t\t\t\t\t\tm_AckGameTick = -1;\n\t\t\t\t\t\t\tSendInput();\n\t\t\t\t\t\t\tm_SnapCrcErrors = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif(m_SnapCrcErrors)\n\t\t\t\t\t\t\tm_SnapCrcErrors--;\n\t\t\t\t\t}\n\n\t\t\t\t\t// purge old snapshots\n\t\t\t\t\tPurgeTick = DeltaTick;\n\t\t\t\t\tif(m_aSnapshots[SNAP_PREV] && m_aSnapshots[SNAP_PREV]->m_Tick < PurgeTick)\n\t\t\t\t\t\tPurgeTick = m_aSnapshots[SNAP_PREV]->m_Tick;\n\t\t\t\t\tif(m_aSnapshots[SNAP_CURRENT] && m_aSnapshots[SNAP_CURRENT]->m_Tick < PurgeTick)\n\t\t\t\t\t\tPurgeTick = m_aSnapshots[SNAP_CURRENT]->m_Tick;\n\t\t\t\t\tm_SnapshotStorage.PurgeUntil(PurgeTick);\n\n\t\t\t\t\t// add new\n\t\t\t\t\tm_SnapshotStorage.Add(GameTick, time_get(), SnapSize, pTmpBuffer3, 1);\n\n\t\t\t\t\t// add snapshot to demo\n\t\t\t\t\tif(m_DemoRecorder.IsRecording())\n\t\t\t\t\t{\n\t\t\t\t\t\t// build up snapshot and add local messages\n\t\t\t\t\t\tm_DemoRecSnapshotBuilder.Init(pTmpBuffer3);\n\t\t\t\t\t\tGameClient()->OnDemoRecSnap();\n\t\t\t\t\t\tSnapSize = m_DemoRecSnapshotBuilder.Finish(pTmpBuffer3);\n\n\t\t\t\t\t\t// write snapshot\n\t\t\t\t\t\tm_DemoRecorder.RecordSnapshot(GameTick, pTmpBuffer3, SnapSize);\n\t\t\t\t\t}\n\n\t\t\t\t\t// apply snapshot, cycle pointers\n\t\t\t\t\tm_RecivedSnapshots++;\n\n\t\t\t\t\tm_CurrentRecvTick = GameTick;\n\n\t\t\t\t\t// we got two snapshots until we see us self as connected\n\t\t\t\t\tif(m_RecivedSnapshots == 2)\n\t\t\t\t\t{\n\t\t\t\t\t\t// start at 200ms and work from there\n\t\t\t\t\t\tm_PredictedTime.Init(GameTick*time_freq()/50);\n\t\t\t\t\t\tm_PredictedTime.SetAdjustSpeed(1, 1000.0f);\n\t\t\t\t\t\tm_GameTime.Init((GameTick-1)*time_freq()/50);\n\t\t\t\t\t\tm_aSnapshots[SNAP_PREV] = m_SnapshotStorage.m_pFirst;\n\t\t\t\t\t\tm_aSnapshots[SNAP_CURRENT] = m_SnapshotStorage.m_pLast;\n\t\t\t\t\t\tm_LocalStartTime = time_get();\n\t\t\t\t\t\tSetState(IClient::STATE_ONLINE);\n\t\t\t\t\t\tDemoRecorder_HandleAutoStart();\n\t\t\t\t\t}\n\n\t\t\t\t\t// adjust game time\n\t\t\t\t\tif(m_RecivedSnapshots > 2)\n\t\t\t\t\t{\n\t\t\t\t\t\tint64 Now = m_GameTime.Get(time_get());\n\t\t\t\t\t\tint64 TickStart = GameTick*time_freq()/50;\n\t\t\t\t\t\tint64 TimeLeft = (TickStart-Now)*1000 / time_freq();\n\t\t\t\t\t\tm_GameTime.Update(&m_GametimeMarginGraph, (GameTick-1)*time_freq()/50, TimeLeft, 0);\n\t\t\t\t\t}\n\n\t\t\t\t\t// ack snapshot\n\t\t\t\t\tm_AckGameTick = GameTick;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\t// game message\n\t\tGameClient()->OnMessage(Msg, &Unpacker);\n\n\t\tif(m_RecordGameMessage && m_DemoRecorder.IsRecording())\n\t\t\tm_DemoRecorder.RecordMessage(pPacket->m_pData, pPacket->m_DataSize);\n\t}\n}\n\nvoid CClient::PumpNetwork()\n{\n\tm_NetClient.Update();\n\n\tif(State() != IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\t// check for errors\n\t\tif(State() != IClient::STATE_OFFLINE && State() != IClient::STATE_QUITING && m_NetClient.State() == NETSTATE_OFFLINE)\n\t\t{\n\t\t\tSetState(IClient::STATE_OFFLINE);\n\t\t\tDisconnect();\n\t\t\tchar aBuf[256];\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"offline error='%s'\", m_NetClient.ErrorString());\n\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"client\", aBuf);\n\t\t}\n\n\t\t//\n\t\tif(State() == IClient::STATE_CONNECTING && m_NetClient.State() == NETSTATE_ONLINE)\n\t\t{\n\t\t\t// we switched to online\n\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"client\", \"connected, sending info\");\n\t\t\tSetState(IClient::STATE_LOADING);\n\t\t\tSendInfo();\n\t\t}\n\t}\n\n\t// process packets\n\tCNetChunk Packet;\n\twhile(m_NetClient.Recv(&Packet))\n\t{\n\t\tif(Packet.m_ClientID == -1)\n\t\t\tProcessConnlessPacket(&Packet);\n\t\telse\n\t\t\tProcessServerPacket(&Packet);\n\t}\n}\n\nvoid CClient::OnDemoPlayerSnapshot(void *pData, int Size)\n{\n\t// update ticks, they could have changed\n\tconst CDemoPlayer::CPlaybackInfo *pInfo = m_DemoPlayer.Info();\n\tCSnapshotStorage::CHolder *pTemp;\n\tm_CurGameTick = pInfo->m_Info.m_CurrentTick;\n\tm_PrevGameTick = pInfo->m_PreviousTick;\n\n\t// handle snapshots\n\tpTemp = m_aSnapshots[SNAP_PREV];\n\tm_aSnapshots[SNAP_PREV] = m_aSnapshots[SNAP_CURRENT];\n\tm_aSnapshots[SNAP_CURRENT] = pTemp;\n\n\tmem_copy(m_aSnapshots[SNAP_CURRENT]->m_pSnap, pData, Size);\n\tmem_copy(m_aSnapshots[SNAP_CURRENT]->m_pAltSnap, pData, Size);\n\n\tGameClient()->OnNewSnapshot();\n}\n\nvoid CClient::OnDemoPlayerMessage(void *pData, int Size)\n{\n\tCUnpacker Unpacker;\n\tUnpacker.Reset(pData, Size);\n\n\t// unpack msgid and system flag\n\tint Msg = Unpacker.GetInt();\n\tint Sys = Msg&1;\n\tMsg >>= 1;\n\n\tif(Unpacker.Error())\n\t\treturn;\n\n\tif(!Sys)\n\t\tGameClient()->OnMessage(Msg, &Unpacker);\n}\n/*\nconst IDemoPlayer::CInfo *client_demoplayer_getinfo()\n{\n\tstatic DEMOPLAYBACK_INFO ret;\n\tconst DEMOREC_PLAYBACKINFO *info = m_DemoPlayer.Info();\n\tret.first_tick = info->first_tick;\n\tret.last_tick = info->last_tick;\n\tret.current_tick = info->current_tick;\n\tret.paused = info->paused;\n\tret.speed = info->speed;\n\treturn &ret;\n}*/\n\n/*\nvoid DemoPlayer()->SetPos(float percent)\n{\n\tdemorec_playback_set(percent);\n}\n\nvoid DemoPlayer()->SetSpeed(float speed)\n{\n\tdemorec_playback_setspeed(speed);\n}\n\nvoid DemoPlayer()->SetPause(int paused)\n{\n\tif(paused)\n\t\tdemorec_playback_pause();\n\telse\n\t\tdemorec_playback_unpause();\n}*/\n\nvoid CClient::Update()\n{\n\tif(State() == IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tm_DemoPlayer.Update();\n\t\tif(m_DemoPlayer.IsPlaying())\n\t\t{\n\t\t\t// update timers\n\t\t\tconst CDemoPlayer::CPlaybackInfo *pInfo = m_DemoPlayer.Info();\n\t\t\tm_CurGameTick = pInfo->m_Info.m_CurrentTick;\n\t\t\tm_PrevGameTick = pInfo->m_PreviousTick;\n\t\t\tm_GameIntraTick = pInfo->m_IntraTick;\n\t\t\tm_GameTickTime = pInfo->m_TickTime;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// disconnect on error\n\t\t\tDisconnect();\n\t\t}\n\t}\n\telse if(State() == IClient::STATE_ONLINE && m_RecivedSnapshots >= 3)\n\t{\n\t\t// switch snapshot\n\t\tint Repredict = 0;\n\t\tint64 Freq = time_freq();\n\t\tint64 Now = m_GameTime.Get(time_get());\n\t\tint64 PredNow = m_PredictedTime.Get(time_get());\n\n\t\twhile(1)\n\t\t{\n\t\t\tCSnapshotStorage::CHolder *pCur = m_aSnapshots[SNAP_CURRENT];\n\t\t\tint64 TickStart = (pCur->m_Tick)*time_freq()/50;\n\n\t\t\tif(TickStart < Now)\n\t\t\t{\n\t\t\t\tCSnapshotStorage::CHolder *pNext = m_aSnapshots[SNAP_CURRENT]->m_pNext;\n\t\t\t\tif(pNext)\n\t\t\t\t{\n\t\t\t\t\tm_aSnapshots[SNAP_PREV] = m_aSnapshots[SNAP_CURRENT];\n\t\t\t\t\tm_aSnapshots[SNAP_CURRENT] = pNext;\n\n\t\t\t\t\t// set ticks\n\t\t\t\t\tm_CurGameTick = m_aSnapshots[SNAP_CURRENT]->m_Tick;\n\t\t\t\t\tm_PrevGameTick = m_aSnapshots[SNAP_PREV]->m_Tick;\n\n\t\t\t\t\tif(m_aSnapshots[SNAP_CURRENT] && m_aSnapshots[SNAP_PREV])\n\t\t\t\t\t{\n\t\t\t\t\t\tGameClient()->OnNewSnapshot();\n\t\t\t\t\t\tRepredict = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\n\t\tif(m_aSnapshots[SNAP_CURRENT] && m_aSnapshots[SNAP_PREV])\n\t\t{\n\t\t\tint64 CurtickStart = (m_aSnapshots[SNAP_CURRENT]->m_Tick)*time_freq()/50;\n\t\t\tint64 PrevtickStart = (m_aSnapshots[SNAP_PREV]->m_Tick)*time_freq()/50;\n\t\t\tint PrevPredTick = (int)(PredNow*50/time_freq());\n\t\t\tint NewPredTick = PrevPredTick+1;\n\n\t\t\tm_GameIntraTick = (Now - PrevtickStart) / (float)(CurtickStart-PrevtickStart);\n\t\t\tm_GameTickTime = (Now - PrevtickStart) / (float)Freq; //(float)SERVER_TICK_SPEED);\n\n\t\t\tCurtickStart = NewPredTick*time_freq()/50;\n\t\t\tPrevtickStart = PrevPredTick*time_freq()/50;\n\t\t\tm_PredIntraTick = (PredNow - PrevtickStart) / (float)(CurtickStart-PrevtickStart);\n\n\t\t\tif(NewPredTick < m_aSnapshots[SNAP_PREV]->m_Tick-SERVER_TICK_SPEED || NewPredTick > m_aSnapshots[SNAP_PREV]->m_Tick+SERVER_TICK_SPEED)\n\t\t\t{\n\t\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"client\", \"prediction time reset!\");\n\t\t\t\tm_PredictedTime.Init(m_aSnapshots[SNAP_CURRENT]->m_Tick*time_freq()/50);\n\t\t\t}\n\n\t\t\tif(NewPredTick > m_PredTick)\n\t\t\t{\n\t\t\t\tm_PredTick = NewPredTick;\n\t\t\t\tRepredict = 1;\n\n\t\t\t\t// send input\n\t\t\t\tSendInput();\n\t\t\t}\n\t\t}\n\n\t\t// only do sane predictions\n\t\tif(Repredict)\n\t\t{\n\t\t\tif(m_PredTick > m_CurGameTick && m_PredTick < m_CurGameTick+50)\n\t\t\t\tGameClient()->OnPredict();\n\t\t}\n\n\t\t// fetch server info if we don't have it\n\t\tif(State() >= IClient::STATE_LOADING &&\n\t\t\tm_CurrentServerInfoRequestTime >= 0 &&\n\t\t\ttime_get() > m_CurrentServerInfoRequestTime)\n\t\t{\n\t\t\tm_ServerBrowser.Request(m_ServerAddress);\n\t\t\tm_CurrentServerInfoRequestTime = time_get()+time_freq()*2;\n\t\t}\n\t}\n\n\t// STRESS TEST: join the server again\n\tif(g_Config.m_DbgStress)\n\t{\n\t\tstatic int64 ActionTaken = 0;\n\t\tint64 Now = time_get();\n\t\tif(State() == IClient::STATE_OFFLINE)\n\t\t{\n\t\t\tif(Now > ActionTaken+time_freq()*2)\n\t\t\t{\n\t\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"stress\", \"reconnecting!\");\n\t\t\t\tConnect(g_Config.m_DbgStressServer);\n\t\t\t\tActionTaken = Now;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(Now > ActionTaken+time_freq()*(10+g_Config.m_DbgStress))\n\t\t\t{\n\t\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"stress\", \"disconnecting!\");\n\t\t\t\tDisconnect();\n\t\t\t\tActionTaken = Now;\n\t\t\t}\n\t\t}\n\t}\n\n\t// pump the network\n\tPumpNetwork();\n\n\t// update the maser server registry\n\tMasterServer()->Update();\n\n\t// update the server browser\n\tm_ServerBrowser.Update(m_ResortServerBrowser);\n\tm_ResortServerBrowser = false;\n}\n\nvoid CClient::VersionUpdate()\n{\n\tif(m_VersionInfo.m_State == CVersionInfo::STATE_INIT)\n\t{\n\t\tEngine()->HostLookup(&m_VersionInfo.m_VersionServeraddr, g_Config.m_ClVersionServer, m_NetClient.NetType());\n\t\tm_VersionInfo.m_State = CVersionInfo::STATE_START;\n\t}\n\telse if(m_VersionInfo.m_State == CVersionInfo::STATE_START)\n\t{\n\t\tif(m_VersionInfo.m_VersionServeraddr.m_Job.Status() == CJob::STATE_DONE)\n\t\t{\n\t\t\tCNetChunk Packet;\n\n\t\t\tmem_zero(&Packet, sizeof(Packet));\n\n\t\t\tm_VersionInfo.m_VersionServeraddr.m_Addr.port = VERSIONSRV_PORT;\n\n\t\t\tPacket.m_ClientID = -1;\n\t\t\tPacket.m_Address = m_VersionInfo.m_VersionServeraddr.m_Addr;\n\t\t\tPacket.m_pData = VERSIONSRV_GETVERSION;\n\t\t\tPacket.m_DataSize = sizeof(VERSIONSRV_GETVERSION);\n\t\t\tPacket.m_Flags = NETSENDFLAG_CONNLESS;\n\n\t\t\tm_NetClient.Send(&Packet);\n\t\t\tm_VersionInfo.m_State = CVersionInfo::STATE_READY;\n\t\t}\n\t}\n}\n\nvoid CClient::RegisterInterfaces()\n{\n\tKernel()->RegisterInterface(static_cast<IDemoRecorder*>(&m_DemoRecorder));\n\tKernel()->RegisterInterface(static_cast<IDemoPlayer*>(&m_DemoPlayer));\n\tKernel()->RegisterInterface(static_cast<IServerBrowser*>(&m_ServerBrowser));\n\tKernel()->RegisterInterface(static_cast<IFriends*>(&m_Friends));\n}\n\nvoid CClient::InitInterfaces()\n{\n\t// fetch interfaces\n\tm_pEngine = Kernel()->RequestInterface<IEngine>();\n\tm_pEditor = Kernel()->RequestInterface<IEditor>();\n\t//m_pGraphics = Kernel()->RequestInterface<IEngineGraphics>();\n\tm_pSound = Kernel()->RequestInterface<IEngineSound>();\n\tm_pGameClient = Kernel()->RequestInterface<IGameClient>();\n\tm_pInput = Kernel()->RequestInterface<IEngineInput>();\n\tm_pMap = Kernel()->RequestInterface<IEngineMap>();\n\tm_pMasterServer = Kernel()->RequestInterface<IEngineMasterServer>();\n\tm_pStorage = Kernel()->RequestInterface<IStorage>();\n\n\t//\n\tm_ServerBrowser.SetBaseInfo(&m_NetClient, m_pGameClient->NetVersion());\n\tm_Friends.Init();\n}\n\nvoid CClient::Run()\n{\n\tm_LocalStartTime = time_get();\n\tm_SnapshotParts = 0;\n\n\t// init SDL\n\t{\n\t\tif(SDL_Init(0) < 0)\n\t\t{\n\t\t\tdbg_msg(\"client\", \"unable to init SDL base: %s\", SDL_GetError());\n\t\t\treturn;\n\t\t}\n\n\t\tatexit(SDL_Quit); // ignore_convention\n\t}\n\n\tm_MenuStartTime = time_get();\n\n\t// init graphics\n\t{\n\t\tm_pGraphics = CreateEngineGraphicsThreaded();\n\n\t\tbool RegisterFail = false;\n\t\tRegisterFail = RegisterFail || !Kernel()->RegisterInterface(static_cast<IEngineGraphics*>(m_pGraphics)); // register graphics as both\n\t\tRegisterFail = RegisterFail || !Kernel()->RegisterInterface(static_cast<IGraphics*>(m_pGraphics));\n\n\t\tif(RegisterFail || m_pGraphics->Init() != 0)\n\t\t{\n\t\t\tdbg_msg(\"client\", \"couldn't init graphics\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\t// init sound, allowed to fail\n\tm_SoundInitFailed = Sound()->Init() != 0;\n\n\t// open socket\n\t{\n\t\tNETADDR BindAddr;\n\t\tif(g_Config.m_Bindaddr[0] && net_host_lookup(g_Config.m_Bindaddr, &BindAddr, NETTYPE_ALL) == 0)\n\t\t{\n\t\t\t// got bindaddr\n\t\t\tBindAddr.type = NETTYPE_ALL;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmem_zero(&BindAddr, sizeof(BindAddr));\n\t\t\tBindAddr.type = NETTYPE_ALL;\n\t\t}\n\t\tif(!m_NetClient.Open(BindAddr, 0))\n\t\t{\n\t\t\tdbg_msg(\"client\", \"couldn't open socket\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\t// init font rendering\n\tKernel()->RequestInterface<IEngineTextRender>()->Init();\n\n\t// init the input\n\tInput()->Init();\n\n\t// start refreshing addresses while we load\n\tMasterServer()->RefreshAddresses(m_NetClient.NetType());\n\n\t// init the editor\n\tm_pEditor->Init();\n\n\n\t// load data\n\tif(!LoadData())\n\t\treturn;\n\n\tGameClient()->OnInit();\n\n\tchar aBuf[256];\n\tstr_format(aBuf, sizeof(aBuf), \"version %s\", GameClient()->NetVersion());\n\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"client\", aBuf);\n\n\t// connect to the server if wanted\n\t/*\n\tif(config.cl_connect[0] != 0)\n\t\tConnect(config.cl_connect);\n\tconfig.cl_connect[0] = 0;\n\t*/\n\n\t//\n\tm_FpsGraph.Init(0.0f, 200.0f);\n\n\t// never start with the editor\n\tg_Config.m_ClEditor = 0;\n\n\tInput()->MouseModeRelative();\n\n\t// process pending commands\n\tm_pConsole->StoreCommands(false);\n\n\twhile (1)\n\t{\n\t\t//\n\t\tVersionUpdate();\n\n\t\t// handle pending connects\n\t\tif(m_aCmdConnect[0])\n\t\t{\n\t\t\tstr_copy(g_Config.m_UiServerAddress, m_aCmdConnect, sizeof(g_Config.m_UiServerAddress));\n\t\t\tConnect(m_aCmdConnect);\n\t\t\tm_aCmdConnect[0] = 0;\n\t\t}\n\n\t\t// update input\n\t\tif(Input()->Update())\n\t\t\tbreak;\t// SDL_QUIT\n\n\t\t// update sound\n\t\tSound()->Update();\n\n\t\t// release focus\n\t\tif(!m_pGraphics->WindowActive())\n\t\t{\n\t\t\tif(m_WindowMustRefocus == 0)\n\t\t\t\tInput()->MouseModeAbsolute();\n\t\t\tm_WindowMustRefocus = 1;\n\t\t}\n\t\telse if (g_Config.m_DbgFocus && Input()->KeyPressed(KEY_ESCAPE))\n\t\t{\n\t\t\tInput()->MouseModeAbsolute();\n\t\t\tm_WindowMustRefocus = 1;\n\t\t}\n\n\t\t// refocus\n\t\tif(m_WindowMustRefocus && m_pGraphics->WindowActive())\n\t\t{\n\t\t\tif(m_WindowMustRefocus < 3)\n\t\t\t{\n\t\t\t\tInput()->MouseModeAbsolute();\n\t\t\t\tm_WindowMustRefocus++;\n\t\t\t}\n\n\t\t\tif(m_WindowMustRefocus >= 3 || Input()->KeyPressed(KEY_MOUSE_1))\n\t\t\t{\n\t\t\t\tInput()->MouseModeRelative();\n\t\t\t\tm_WindowMustRefocus = 0;\n\t\t\t}\n\t\t}\n\n\t\t// panic quit button\n\t\tif(Input()->KeyPressed(KEY_LCTRL) && Input()->KeyPressed(KEY_LSHIFT) && Input()->KeyPressed('q'))\n\t\t{\n\t\t\tQuit();\n\t\t\tbreak;\n\t\t}\n\n\t\tif(Input()->KeyPressed(KEY_LCTRL) && Input()->KeyPressed(KEY_LSHIFT) && Input()->KeyDown('d'))\n\t\t\tg_Config.m_Debug ^= 1;\n\n\t\tif(Input()->KeyPressed(KEY_LCTRL) && Input()->KeyPressed(KEY_LSHIFT) && Input()->KeyDown('g'))\n\t\t\tg_Config.m_DbgGraphs ^= 1;\n\n\t\tif(Input()->KeyPressed(KEY_LCTRL) && Input()->KeyPressed(KEY_LSHIFT) && Input()->KeyDown('e'))\n\t\t{\n\t\t\tg_Config.m_ClEditor = g_Config.m_ClEditor^1;\n\t\t\tInput()->MouseModeRelative();\n\t\t}\n\n\t\t/*\n\t\tif(!gfx_window_open())\n\t\t\tbreak;\n\t\t*/\n\n\t\t// render\n\t\t{\n\t\t\tif(g_Config.m_ClEditor)\n\t\t\t{\n\t\t\t\tif(!m_EditorActive)\n\t\t\t\t{\n\t\t\t\t\tGameClient()->OnActivateEditor();\n\t\t\t\t\tm_EditorActive = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(m_EditorActive)\n\t\t\t\tm_EditorActive = false;\n\n\t\t\tUpdate();\n\t\t\t\n\t\t\tif(!g_Config.m_GfxAsyncRender || m_pGraphics->IsIdle())\n\t\t\t{\n\t\t\t\tm_RenderFrames++;\n\n\t\t\t\t// update frametime\n\t\t\t\tint64 Now = time_get();\n\t\t\t\tm_RenderFrameTime = (Now - m_LastRenderTime) / (float)time_freq();\n\t\t\t\tif(m_RenderFrameTime < m_RenderFrameTimeLow)\n\t\t\t\t\tm_RenderFrameTimeLow = m_RenderFrameTime;\n\t\t\t\tif(m_RenderFrameTime > m_RenderFrameTimeHigh)\n\t\t\t\t\tm_RenderFrameTimeHigh = m_RenderFrameTime;\n\t\t\t\tm_FpsGraph.Add(1.0f/m_RenderFrameTime, 1,1,1);\n\n\t\t\t\tm_LastRenderTime = Now;\n\n\t\t\t\t// when we are stress testing only render every 10th frame\n\t\t\t\tif(!g_Config.m_DbgStress || (m_RenderFrames%10) == 0 )\n\t\t\t\t{\n\t\t\t\t\tif(!m_EditorActive)\n\t\t\t\t\t\tRender();\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tm_pEditor->UpdateAndRender();\n\t\t\t\t\t\tDebugRender();\n\t\t\t\t\t}\n\t\t\t\t\tm_pGraphics->Swap();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tAutoScreenshot_Cleanup();\n\n\t\t// check conditions\n\t\tif(State() == IClient::STATE_QUITING)\n\t\t\tbreak;\n\n\t\t// menu tick\n\t\tif(State() == IClient::STATE_OFFLINE)\n\t\t{\n\t\t\tint64 t = time_get();\n\t\t\twhile(t > TickStartTime(m_CurMenuTick+1))\n\t\t\t\tm_CurMenuTick++;\n\t\t}\n\n\t\t// beNice\n\t\tif(g_Config.m_ClCpuThrottle)\n\t\t\tthread_sleep(g_Config.m_ClCpuThrottle);\n\t\telse if(g_Config.m_DbgStress || !m_pGraphics->WindowActive())\n\t\t\tthread_sleep(5);\n\n\t\tif(g_Config.m_DbgHitch)\n\t\t{\n\t\t\tthread_sleep(g_Config.m_DbgHitch);\n\t\t\tg_Config.m_DbgHitch = 0;\n\t\t}\n\n\t\t/*\n\t\tif(ReportTime < time_get())\n\t\t{\n\t\t\tif(0 && g_Config.m_Debug)\n\t\t\t{\n\t\t\t\tdbg_msg(\"client/report\", \"fps=%.02f (%.02f %.02f) netstate=%d\",\n\t\t\t\t\tm_Frames/(float)(ReportInterval/time_freq()),\n\t\t\t\t\t1.0f/m_RenderFrameTimeHigh,\n\t\t\t\t\t1.0f/m_RenderFrameTimeLow,\n\t\t\t\t\tm_NetClient.State());\n\t\t\t}\n\t\t\tm_RenderFrameTimeLow = 1;\n\t\t\tm_RenderFrameTimeHigh = 0;\n\t\t\tm_RenderFrames = 0;\n\t\t\tReportTime += ReportInterval;\n\t\t}*/\n\n\t\t// update local time\n\t\tm_LocalTime = (time_get()-m_LocalStartTime)/(float)time_freq();\n\t}\n\n\tGameClient()->OnShutdown();\n\tDisconnect();\n\n\tm_pGraphics->Shutdown();\n\tm_pSound->Shutdown();\n\n\t// shutdown SDL\n\t{\n\t\tSDL_Quit();\n\t}\n}\n\nint64 CClient::TickStartTime(int Tick)\n{\n\treturn m_MenuStartTime + (time_freq()*Tick)/m_GameTickSpeed;\n}\n\nvoid CClient::Con_Connect(IConsole::IResult *pResult, void *pUserData)\n{\n\tCClient *pSelf = (CClient *)pUserData;\n\tstr_copy(pSelf->m_aCmdConnect, pResult->GetString(0), sizeof(pSelf->m_aCmdConnect));\n}\n\nvoid CClient::Con_Disconnect(IConsole::IResult *pResult, void *pUserData)\n{\n\tCClient *pSelf = (CClient *)pUserData;\n\tpSelf->Disconnect();\n}\n\nvoid CClient::Con_Quit(IConsole::IResult *pResult, void *pUserData)\n{\n\tCClient *pSelf = (CClient *)pUserData;\n\tpSelf->Quit();\n}\n\nvoid CClient::Con_Minimize(IConsole::IResult *pResult, void *pUserData)\n{\n\tCClient *pSelf = (CClient *)pUserData;\n\tpSelf->Graphics()->Minimize();\n}\n\nvoid CClient::Con_Ping(IConsole::IResult *pResult, void *pUserData)\n{\n\tCClient *pSelf = (CClient *)pUserData;\n\n\tCMsgPacker Msg(NETMSG_PING, true);\n\tpSelf->SendMsg(&Msg, 0);\n\tpSelf->m_PingStartTime = time_get();\n}\n\nvoid CClient::AutoScreenshot_Start()\n{\n\tif(g_Config.m_ClAutoScreenshot)\n\t{\n\t\tGraphics()->TakeScreenshot(\"auto/autoscreen\");\n\t\tm_AutoScreenshotRecycle = true;\n\t}\n}\n\nvoid CClient::AutoScreenshot_Cleanup()\n{\n\tif(m_AutoScreenshotRecycle)\n\t{\n\t\tif(g_Config.m_ClAutoScreenshotMax)\n\t\t{\n\t\t\t// clean up auto taken screens\n\t\t\tCFileCollection AutoScreens;\n\t\t\tAutoScreens.Init(Storage(), \"screenshots/auto\", \"autoscreen\", \".png\", g_Config.m_ClAutoScreenshotMax);\n\t\t}\n\t\tm_AutoScreenshotRecycle = false;\n\t}\n}\n\nvoid CClient::Con_Screenshot(IConsole::IResult *pResult, void *pUserData)\n{\n\tCClient *pSelf = (CClient *)pUserData;\n\tpSelf->Graphics()->TakeScreenshot(0);\n}\n\nvoid CClient::Con_Rcon(IConsole::IResult *pResult, void *pUserData)\n{\n\tCClient *pSelf = (CClient *)pUserData;\n\tpSelf->Rcon(pResult->GetString(0));\n}\n\nvoid CClient::Con_RconAuth(IConsole::IResult *pResult, void *pUserData)\n{\n\tCClient *pSelf = (CClient *)pUserData;\n\tpSelf->RconAuth(\"\", pResult->GetString(0));\n}\n\nconst char *CClient::DemoPlayer_Play(const char *pFilename, int StorageType)\n{\n\tint Crc;\n\t\n\tDisconnect();\n\tm_NetClient.ResetErrorString();\n\n\t// try to start playback\n\tm_DemoPlayer.SetListner(this);\n\n\tconst char *pError = m_DemoPlayer.Load(Storage(), m_pConsole, pFilename, StorageType, GameClient()->NetVersion());\n\tif(pError)\n\t\treturn pError;\n\n\t// load map\n\tCrc = (m_DemoPlayer.Info()->m_Header.m_aMapCrc[0]<<24)|\n\t\t(m_DemoPlayer.Info()->m_Header.m_aMapCrc[1]<<16)|\n\t\t(m_DemoPlayer.Info()->m_Header.m_aMapCrc[2]<<8)|\n\t\t(m_DemoPlayer.Info()->m_Header.m_aMapCrc[3]);\n\tpError = LoadMapSearch(m_DemoPlayer.Info()->m_Header.m_aMapName, Crc);\n\tif(pError)\n\t{\n\t\tDisconnectWithReason(pError);\n\t\treturn pError;\n\t}\n\n\tGameClient()->OnConnected();\n\n\t// setup buffers\n\tmem_zero(m_aDemorecSnapshotData, sizeof(m_aDemorecSnapshotData));\n\n\tm_aSnapshots[SNAP_CURRENT] = &m_aDemorecSnapshotHolders[SNAP_CURRENT];\n\tm_aSnapshots[SNAP_PREV] = &m_aDemorecSnapshotHolders[SNAP_PREV];\n\n\tm_aSnapshots[SNAP_CURRENT]->m_pSnap = (CSnapshot *)m_aDemorecSnapshotData[SNAP_CURRENT][0];\n\tm_aSnapshots[SNAP_CURRENT]->m_pAltSnap = (CSnapshot *)m_aDemorecSnapshotData[SNAP_CURRENT][1];\n\tm_aSnapshots[SNAP_CURRENT]->m_SnapSize = 0;\n\tm_aSnapshots[SNAP_CURRENT]->m_Tick = -1;\n\n\tm_aSnapshots[SNAP_PREV]->m_pSnap = (CSnapshot *)m_aDemorecSnapshotData[SNAP_PREV][0];\n\tm_aSnapshots[SNAP_PREV]->m_pAltSnap = (CSnapshot *)m_aDemorecSnapshotData[SNAP_PREV][1];\n\tm_aSnapshots[SNAP_PREV]->m_SnapSize = 0;\n\tm_aSnapshots[SNAP_PREV]->m_Tick = -1;\n\n\t// enter demo playback state\n\tSetState(IClient::STATE_DEMOPLAYBACK);\n\n\tm_DemoPlayer.Play();\n\tGameClient()->OnEnterGame();\n\n\treturn 0;\n}\n\nvoid CClient::Con_Play(IConsole::IResult *pResult, void *pUserData)\n{\n\tCClient *pSelf = (CClient *)pUserData;\n\tpSelf->DemoPlayer_Play(pResult->GetString(0), IStorage::TYPE_ALL);\n}\n\nvoid CClient::DemoRecorder_Start(const char *pFilename, bool WithTimestamp)\n{\n\tif(State() != IClient::STATE_ONLINE)\n\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"demorec/record\", \"client is not online\");\n\telse\n\t{\n\t\tchar aFilename[128];\n\t\tif(WithTimestamp)\n\t\t{\n\t\t\tchar aDate[20];\n\t\t\tstr_timestamp(aDate, sizeof(aDate));\n\t\t\tstr_format(aFilename, sizeof(aFilename), \"demos/%s_%s.demo\", pFilename, aDate);\n\t\t}\n\t\telse\n\t\t\tstr_format(aFilename, sizeof(aFilename), \"demos/%s.demo\", pFilename);\n\t\tm_DemoRecorder.Start(Storage(), m_pConsole, aFilename, GameClient()->NetVersion(), m_aCurrentMap, m_CurrentMapCrc, \"client\");\n\t}\n}\n\nvoid CClient::DemoRecorder_HandleAutoStart()\n{\n\tif(g_Config.m_ClAutoDemoRecord)\n\t{\n\t\tDemoRecorder_Stop();\n\t\tDemoRecorder_Start(\"auto/autorecord\", true);\n\t\tif(g_Config.m_ClAutoDemoMax)\n\t\t{\n\t\t\t// clean up auto recorded demos\n\t\t\tCFileCollection AutoDemos;\n\t\t\tAutoDemos.Init(Storage(), \"demos/auto\", \"autorecord\", \".demo\", g_Config.m_ClAutoDemoMax);\n\t\t}\n\t}\n}\n\nvoid CClient::DemoRecorder_Stop()\n{\n\tm_DemoRecorder.Stop();\n}\n\nvoid CClient::DemoRecorder_AddDemoMarker()\n{\n\tm_DemoRecorder.AddDemoMarker();\n}\n\nvoid CClient::Con_Record(IConsole::IResult *pResult, void *pUserData)\n{\n\tCClient *pSelf = (CClient *)pUserData;\n\tif(pResult->NumArguments())\n\t\tpSelf->DemoRecorder_Start(pResult->GetString(0), false);\n\telse\n\t\tpSelf->DemoRecorder_Start(\"demo\", true);\n}\n\nvoid CClient::Con_StopRecord(IConsole::IResult *pResult, void *pUserData)\n{\n\tCClient *pSelf = (CClient *)pUserData;\n\tpSelf->DemoRecorder_Stop();\n}\n\nvoid CClient::Con_AddDemoMarker(IConsole::IResult *pResult, void *pUserData)\n{\n\tCClient *pSelf = (CClient *)pUserData;\n\tpSelf->DemoRecorder_AddDemoMarker();\n}\n\nvoid CClient::ServerBrowserUpdate()\n{\n\tm_ResortServerBrowser = true;\n}\n\nvoid CClient::ConchainServerBrowserUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)\n{\n\tpfnCallback(pResult, pCallbackUserData);\n\tif(pResult->NumArguments())\n\t\t((CClient *)pUserData)->ServerBrowserUpdate();\n}\n\nvoid CClient::RegisterCommands()\n{\n\tm_pConsole = Kernel()->RequestInterface<IConsole>();\n\n\tm_pConsole->Register(\"quit\", \"\", CFGFLAG_CLIENT|CFGFLAG_STORE, Con_Quit, this, \"Quit Teeworlds\");\n\tm_pConsole->Register(\"exit\", \"\", CFGFLAG_CLIENT|CFGFLAG_STORE, Con_Quit, this, \"Quit Teeworlds\");\n\tm_pConsole->Register(\"minimize\", \"\", CFGFLAG_CLIENT|CFGFLAG_STORE, Con_Minimize, this, \"Minimize Teeworlds\");\n\tm_pConsole->Register(\"connect\", \"s\", CFGFLAG_CLIENT, Con_Connect, this, \"Connect to the specified host/ip\");\n\tm_pConsole->Register(\"disconnect\", \"\", CFGFLAG_CLIENT, Con_Disconnect, this, \"Disconnect from the server\");\n\tm_pConsole->Register(\"ping\", \"\", CFGFLAG_CLIENT, Con_Ping, this, \"Ping the current server\");\n\tm_pConsole->Register(\"screenshot\", \"\", CFGFLAG_CLIENT, Con_Screenshot, this, \"Take a screenshot\");\n\tm_pConsole->Register(\"rcon\", \"r\", CFGFLAG_CLIENT, Con_Rcon, this, \"Send specified command to rcon\");\n\tm_pConsole->Register(\"rcon_auth\", \"s\", CFGFLAG_CLIENT, Con_RconAuth, this, \"Authenticate to rcon\");\n\tm_pConsole->Register(\"play\", \"r\", CFGFLAG_CLIENT|CFGFLAG_STORE, Con_Play, this, \"Play the file specified\");\n\tm_pConsole->Register(\"record\", \"?s\", CFGFLAG_CLIENT, Con_Record, this, \"Record to the file\");\n\tm_pConsole->Register(\"stoprecord\", \"\", CFGFLAG_CLIENT, Con_StopRecord, this, \"Stop recording\");\n\tm_pConsole->Register(\"add_demomarker\", \"\", CFGFLAG_CLIENT, Con_AddDemoMarker, this, \"Add demo timeline marker\");\n\n\t// used for server browser update\n\tm_pConsole->Chain(\"br_filter_string\", ConchainServerBrowserUpdate, this);\n\tm_pConsole->Chain(\"br_filter_gametype\", ConchainServerBrowserUpdate, this);\n\tm_pConsole->Chain(\"br_filter_serveraddress\", ConchainServerBrowserUpdate, this);\n}\n\nstatic CClient *CreateClient()\n{\n\tCClient *pClient = static_cast<CClient *>(mem_alloc(sizeof(CClient), 1));\n\tmem_zero(pClient, sizeof(CClient));\n\treturn new(pClient) CClient;\n}\n\n/*\n\tServer Time\n\tClient Mirror Time\n\tClient Predicted Time\n\n\tSnapshot Latency\n\t\tDownstream latency\n\n\tPrediction Latency\n\t\tUpstream latency\n*/\n\n#if defined(CONF_PLATFORM_MACOSX)\nextern \"C\" int SDL_main(int argc, char **argv_) // ignore_convention\n{\n\tconst char **argv = const_cast<const char **>(argv_);\n#else\nint main(int argc, const char **argv) // ignore_convention\n{\n#endif\n#if defined(CONF_FAMILY_WINDOWS)\n\tfor(int i = 1; i < argc; i++) // ignore_convention\n\t{\n\t\tif(str_comp(\"-s\", argv[i]) == 0 || str_comp(\"--silent\", argv[i]) == 0) // ignore_convention\n\t\t{\n\t\t\tFreeConsole();\n\t\t\tbreak;\n\t\t}\n\t}\n#endif\n\n\tCClient *pClient = CreateClient();\n\tIKernel *pKernel = IKernel::Create();\n\tpKernel->RegisterInterface(pClient);\n\tpClient->RegisterInterfaces();\n\n\t// create the components\n\tIEngine *pEngine = CreateEngine(\"Teeworlds\");\n\tIConsole *pConsole = CreateConsole(CFGFLAG_CLIENT);\n\tIStorage *pStorage = CreateStorage(\"Teeworlds\", IStorage::STORAGETYPE_CLIENT, argc, argv); // ignore_convention\n\tIConfig *pConfig = CreateConfig();\n\tIEngineSound *pEngineSound = CreateEngineSound();\n\tIEngineInput *pEngineInput = CreateEngineInput();\n\tIEngineTextRender *pEngineTextRender = CreateEngineTextRender();\n\tIEngineMap *pEngineMap = CreateEngineMap();\n\tIEngineMasterServer *pEngineMasterServer = CreateEngineMasterServer();\n\n\t{\n\t\tbool RegisterFail = false;\n\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(pEngine);\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(pConsole);\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(pConfig);\n\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineSound*>(pEngineSound)); // register as both\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<ISound*>(pEngineSound));\n\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineInput*>(pEngineInput)); // register as both\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IInput*>(pEngineInput));\n\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineTextRender*>(pEngineTextRender)); // register as both\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<ITextRender*>(pEngineTextRender));\n\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineMap*>(pEngineMap)); // register as both\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IMap*>(pEngineMap));\n\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineMasterServer*>(pEngineMasterServer)); // register as both\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IMasterServer*>(pEngineMasterServer));\n\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(CreateEditor());\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(CreateGameClient());\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(pStorage);\n\n\t\tif(RegisterFail)\n\t\t\treturn -1;\n\t}\n\n\tpEngine->Init();\n\tpConfig->Init();\n\tpEngineMasterServer->Init();\n\tpEngineMasterServer->Load();\n\n\t// register all console commands\n\tpClient->RegisterCommands();\n\n\t// init client's interfaces\n\tpClient->InitInterfaces();\n\n\tpKernel->RequestInterface<IGameClient>()->OnConsoleInit();\n\n\t// execute config file\n\tpConsole->ExecuteFile(\"settings.cfg\");\n\n\t// execute autoexec file\n\tpConsole->ExecuteFile(\"autoexec.cfg\");\n\n\t// parse the command line arguments\n\tif(argc > 1) // ignore_convention\n\t\tpConsole->ParseArguments(argc-1, &argv[1]); // ignore_convention\n\n\t// restore empty config strings to their defaults\n\tpConfig->RestoreStrings();\n\n\tpClient->Engine()->InitLogfile();\n\n\t// run the client\n\tdbg_msg(\"client\", \"starting...\");\n\tpClient->Run();\n\n\t// write down the config and quit\n\tpConfig->Save();\n\n\t// free components\n\tmem_free(pClient);\n\tdelete pKernel;\n\tdelete pEngine;\n\tdelete pConsole;\n\tdelete pStorage;\n\tdelete pConfig;\n\tdelete pEngineSound;\n\tdelete pEngineInput;\n\tdelete pEngineTextRender;\n\tdelete pEngineMap;\n\tdelete pEngineMasterServer;\n\n\treturn 0;\n}\n"
  },
  {
    "path": "src/engine/client/client.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_CLIENT_CLIENT_H\n#define ENGINE_CLIENT_CLIENT_H\n\nclass CGraph\n{\npublic:\n\tenum\n\t{\n\t\t// restrictions: Must be power of two\n\t\tMAX_VALUES=128,\n\t};\n\n\tfloat m_Min, m_Max;\n\tfloat m_aValues[MAX_VALUES];\n\tfloat m_aColors[MAX_VALUES][3];\n\tint m_Index;\n\n\tvoid Init(float Min, float Max);\n\n\tvoid ScaleMax();\n\tvoid ScaleMin();\n\n\tvoid Add(float v, float r, float g, float b);\n\tvoid Render(IGraphics *pGraphics, IGraphics::CTextureHandle FontTexture, float x, float y, float w, float h, const char *pDescription);\n};\n\n\nclass CSmoothTime\n{\n\tint64 m_Snap;\n\tint64 m_Current;\n\tint64 m_Target;\n\n\tint64 m_RLast;\n\tint64 m_TLast;\n\tCGraph m_Graph;\n\n\tint m_SpikeCounter;\n\n\tfloat m_aAdjustSpeed[2]; // 0 = down, 1 = up\npublic:\n\tvoid Init(int64 Target);\n\tvoid SetAdjustSpeed(int Direction, float Value);\n\n\tint64 Get(int64 Now);\n\n\tvoid UpdateInt(int64 Target);\n\tvoid Update(CGraph *pGraph, int64 Target, int TimeLeft, int AdjustDirection);\n};\n\n\nclass CClient : public IClient, public CDemoPlayer::IListner\n{\n\t// needed interfaces\n\tIEngine *m_pEngine;\n\tIEditor *m_pEditor;\n\tIEngineInput *m_pInput;\n\tIEngineGraphics *m_pGraphics;\n\tIEngineSound *m_pSound;\n\tIGameClient *m_pGameClient;\n\tIEngineMap *m_pMap;\n\tIConsole *m_pConsole;\n\tIStorage *m_pStorage;\n\tIEngineMasterServer *m_pMasterServer;\n\n\tenum\n\t{\n\t\tNUM_SNAPSHOT_TYPES=2,\n\t\tPREDICTION_MARGIN=1000/50/2, // magic network prediction value\n\t};\n\n\tclass CNetClient m_NetClient;\n\tclass CDemoPlayer m_DemoPlayer;\n\tclass CDemoRecorder m_DemoRecorder;\n\tclass CServerBrowser m_ServerBrowser;\n\tclass CFriends m_Friends;\n\tclass CMapChecker m_MapChecker;\n\n\tchar m_aServerAddressStr[256];\n\n\tunsigned m_SnapshotParts;\n\tint64 m_LocalStartTime;\n\n\tIGraphics::CTextureHandle m_DebugFont;\n\t\n\tint64 m_LastRenderTime;\n\tfloat m_RenderFrameTimeLow;\n\tfloat m_RenderFrameTimeHigh;\n\tint m_RenderFrames;\n\n\tNETADDR m_ServerAddress;\n\tint m_WindowMustRefocus;\n\tint m_SnapCrcErrors;\n\tbool m_AutoScreenshotRecycle;\n\tbool m_EditorActive;\n\tbool m_SoundInitFailed;\n\tbool m_ResortServerBrowser;\n\tbool m_RecordGameMessage;\n\n\tint m_AckGameTick;\n\tint m_CurrentRecvTick;\n\tint m_RconAuthed;\n\tint m_UseTempRconCommands;\n\n\t// version-checking\n\tchar m_aVersionStr[10];\n\n\t// pinging\n\tint64 m_PingStartTime;\n\n\t//\n\tchar m_aCurrentMap[256];\n\tunsigned m_CurrentMapCrc;\n\n\t//\n\tchar m_aCmdConnect[256];\n\n\t// map download\n\tchar m_aMapdownloadFilename[256];\n\tchar m_aMapdownloadName[256];\n\tIOHANDLE m_MapdownloadFile;\n\tint m_MapdownloadChunk;\n\tint m_MapdownloadChunkNum;\n\tint m_MapDownloadChunkSize;\n\tint m_MapdownloadCrc;\n\tint m_MapdownloadAmount;\n\tint m_MapdownloadTotalsize;\n\n\t// time\n\tCSmoothTime m_GameTime;\n\tCSmoothTime m_PredictedTime;\n\n\t// input\n\tstruct // TODO: handle input better\n\t{\n\t\tint m_aData[MAX_INPUT_SIZE]; // the input data\n\t\tint m_Tick; // the tick that the input is for\n\t\tint64 m_PredictedTime; // prediction latency when we sent this input\n\t\tint64 m_Time;\n\t} m_aInputs[200];\n\n\tint m_CurrentInput;\n\n\t// graphs\n\tCGraph m_InputtimeMarginGraph;\n\tCGraph m_GametimeMarginGraph;\n\tCGraph m_FpsGraph;\n\n\t// the game snapshots are modifiable by the game\n\tclass CSnapshotStorage m_SnapshotStorage;\n\tCSnapshotStorage::CHolder *m_aSnapshots[NUM_SNAPSHOT_TYPES];\n\n\tint m_RecivedSnapshots;\n\tchar m_aSnapshotIncommingData[CSnapshot::MAX_SIZE];\n\n\tclass CSnapshotStorage::CHolder m_aDemorecSnapshotHolders[NUM_SNAPSHOT_TYPES];\n\tchar *m_aDemorecSnapshotData[NUM_SNAPSHOT_TYPES][2][CSnapshot::MAX_SIZE];\n\tclass CSnapshotBuilder m_DemoRecSnapshotBuilder;\n\n\tclass CSnapshotDelta m_SnapshotDelta;\n\n\t//\n\tclass CServerInfo m_CurrentServerInfo;\n\tint64 m_CurrentServerInfoRequestTime; // >= 0 should request, == -1 got info\n\n\t// version info\n\tstruct CVersionInfo\n\t{\n\t\tenum\n\t\t{\n\t\t\tSTATE_INIT=0,\n\t\t\tSTATE_START,\n\t\t\tSTATE_READY,\n\t\t};\n\n\t\tint m_State;\n\t\tclass CHostLookup m_VersionServeraddr;\n\t} m_VersionInfo;\n\n\tvolatile int m_GfxState;\n\tstatic void GraphicsThreadProxy(void *pThis) { ((CClient*)pThis)->GraphicsThread(); }\n\tvoid GraphicsThread();\n\n\tint64 TickStartTime(int Tick);\n\npublic:\n\tIEngine *Engine() { return m_pEngine; }\n\tIEngineGraphics *Graphics() { return m_pGraphics; }\n\tIEngineInput *Input() { return m_pInput; }\n\tIEngineSound *Sound() { return m_pSound; }\n\tIGameClient *GameClient() { return m_pGameClient; }\n\tIEngineMasterServer *MasterServer() { return m_pMasterServer; }\n\tIStorage *Storage() { return m_pStorage; }\n\n\tCClient();\n\n\t// ----- send functions -----\n\tvirtual int SendMsg(CMsgPacker *pMsg, int Flags);\n\n\tvoid SendInfo();\n\tvoid SendEnterGame();\n\tvoid SendReady();\n\n\tvirtual bool RconAuthed() { return m_RconAuthed != 0; }\n\tvirtual bool UseTempRconCommands() { return m_UseTempRconCommands != 0; }\n\tvoid RconAuth(const char *pName, const char *pPassword);\n\tvirtual void Rcon(const char *pCmd);\n\n\tvirtual bool ConnectionProblems();\n\n\tvirtual bool SoundInitFailed() { return m_SoundInitFailed; }\n\n\tvirtual IGraphics::CTextureHandle GetDebugFont() { return m_DebugFont; }\n\n\tvoid DirectInput(int *pInput, int Size);\n\tvoid SendInput();\n\n\t// TODO: OPT: do this alot smarter!\n\tvirtual int *GetInput(int Tick);\n\n\tconst char *LatestVersion();\n\tvoid VersionUpdate();\n\n\t// ------ state handling -----\n\tvoid SetState(int s);\n\n\t// called when the map is loaded and we should init for a new round\n\tvoid OnEnterGame();\n\tvirtual void EnterGame();\n\n\tvirtual void Connect(const char *pAddress);\n\tvoid DisconnectWithReason(const char *pReason);\n\tvirtual void Disconnect();\n\n\n\tvirtual void GetServerInfo(CServerInfo *pServerInfo);\n\tvoid ServerInfoRequest();\n\n\tint LoadData();\n\n\t// ---\n\n\tvoid *SnapGetItem(int SnapID, int Index, CSnapItem *pItem);\n\tvoid SnapInvalidateItem(int SnapID, int Index);\n\tvoid *SnapFindItem(int SnapID, int Type, int ID);\n\tint SnapNumItems(int SnapID);\n\tvoid *SnapNewItem(int Type, int ID, int Size);\n\tvoid SnapSetStaticsize(int ItemType, int Size);\n\n\tvoid Render();\n\tvoid DebugRender();\n\n\tvirtual void Quit();\n\n\tvirtual const char *ErrorString();\n\n\tconst char *LoadMap(const char *pName, const char *pFilename, unsigned WantedCrc);\n\tconst char *LoadMapSearch(const char *pMapName, int WantedCrc);\n\n\tstatic int PlayerScoreComp(const void *a, const void *b);\n\n\tvoid ProcessConnlessPacket(CNetChunk *pPacket);\n\tvoid ProcessServerPacket(CNetChunk *pPacket);\n\n\tvirtual int MapDownloadAmount() { return m_MapdownloadAmount; }\n\tvirtual int MapDownloadTotalsize() { return m_MapdownloadTotalsize; }\n\n\tvoid PumpNetwork();\n\n\tvirtual void OnDemoPlayerSnapshot(void *pData, int Size);\n\tvirtual void OnDemoPlayerMessage(void *pData, int Size);\n\n\tvoid Update();\n\n\tvoid RegisterInterfaces();\n\tvoid InitInterfaces();\n\n\tvoid Run();\n\n\n\tstatic void Con_Connect(IConsole::IResult *pResult, void *pUserData);\n\tstatic void Con_Disconnect(IConsole::IResult *pResult, void *pUserData);\n\tstatic void Con_Quit(IConsole::IResult *pResult, void *pUserData);\n\tstatic void Con_Minimize(IConsole::IResult *pResult, void *pUserData);\n\tstatic void Con_Ping(IConsole::IResult *pResult, void *pUserData);\n\tstatic void Con_Screenshot(IConsole::IResult *pResult, void *pUserData);\n\tstatic void Con_Rcon(IConsole::IResult *pResult, void *pUserData);\n\tstatic void Con_RconAuth(IConsole::IResult *pResult, void *pUserData);\n\tstatic void Con_AddFavorite(IConsole::IResult *pResult, void *pUserData);\n\tstatic void Con_RemoveFavorite(IConsole::IResult *pResult, void *pUserData);\n\tstatic void Con_Play(IConsole::IResult *pResult, void *pUserData);\n\tstatic void Con_Record(IConsole::IResult *pResult, void *pUserData);\n\tstatic void Con_StopRecord(IConsole::IResult *pResult, void *pUserData);\n\tstatic void Con_AddDemoMarker(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConchainServerBrowserUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData);\n\n\tvoid RegisterCommands();\n\n\tconst char *DemoPlayer_Play(const char *pFilename, int StorageType);\n\tvoid DemoRecorder_Start(const char *pFilename, bool WithTimestamp);\n\tvoid DemoRecorder_HandleAutoStart();\n\tvoid DemoRecorder_Stop();\n\tvoid DemoRecorder_AddDemoMarker();\n\tvoid RecordGameMessage(bool State) { m_RecordGameMessage = State; }\n\n\tvoid AutoScreenshot_Start();\n\tvoid AutoScreenshot_Cleanup();\n\n\tvoid ServerBrowserUpdate();\n};\n#endif\n"
  },
  {
    "path": "src/engine/client/friends.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/math.h>\n#include <base/system.h>\n\n#include <engine/config.h>\n#include <engine/console.h>\n#include <engine/shared/config.h>\n\n#include \"friends.h\"\n\nCFriends::CFriends()\n{\n\tmem_zero(m_aFriends, sizeof(m_aFriends));\n\tm_NumFriends = 0;\n}\n\nvoid CFriends::ConAddFriend(IConsole::IResult *pResult, void *pUserData)\n{\n\tCFriends *pSelf = (CFriends *)pUserData;\n\tpSelf->AddFriend(pResult->GetString(0), pResult->GetString(1));\n}\n\nvoid CFriends::ConRemoveFriend(IConsole::IResult *pResult, void *pUserData)\n{\n\tCFriends *pSelf = (CFriends *)pUserData;\n\tpSelf->RemoveFriend(pResult->GetString(0), pResult->GetString(1));\n}\n\nvoid CFriends::Init()\n{\n\tIConfig *pConfig = Kernel()->RequestInterface<IConfig>();\n\tif(pConfig)\n\t\tpConfig->RegisterCallback(ConfigSaveCallback, this);\n\n\tIConsole *pConsole = Kernel()->RequestInterface<IConsole>();\n\tif(pConsole)\n\t{\n\t\tpConsole->Register(\"add_friend\", \"ss\", CFGFLAG_CLIENT, ConAddFriend, this, \"Add a friend\");\n\t\tpConsole->Register(\"remove_friend\", \"ss\", CFGFLAG_CLIENT, ConRemoveFriend, this, \"Remove a friend\");\n\t}\n}\n\nconst CFriendInfo *CFriends::GetFriend(int Index) const\n{\n\treturn &m_aFriends[max(0, Index%m_NumFriends)];\n}\n\nint CFriends::GetFriendState(const char *pName, const char *pClan) const\n{\n\tint Result = FRIEND_NO;\n\tunsigned NameHash = str_quickhash(pName);\n\tunsigned ClanHash = str_quickhash(pClan);\n\tfor(int i = 0; i < m_NumFriends; ++i)\n\t{\n\t\tif(m_aFriends[i].m_ClanHash == ClanHash)\n\t\t{\n\t\t\tif(m_aFriends[i].m_aName[0] == 0)\n\t\t\t\tResult = FRIEND_CLAN;\n\t\t\telse if(m_aFriends[i].m_NameHash == NameHash)\n\t\t\t{\n\t\t\t\tResult = FRIEND_PLAYER;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn Result;\n}\n\nbool CFriends::IsFriend(const char *pName, const char *pClan, bool PlayersOnly) const\n{\n\tunsigned NameHash = str_quickhash(pName);\n\tunsigned ClanHash = str_quickhash(pClan);\n\tfor(int i = 0; i < m_NumFriends; ++i)\n\t{\n\t\tif(m_aFriends[i].m_ClanHash == ClanHash &&\n\t\t\t((!PlayersOnly && m_aFriends[i].m_aName[0] == 0) || m_aFriends[i].m_NameHash == NameHash))\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid CFriends::AddFriend(const char *pName, const char *pClan)\n{\n\tif(m_NumFriends == MAX_FRIENDS || (pName[0] == 0 && pClan[0] == 0))\n\t\treturn;\n\n\t// make sure we don't have the friend already\n\tunsigned NameHash = str_quickhash(pName);\n\tunsigned ClanHash = str_quickhash(pClan);\n\tfor(int i = 0; i < m_NumFriends; ++i)\n\t{\n\t\tif(m_aFriends[i].m_NameHash == NameHash && m_aFriends[i].m_ClanHash == ClanHash)\n\t\t\treturn;\n\t}\n\n\tstr_copy(m_aFriends[m_NumFriends].m_aName, pName, sizeof(m_aFriends[m_NumFriends].m_aName));\n\tstr_copy(m_aFriends[m_NumFriends].m_aClan, pClan, sizeof(m_aFriends[m_NumFriends].m_aClan));\n\tm_aFriends[m_NumFriends].m_NameHash = NameHash;\n\tm_aFriends[m_NumFriends].m_ClanHash = ClanHash;\n\t++m_NumFriends;\n}\n\nvoid CFriends::RemoveFriend(const char *pName, const char *pClan)\n{\n\tunsigned NameHash = str_quickhash(pName);\n\tunsigned ClanHash = str_quickhash(pClan);\n\tfor(int i = 0; i < m_NumFriends; ++i)\n\t{\n\t\tif(m_aFriends[i].m_NameHash == NameHash && m_aFriends[i].m_ClanHash == ClanHash)\n\t\t{\n\t\t\tRemoveFriend(i);\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nvoid CFriends::RemoveFriend(int Index)\n{\n\tif(Index >= 0 && Index < m_NumFriends)\n\t{\n\t\tmem_move(&m_aFriends[Index], &m_aFriends[Index+1], sizeof(CFriendInfo)*(m_NumFriends-(Index+1)));\n\t\t--m_NumFriends;\n\t}\n\treturn;\n}\n\nvoid CFriends::ConfigSaveCallback(IConfig *pConfig, void *pUserData)\n{\n\tCFriends *pSelf = (CFriends *)pUserData;\n\tchar aBuf[128];\n\tconst char *pEnd = aBuf+sizeof(aBuf)-4;\n\tfor(int i = 0; i < pSelf->m_NumFriends; ++i)\n\t{\n\t\tstr_copy(aBuf, \"add_friend \", sizeof(aBuf));\n\n\t\tconst char *pSrc = pSelf->m_aFriends[i].m_aName;\n\t\tchar *pDst = aBuf+str_length(aBuf);\n\t\t*pDst++ = '\"';\n\t\twhile(*pSrc && pDst < pEnd)\n\t\t{\n\t\t\tif(*pSrc == '\"' || *pSrc == '\\\\') // escape \\ and \"\n\t\t\t\t*pDst++ = '\\\\';\n\t\t\t*pDst++ = *pSrc++;\n\t\t}\n\t\t*pDst++ = '\"';\n\t\t*pDst++ = ' ';\n\n\t\tpSrc = pSelf->m_aFriends[i].m_aClan;\n\t\t*pDst++ = '\"';\n\t\twhile(*pSrc && pDst < pEnd)\n\t\t{\n\t\t\tif(*pSrc == '\"' || *pSrc == '\\\\') // escape \\ and \"\n\t\t\t\t*pDst++ = '\\\\';\n\t\t\t*pDst++ = *pSrc++;\n\t\t}\n\t\t*pDst++ = '\"';\n\t\t*pDst++ = 0;\n\n\t\tpConfig->WriteLine(aBuf);\n\t}\n}\n"
  },
  {
    "path": "src/engine/client/friends.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_CLIENT_FRIENDS_H\n#define ENGINE_CLIENT_FRIENDS_H\n\n#include <engine/friends.h>\n\nclass CFriends : public IFriends\n{\n\tCFriendInfo m_aFriends[MAX_FRIENDS];\n\tint m_NumFriends;\n\n\tstatic void ConAddFriend(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConRemoveFriend(IConsole::IResult *pResult, void *pUserData);\n\n\tstatic void ConfigSaveCallback(IConfig *pConfig, void *pUserData);\n\npublic:\n\tCFriends();\n\n\tvoid Init();\n\n\tint NumFriends() const { return m_NumFriends; }\n\tconst CFriendInfo *GetFriend(int Index) const;\n\tint GetFriendState(const char *pName, const char *pClan) const;\n\tbool IsFriend(const char *pName, const char *pClan, bool PlayersOnly) const;\n\n\tvoid AddFriend(const char *pName, const char *pClan);\n\tvoid RemoveFriend(const char *pName, const char *pClan);\n\tvoid RemoveFriend(int Index);\n};\n\n#endif\n"
  },
  {
    "path": "src/engine/client/graphics_threaded.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n\n#include <base/detect.h>\n#include <base/math.h>\n#include <base/tl/threading.h>\n\n#include <base/system.h>\n#include <engine/external/pnglite/pnglite.h>\n\n#include <engine/shared/config.h>\n#include <engine/graphics.h>\n#include <engine/storage.h>\n#include <engine/keys.h>\n#include <engine/console.h>\n\n#include <math.h> // cosf, sinf\n\n#include \"graphics_threaded.h\"\n\nstatic CVideoMode g_aFakeModes[] = {\n\t{320,200,8,8,8}, {320,240,8,8,8}, {400,300,8,8,8},\n\t{512,384,8,8,8}, {640,400,8,8,8}, {640,480,8,8,8},\n\t{720,400,8,8,8}, {768,576,8,8,8}, {800,600,8,8,8},\n\t{1024,600,8,8,8}, {1024,768,8,8,8}, {1152,864,8,8,8},\n\t{1280,600,8,8,8}, {1280,720,8,8,8}, {1280,768,8,8,8},\n\t{1280,800,8,8,8}, {1280,960,8,8,8}, {1280,1024,8,8,8},\n\t{1360,768,8,8,8}, {1366,768,8,8,8}, {1368,768,8,8,8},\n\t{1400,1050,8,8,8}, {1440,900,8,8,8}, {1440,1050,8,8,8},\n\t{1600,900,8,8,8}, {1600,1000,8,8,8}, {1600,1200,8,8,8},\n\t{1680,1050,8,8,8}, {1792,1344,8,8,8}, {1800,1440,8,8,8},\n\t{1856,1392,8,8,8}, {1920,1080,8,8,8}, {1920,1200,8,8,8},\n\t{1920,1440,8,8,8}, {1920,2400,8,8,8}, {2048,1536,8,8,8}\n};\n\nvoid CGraphics_Threaded::FlushVertices()\n{\n\tif(m_NumVertices == 0)\n\t\treturn;\n\n\tint NumVerts = m_NumVertices;\n\tm_NumVertices = 0;\n\n\tCCommandBuffer::SCommand_Render Cmd;\n\tCmd.m_State = m_State;\n\n\tif(m_Drawing == DRAWING_QUADS)\n\t{\n\t\tCmd.m_PrimType = CCommandBuffer::PRIMTYPE_QUADS;\n\t\tCmd.m_PrimCount = NumVerts/4;\n\t}\n\telse if(m_Drawing == DRAWING_LINES)\n\t{\n\t\tCmd.m_PrimType = CCommandBuffer::PRIMTYPE_LINES;\n\t\tCmd.m_PrimCount = NumVerts/2;\n\t}\n\telse\n\t\treturn;\n\n\tCmd.m_pVertices = (CCommandBuffer::SVertex *)m_pCommandBuffer->AllocData(sizeof(CCommandBuffer::SVertex)*NumVerts);\n\tif(Cmd.m_pVertices == 0x0)\n\t{\n\t\t// kick command buffer and try again\n\t\tKickCommandBuffer();\n\n\t\tCmd.m_pVertices = (CCommandBuffer::SVertex *)m_pCommandBuffer->AllocData(sizeof(CCommandBuffer::SVertex)*NumVerts);\n\t\tif(Cmd.m_pVertices == 0x0)\n\t\t{\n\t\t\tdbg_msg(\"graphics\", \"failed to allocate data for vertices\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\t// check if we have enough free memory in the commandbuffer\n\tif(!m_pCommandBuffer->AddCommand(Cmd))\n\t{\n\t\t// kick command buffer and try again\n\t\tKickCommandBuffer();\n\t\t\n\t\tCmd.m_pVertices = (CCommandBuffer::SVertex *)m_pCommandBuffer->AllocData(sizeof(CCommandBuffer::SVertex)*NumVerts);\n\t\tif(Cmd.m_pVertices == 0x0)\n\t\t{\n\t\t\tdbg_msg(\"graphics\", \"failed to allocate data for vertices\");\n\t\t\treturn;\n\t\t}\n\n\t\tif(!m_pCommandBuffer->AddCommand(Cmd))\n\t\t{\n\t\t\tdbg_msg(\"graphics\", \"failed to allocate memory for render command\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\tmem_copy(Cmd.m_pVertices, m_aVertices, sizeof(CCommandBuffer::SVertex)*NumVerts);\n}\n\nvoid CGraphics_Threaded::AddVertices(int Count)\n{\n\tm_NumVertices += Count;\n\tif((m_NumVertices + Count) >= MAX_VERTICES)\n\t\tFlushVertices();\n}\n\nvoid CGraphics_Threaded::Rotate4(const CCommandBuffer::SPoint &rCenter, CCommandBuffer::SVertex *pPoints)\n{\n\tfloat c = cosf(m_Rotation);\n\tfloat s = sinf(m_Rotation);\n\tfloat x, y;\n\tint i;\n\n\tfor(i = 0; i < 4; i++)\n\t{\n\t\tx = pPoints[i].m_Pos.x - rCenter.x;\n\t\ty = pPoints[i].m_Pos.y - rCenter.y;\n\t\tpPoints[i].m_Pos.x = x * c - y * s + rCenter.x;\n\t\tpPoints[i].m_Pos.y = x * s + y * c + rCenter.y;\n\t}\n}\n\nCGraphics_Threaded::CGraphics_Threaded()\n{\n\tm_State.m_ScreenTL.x = 0;\n\tm_State.m_ScreenTL.y = 0;\n\tm_State.m_ScreenBR.x = 0;\n\tm_State.m_ScreenBR.y = 0;\n\tm_State.m_ClipEnable = false;\n\tm_State.m_ClipX = 0;\n\tm_State.m_ClipY = 0;\n\tm_State.m_ClipW = 0;\n\tm_State.m_ClipH = 0;\n\tm_State.m_Texture = -1;\n\tm_State.m_BlendMode = CCommandBuffer::BLEND_NONE;\n\tm_State.m_WrapMode = CCommandBuffer::WRAP_REPEAT;\n\n\tm_CurrentCommandBuffer = 0;\n\tm_pCommandBuffer = 0x0;\n\tm_apCommandBuffers[0] = 0x0;\n\tm_apCommandBuffers[1] = 0x0;\n\n\tm_NumVertices = 0;\n\n\tm_ScreenWidth = -1;\n\tm_ScreenHeight = -1;\n\n\tm_Rotation = 0;\n\tm_Drawing = 0;\n\n\tm_TextureMemoryUsage = 0;\n\n\tm_RenderEnable = true;\n\tm_DoScreenshot = false;\n}\n\nvoid CGraphics_Threaded::ClipEnable(int x, int y, int w, int h)\n{\n\tif(x < 0)\n\t\tw += x;\n\tif(y < 0)\n\t\th += y;\n\n\tx = clamp(x, 0, ScreenWidth());\n\ty = clamp(y, 0, ScreenHeight());\n\tw = clamp(w, 0, ScreenWidth()-x);\n\th = clamp(h, 0, ScreenHeight()-y);\n\n\tm_State.m_ClipEnable = true;\n\tm_State.m_ClipX = x;\n\tm_State.m_ClipY = ScreenHeight()-(y+h);\n\tm_State.m_ClipW = w;\n\tm_State.m_ClipH = h;\n}\n\nvoid CGraphics_Threaded::ClipDisable()\n{\n\tm_State.m_ClipEnable = false;\n}\n\nvoid CGraphics_Threaded::BlendNone()\n{\n\tm_State.m_BlendMode = CCommandBuffer::BLEND_NONE;\n}\n\nvoid CGraphics_Threaded::BlendNormal()\n{\n\tm_State.m_BlendMode = CCommandBuffer::BLEND_ALPHA;\n}\n\nvoid CGraphics_Threaded::BlendAdditive()\n{\n\tm_State.m_BlendMode = CCommandBuffer::BLEND_ADDITIVE;\n}\n\nvoid CGraphics_Threaded::WrapNormal()\n{\n\tm_State.m_WrapMode = CCommandBuffer::WRAP_REPEAT;\n}\n\nvoid CGraphics_Threaded::WrapClamp()\n{\n\tm_State.m_WrapMode = CCommandBuffer::WRAP_CLAMP;\n}\n\nint CGraphics_Threaded::MemoryUsage() const\n{\n\treturn m_pBackend->MemoryUsage();\n}\n\nvoid CGraphics_Threaded::MapScreen(float TopLeftX, float TopLeftY, float BottomRightX, float BottomRightY)\n{\n\tm_State.m_ScreenTL.x = TopLeftX;\n\tm_State.m_ScreenTL.y = TopLeftY;\n\tm_State.m_ScreenBR.x = BottomRightX;\n\tm_State.m_ScreenBR.y = BottomRightY;\n}\n\nvoid CGraphics_Threaded::GetScreen(float *pTopLeftX, float *pTopLeftY, float *pBottomRightX, float *pBottomRightY)\n{\n\t*pTopLeftX = m_State.m_ScreenTL.x;\n\t*pTopLeftY = m_State.m_ScreenTL.y;\n\t*pBottomRightX = m_State.m_ScreenBR.x;\n\t*pBottomRightY = m_State.m_ScreenBR.y;\n}\n\nvoid CGraphics_Threaded::LinesBegin()\n{\n\tdbg_assert(m_Drawing == 0, \"called Graphics()->LinesBegin twice\");\n\tm_Drawing = DRAWING_LINES;\n\tSetColor(1,1,1,1);\n}\n\nvoid CGraphics_Threaded::LinesEnd()\n{\n\tdbg_assert(m_Drawing == DRAWING_LINES, \"called Graphics()->LinesEnd without begin\");\n\tFlushVertices();\n\tm_Drawing = 0;\n}\n\nvoid CGraphics_Threaded::LinesDraw(const CLineItem *pArray, int Num)\n{\n\tdbg_assert(m_Drawing == DRAWING_LINES, \"called Graphics()->LinesDraw without begin\");\n\n\tfor(int i = 0; i < Num; ++i)\n\t{\n\t\tm_aVertices[m_NumVertices + 2*i].m_Pos.x = pArray[i].m_X0;\n\t\tm_aVertices[m_NumVertices + 2*i].m_Pos.y = pArray[i].m_Y0;\n\t\tm_aVertices[m_NumVertices + 2*i].m_Tex = m_aTexture[0];\n\t\tm_aVertices[m_NumVertices + 2*i].m_Color = m_aColor[0];\n\n\t\tm_aVertices[m_NumVertices + 2*i + 1].m_Pos.x = pArray[i].m_X1;\n\t\tm_aVertices[m_NumVertices + 2*i + 1].m_Pos.y = pArray[i].m_Y1;\n\t\tm_aVertices[m_NumVertices + 2*i + 1].m_Tex = m_aTexture[1];\n\t\tm_aVertices[m_NumVertices + 2*i + 1].m_Color = m_aColor[1];\n\t}\n\n\tAddVertices(2*Num);\n}\n\nint CGraphics_Threaded::UnloadTexture(CTextureHandle Index)\n{\n\tif(Index.Id() == m_InvalidTexture.Id())\n\t\treturn 0;\n\n\tif(!Index.IsValid())\n\t\treturn 0;\n\n\tCCommandBuffer::SCommand_Texture_Destroy Cmd;\n\tCmd.m_Slot = Index.Id();\n\tm_pCommandBuffer->AddCommand(Cmd);\n\n\tm_aTextureIndices[Index.Id()] = m_FirstFreeTexture;\n\tm_FirstFreeTexture = Index.Id();\n\treturn 0;\n}\n\nstatic int ImageFormatToTexFormat(int Format)\n{\n\tif(Format == CImageInfo::FORMAT_RGB) return CCommandBuffer::TEXFORMAT_RGB;\n\tif(Format == CImageInfo::FORMAT_RGBA) return CCommandBuffer::TEXFORMAT_RGBA;\n\tif(Format == CImageInfo::FORMAT_ALPHA) return CCommandBuffer::TEXFORMAT_ALPHA;\n\treturn CCommandBuffer::TEXFORMAT_RGBA;\n}\n\nstatic int ImageFormatToPixelSize(int Format)\n{\n\tswitch(Format)\n\t{\n\tcase CImageInfo::FORMAT_RGB: return 3;\n\tcase CImageInfo::FORMAT_ALPHA: return 1;\n\tdefault: return 4;\n\t}\n}\n\n\nint CGraphics_Threaded::LoadTextureRawSub(CTextureHandle TextureID, int x, int y, int Width, int Height, int Format, const void *pData)\n{\n\tCCommandBuffer::SCommand_Texture_Update Cmd;\n\tCmd.m_Slot = TextureID.Id();\n\tCmd.m_X = x;\n\tCmd.m_Y = y;\n\tCmd.m_Width = Width;\n\tCmd.m_Height = Height;\n\tCmd.m_Format = ImageFormatToTexFormat(Format);\n\n\t// calculate memory usage\n\tint MemSize = Width*Height*ImageFormatToPixelSize(Format);\n\n\t// copy texture data\n\tvoid *pTmpData = mem_alloc(MemSize, sizeof(void*));\n\tmem_copy(pTmpData, pData, MemSize);\n\tCmd.m_pData = pTmpData;\n\n\t//\n\tm_pCommandBuffer->AddCommand(Cmd);\n\treturn 0;\n}\n\nIGraphics::CTextureHandle CGraphics_Threaded::LoadTextureRaw(int Width, int Height, int Format, const void *pData, int StoreFormat, int Flags)\n{\n\t// don't waste memory on texture if we are stress testing\n\tif(g_Config.m_DbgStress)\n\t\treturn m_InvalidTexture;\n\n\t// grab texture\n\tint Tex = m_FirstFreeTexture;\n\tm_FirstFreeTexture = m_aTextureIndices[Tex];\n\tm_aTextureIndices[Tex] = -1;\n\n\tCCommandBuffer::SCommand_Texture_Create Cmd;\n\tCmd.m_Slot = Tex;\n\tCmd.m_Width = Width;\n\tCmd.m_Height = Height;\n\tCmd.m_PixelSize = ImageFormatToPixelSize(Format);\n\tCmd.m_Format = ImageFormatToTexFormat(Format);\n\tCmd.m_StoreFormat = ImageFormatToTexFormat(StoreFormat);\n\n\t// flags\n\tCmd.m_Flags = 0;\n\tif(Flags&IGraphics::TEXLOAD_NOMIPMAPS)\n\t\tCmd.m_Flags |= CCommandBuffer::TEXFLAG_NOMIPMAPS;\n\tif(g_Config.m_GfxTextureCompression)\n\t\tCmd.m_Flags |= CCommandBuffer::TEXFLAG_COMPRESSED;\n\tif(g_Config.m_GfxTextureQuality || Flags&TEXLOAD_NORESAMPLE)\n\t\tCmd.m_Flags |= CCommandBuffer::TEXFLAG_QUALITY;\n\n\t// copy texture data\n\tint MemSize = Width*Height*Cmd.m_PixelSize;\n\tvoid *pTmpData = mem_alloc(MemSize, sizeof(void*));\n\tmem_copy(pTmpData, pData, MemSize);\n\tCmd.m_pData = pTmpData;\n\n\t//\n\tm_pCommandBuffer->AddCommand(Cmd);\n\n\treturn CreateTextureHandle(Tex);\n}\n\n// simple uncompressed RGBA loaders\nIGraphics::CTextureHandle CGraphics_Threaded::LoadTexture(const char *pFilename, int StorageType, int StoreFormat, int Flags)\n{\n\tint l = str_length(pFilename);\n\tIGraphics::CTextureHandle ID;\n\tCImageInfo Img;\n\n\tif(l < 3)\n\t\treturn CTextureHandle();\n\tif(LoadPNG(&Img, pFilename, StorageType))\n\t{\n\t\tif (StoreFormat == CImageInfo::FORMAT_AUTO)\n\t\t\tStoreFormat = Img.m_Format;\n\n\t\tID = LoadTextureRaw(Img.m_Width, Img.m_Height, Img.m_Format, Img.m_pData, StoreFormat, Flags);\n\t\tmem_free(Img.m_pData);\n\t\tif(ID.Id() != m_InvalidTexture.Id() && g_Config.m_Debug)\n\t\t\tdbg_msg(\"graphics/texture\", \"loaded %s\", pFilename);\n\t\treturn ID;\n\t}\n\n\treturn m_InvalidTexture;\n}\n\nint CGraphics_Threaded::LoadPNG(CImageInfo *pImg, const char *pFilename, int StorageType)\n{\n\tchar aCompleteFilename[512];\n\tunsigned char *pBuffer;\n\tpng_t Png; // ignore_convention\n\n\t// open file for reading\n\tpng_init(0,0); // ignore_convention\n\n\tIOHANDLE File = m_pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType, aCompleteFilename, sizeof(aCompleteFilename));\n\tif(File)\n\t\tio_close(File);\n\telse\n\t{\n\t\tdbg_msg(\"game/png\", \"failed to open file. filename='%s'\", pFilename);\n\t\treturn 0;\n\t}\n\n\tint Error = png_open_file(&Png, aCompleteFilename); // ignore_convention\n\tif(Error != PNG_NO_ERROR)\n\t{\n\t\tdbg_msg(\"game/png\", \"failed to open file. filename='%s'\", aCompleteFilename);\n\t\tif(Error != PNG_FILE_ERROR)\n\t\t\tpng_close_file(&Png); // ignore_convention\n\t\treturn 0;\n\t}\n\n\tif(Png.depth != 8 || (Png.color_type != PNG_TRUECOLOR && Png.color_type != PNG_TRUECOLOR_ALPHA)) // ignore_convention\n\t{\n\t\tdbg_msg(\"game/png\", \"invalid format. filename='%s'\", aCompleteFilename);\n\t\tpng_close_file(&Png); // ignore_convention\n\t\treturn 0;\n\t}\n\n\tpBuffer = (unsigned char *)mem_alloc(Png.width * Png.height * Png.bpp, 1); // ignore_convention\n\tpng_get_data(&Png, pBuffer); // ignore_convention\n\tpng_close_file(&Png); // ignore_convention\n\n\tpImg->m_Width = Png.width; // ignore_convention\n\tpImg->m_Height = Png.height; // ignore_convention\n\tif(Png.color_type == PNG_TRUECOLOR) // ignore_convention\n\t\tpImg->m_Format = CImageInfo::FORMAT_RGB;\n\telse if(Png.color_type == PNG_TRUECOLOR_ALPHA) // ignore_convention\n\t\tpImg->m_Format = CImageInfo::FORMAT_RGBA;\n\tpImg->m_pData = pBuffer;\n\treturn 1;\n}\n\nvoid CGraphics_Threaded::KickCommandBuffer()\n{\n\tm_pBackend->RunBuffer(m_pCommandBuffer);\n\n\t// swap buffer\n\tm_CurrentCommandBuffer ^= 1;\n\tm_pCommandBuffer = m_apCommandBuffers[m_CurrentCommandBuffer];\n\tm_pCommandBuffer->Reset();\n}\n\nvoid CGraphics_Threaded::ScreenshotDirect(const char *pFilename)\n{\n\t// add swap command\n\tCImageInfo Image;\n\tmem_zero(&Image, sizeof(Image));\n\n\tCCommandBuffer::SCommand_Screenshot Cmd;\n\tCmd.m_pImage = &Image;\n\tm_pCommandBuffer->AddCommand(Cmd);\n\n\t// kick the buffer and wait for the result\n\tKickCommandBuffer();\n\tWaitForIdle();\n\n\tif(Image.m_pData)\n\t{\n\t\t// find filename\n\t\tchar aWholePath[1024];\n\t\tpng_t Png; // ignore_convention\n\n\t\tIOHANDLE File = m_pStorage->OpenFile(pFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE, aWholePath, sizeof(aWholePath));\n\t\tif(File)\n\t\t\tio_close(File);\n\n\t\t// save png\n\t\tchar aBuf[256];\n\t\tstr_format(aBuf, sizeof(aBuf), \"saved screenshot to '%s'\", aWholePath);\n\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"client\", aBuf);\n\t\tpng_open_file_write(&Png, aWholePath); // ignore_convention\n\t\tpng_set_data(&Png, Image.m_Width, Image.m_Height, 8, PNG_TRUECOLOR, (unsigned char *)Image.m_pData); // ignore_convention\n\t\tpng_close_file(&Png); // ignore_convention\n\n\t\tmem_free(Image.m_pData);\n\t}\n}\n\nvoid CGraphics_Threaded::TextureSet(CTextureHandle TextureID)\n{\n\tdbg_assert(m_Drawing == 0, \"called Graphics()->TextureSet within begin\");\n\tm_State.m_Texture = TextureID.Id();\n}\n\nvoid CGraphics_Threaded::Clear(float r, float g, float b)\n{\n\tCCommandBuffer::SCommand_Clear Cmd;\n\tCmd.m_Color.r = r;\n\tCmd.m_Color.g = g;\n\tCmd.m_Color.b = b;\n\tCmd.m_Color.a = 0;\n\tm_pCommandBuffer->AddCommand(Cmd);\n}\n\nvoid CGraphics_Threaded::QuadsBegin()\n{\n\tdbg_assert(m_Drawing == 0, \"called Graphics()->QuadsBegin twice\");\n\tm_Drawing = DRAWING_QUADS;\n\n\tQuadsSetSubset(0,0,1,1);\n\tQuadsSetRotation(0);\n\tSetColor(1,1,1,1);\n}\n\nvoid CGraphics_Threaded::QuadsEnd()\n{\n\tdbg_assert(m_Drawing == DRAWING_QUADS, \"called Graphics()->QuadsEnd without begin\");\n\tFlushVertices();\n\tm_Drawing = 0;\n}\n\nvoid CGraphics_Threaded::QuadsSetRotation(float Angle)\n{\n\tdbg_assert(m_Drawing == DRAWING_QUADS, \"called Graphics()->QuadsSetRotation without begin\");\n\tm_Rotation = Angle;\n}\n\nvoid CGraphics_Threaded::SetColorVertex(const CColorVertex *pArray, int Num)\n{\n\tdbg_assert(m_Drawing != 0, \"called Graphics()->SetColorVertex without begin\");\n\n\tfor(int i = 0; i < Num; ++i)\n\t{\n\t\tm_aColor[pArray[i].m_Index].r = pArray[i].m_R;\n\t\tm_aColor[pArray[i].m_Index].g = pArray[i].m_G;\n\t\tm_aColor[pArray[i].m_Index].b = pArray[i].m_B;\n\t\tm_aColor[pArray[i].m_Index].a = pArray[i].m_A;\n\t}\n}\n\nvoid CGraphics_Threaded::SetColor(float r, float g, float b, float a)\n{\n\tdbg_assert(m_Drawing != 0, \"called Graphics()->SetColor without begin\");\n\tCColorVertex Array[4] = {\n\t\tCColorVertex(0, r, g, b, a),\n\t\tCColorVertex(1, r, g, b, a),\n\t\tCColorVertex(2, r, g, b, a),\n\t\tCColorVertex(3, r, g, b, a)};\n\tSetColorVertex(Array, 4);\n}\n\nvoid CGraphics_Threaded::SetColor4(vec4 TopLeft, vec4 TopRight, vec4 BottomLeft, vec4 BottomRight)\n{\n\tdbg_assert(m_Drawing != 0, \"called Graphics()->SetColor without begin\");\n\tCColorVertex Array[4] = {\n\t\tCColorVertex(0, TopLeft.r, TopLeft.g, TopLeft.b, TopLeft.a),\n\t\tCColorVertex(1, TopRight.r, TopRight.g, TopRight.b, TopRight.a),\n\t\tCColorVertex(2, BottomRight.r, BottomRight.g, BottomRight.b, BottomRight.a),\n\t\tCColorVertex(3, BottomLeft.r, BottomLeft.g, BottomLeft.b, BottomLeft.a)};\n\tSetColorVertex(Array, 4);\n}\n\nvoid CGraphics_Threaded::QuadsSetSubset(float TlU, float TlV, float BrU, float BrV)\n{\n\tdbg_assert(m_Drawing == DRAWING_QUADS, \"called Graphics()->QuadsSetSubset without begin\");\n\n\tm_aTexture[0].u = TlU;\tm_aTexture[1].u = BrU;\n\tm_aTexture[0].v = TlV;\tm_aTexture[1].v = TlV;\n\n\tm_aTexture[3].u = TlU;\tm_aTexture[2].u = BrU;\n\tm_aTexture[3].v = BrV;\tm_aTexture[2].v = BrV;\n}\n\nvoid CGraphics_Threaded::QuadsSetSubsetFree(\n\tfloat x0, float y0, float x1, float y1,\n\tfloat x2, float y2, float x3, float y3)\n{\n\tm_aTexture[0].u = x0; m_aTexture[0].v = y0;\n\tm_aTexture[1].u = x1; m_aTexture[1].v = y1;\n\tm_aTexture[2].u = x2; m_aTexture[2].v = y2;\n\tm_aTexture[3].u = x3; m_aTexture[3].v = y3;\n}\n\nvoid CGraphics_Threaded::QuadsDraw(CQuadItem *pArray, int Num)\n{\n\tfor(int i = 0; i < Num; ++i)\n\t{\n\t\tpArray[i].m_X -= pArray[i].m_Width/2;\n\t\tpArray[i].m_Y -= pArray[i].m_Height/2;\n\t}\n\n\tQuadsDrawTL(pArray, Num);\n}\n\nvoid CGraphics_Threaded::QuadsDrawTL(const CQuadItem *pArray, int Num)\n{\n\tCCommandBuffer::SPoint Center;\n\tCenter.z = 0;\n\n\tdbg_assert(m_Drawing == DRAWING_QUADS, \"called Graphics()->QuadsDrawTL without begin\");\n\n\tfor(int i = 0; i < Num; ++i)\n\t{\n\t\tm_aVertices[m_NumVertices + 4*i].m_Pos.x = pArray[i].m_X;\n\t\tm_aVertices[m_NumVertices + 4*i].m_Pos.y = pArray[i].m_Y;\n\t\tm_aVertices[m_NumVertices + 4*i].m_Tex = m_aTexture[0];\n\t\tm_aVertices[m_NumVertices + 4*i].m_Color = m_aColor[0];\n\n\t\tm_aVertices[m_NumVertices + 4*i + 1].m_Pos.x = pArray[i].m_X + pArray[i].m_Width;\n\t\tm_aVertices[m_NumVertices + 4*i + 1].m_Pos.y = pArray[i].m_Y;\n\t\tm_aVertices[m_NumVertices + 4*i + 1].m_Tex = m_aTexture[1];\n\t\tm_aVertices[m_NumVertices + 4*i + 1].m_Color = m_aColor[1];\n\n\t\tm_aVertices[m_NumVertices + 4*i + 2].m_Pos.x = pArray[i].m_X + pArray[i].m_Width;\n\t\tm_aVertices[m_NumVertices + 4*i + 2].m_Pos.y = pArray[i].m_Y + pArray[i].m_Height;\n\t\tm_aVertices[m_NumVertices + 4*i + 2].m_Tex = m_aTexture[2];\n\t\tm_aVertices[m_NumVertices + 4*i + 2].m_Color = m_aColor[2];\n\n\t\tm_aVertices[m_NumVertices + 4*i + 3].m_Pos.x = pArray[i].m_X;\n\t\tm_aVertices[m_NumVertices + 4*i + 3].m_Pos.y = pArray[i].m_Y + pArray[i].m_Height;\n\t\tm_aVertices[m_NumVertices + 4*i + 3].m_Tex = m_aTexture[3];\n\t\tm_aVertices[m_NumVertices + 4*i + 3].m_Color = m_aColor[3];\n\n\t\tif(m_Rotation != 0)\n\t\t{\n\t\t\tCenter.x = pArray[i].m_X + pArray[i].m_Width/2;\n\t\t\tCenter.y = pArray[i].m_Y + pArray[i].m_Height/2;\n\n\t\t\tRotate4(Center, &m_aVertices[m_NumVertices + 4*i]);\n\t\t}\n\t}\n\n\tAddVertices(4*Num);\n}\n\nvoid CGraphics_Threaded::QuadsDrawFreeform(const CFreeformItem *pArray, int Num)\n{\n\tdbg_assert(m_Drawing == DRAWING_QUADS, \"called Graphics()->QuadsDrawFreeform without begin\");\n\n\tfor(int i = 0; i < Num; ++i)\n\t{\n\t\tm_aVertices[m_NumVertices + 4*i].m_Pos.x = pArray[i].m_X0;\n\t\tm_aVertices[m_NumVertices + 4*i].m_Pos.y = pArray[i].m_Y0;\n\t\tm_aVertices[m_NumVertices + 4*i].m_Tex = m_aTexture[0];\n\t\tm_aVertices[m_NumVertices + 4*i].m_Color = m_aColor[0];\n\n\t\tm_aVertices[m_NumVertices + 4*i + 1].m_Pos.x = pArray[i].m_X1;\n\t\tm_aVertices[m_NumVertices + 4*i + 1].m_Pos.y = pArray[i].m_Y1;\n\t\tm_aVertices[m_NumVertices + 4*i + 1].m_Tex = m_aTexture[1];\n\t\tm_aVertices[m_NumVertices + 4*i + 1].m_Color = m_aColor[1];\n\n\t\tm_aVertices[m_NumVertices + 4*i + 2].m_Pos.x = pArray[i].m_X3;\n\t\tm_aVertices[m_NumVertices + 4*i + 2].m_Pos.y = pArray[i].m_Y3;\n\t\tm_aVertices[m_NumVertices + 4*i + 2].m_Tex = m_aTexture[3];\n\t\tm_aVertices[m_NumVertices + 4*i + 2].m_Color = m_aColor[3];\n\n\t\tm_aVertices[m_NumVertices + 4*i + 3].m_Pos.x = pArray[i].m_X2;\n\t\tm_aVertices[m_NumVertices + 4*i + 3].m_Pos.y = pArray[i].m_Y2;\n\t\tm_aVertices[m_NumVertices + 4*i + 3].m_Tex = m_aTexture[2];\n\t\tm_aVertices[m_NumVertices + 4*i + 3].m_Color = m_aColor[2];\n\t}\n\n\tAddVertices(4*Num);\n}\n\nvoid CGraphics_Threaded::QuadsText(float x, float y, float Size, const char *pText)\n{\n\tfloat StartX = x;\n\n\twhile(*pText)\n\t{\n\t\tchar c = *pText;\n\t\tpText++;\n\n\t\tif(c == '\\n')\n\t\t{\n\t\t\tx = StartX;\n\t\t\ty += Size;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tQuadsSetSubset(\n\t\t\t\t(c%16)/16.0f,\n\t\t\t\t(c/16)/16.0f,\n\t\t\t\t(c%16)/16.0f+1.0f/16.0f,\n\t\t\t\t(c/16)/16.0f+1.0f/16.0f);\n\n\t\t\tCQuadItem QuadItem(x, y, Size, Size);\n\t\t\tQuadsDrawTL(&QuadItem, 1);\n\t\t\tx += Size/2;\n\t\t}\n\t}\n}\n\nint CGraphics_Threaded::IssueInit()\n{\n\tint Flags = 0;\n\tif(g_Config.m_GfxBorderless && g_Config.m_GfxFullscreen)\n\t{\n\t\tdbg_msg(\"gfx\", \"both borderless and fullscreen activated, disabling borderless\");\n\t\tg_Config.m_GfxBorderless = 0;\n\t}\n\n\tif(g_Config.m_GfxBorderless) Flags |= IGraphicsBackend::INITFLAG_BORDERLESS;\n\telse if(g_Config.m_GfxFullscreen) Flags |= IGraphicsBackend::INITFLAG_FULLSCREEN;\n\tif(g_Config.m_GfxVsync) Flags |= IGraphicsBackend::INITFLAG_VSYNC;\n\tif(g_Config.m_DbgResizable) Flags |= IGraphicsBackend::INITFLAG_RESIZABLE;\n\n\treturn m_pBackend->Init(\"Teeworlds\", &g_Config.m_GfxScreenWidth, &g_Config.m_GfxScreenHeight, g_Config.m_GfxFsaaSamples, Flags, &m_DesktopScreenWidth, &m_DesktopScreenHeight);\n}\n\nint CGraphics_Threaded::InitWindow()\n{\n\tif(IssueInit() == 0)\n\t\treturn 0;\n\n\t// try disabling fsaa\n\twhile(g_Config.m_GfxFsaaSamples)\n\t{\n\t\tg_Config.m_GfxFsaaSamples--;\n\n\t\tif(g_Config.m_GfxFsaaSamples)\n\t\t\tdbg_msg(\"gfx\", \"lowering FSAA to %d and trying again\", g_Config.m_GfxFsaaSamples);\n\t\telse\n\t\t\tdbg_msg(\"gfx\", \"disabling FSAA and trying again\");\n\n\t\tif(IssueInit() == 0)\n\t\t\treturn 0;\n\t}\n\n\t// try lowering the resolution\n\tif(g_Config.m_GfxScreenWidth != 640 || g_Config.m_GfxScreenHeight != 480)\n\t{\n\t\tdbg_msg(\"gfx\", \"setting resolution to 640x480 and trying again\");\n\t\tg_Config.m_GfxScreenWidth = 640;\n\t\tg_Config.m_GfxScreenHeight = 480;\n\n\t\tif(IssueInit() == 0)\n\t\t\treturn 0;\n\t}\n\n\tdbg_msg(\"gfx\", \"out of ideas. failed to init graphics\");\n\n\treturn -1;\n}\n\nint CGraphics_Threaded::Init()\n{\n\t// fetch pointers\n\tm_pStorage = Kernel()->RequestInterface<IStorage>();\n\tm_pConsole = Kernel()->RequestInterface<IConsole>();\n\n\t// Set all z to -5.0f\n\tfor(int i = 0; i < MAX_VERTICES; i++)\n\t\tm_aVertices[i].m_Pos.z = -5.0f;\n\n\t// init textures\n\tm_FirstFreeTexture = 0;\n\tfor(int i = 0; i < MAX_TEXTURES-1; i++)\n\t\tm_aTextureIndices[i] = i+1;\n\tm_aTextureIndices[MAX_TEXTURES-1] = -1;\n\n\tm_pBackend = CreateGraphicsBackend();\n\tif(InitWindow() != 0)\n\t\treturn -1;\n\n\t// fetch final resolusion\n\tm_ScreenWidth = g_Config.m_GfxScreenWidth;\n\tm_ScreenHeight = g_Config.m_GfxScreenHeight;\n\n\t// create command buffers\n\tfor(int i = 0; i < NUM_CMDBUFFERS; i++)\n\t\tm_apCommandBuffers[i] = new CCommandBuffer(128*1024, 2*1024*1024);\n\tm_pCommandBuffer = m_apCommandBuffers[0];\n\n\t// create null texture, will get id=0\n\tstatic const unsigned char aNullTextureData[] = {\n\t\t0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, 0x00,0xff,0x00,0xff, 0x00,0xff,0x00,0xff,\n\t\t0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, 0x00,0xff,0x00,0xff, 0x00,0xff,0x00,0xff,\n\t\t0x00,0x00,0xff,0xff, 0x00,0x00,0xff,0xff, 0xff,0xff,0x00,0xff, 0xff,0xff,0x00,0xff,\n\t\t0x00,0x00,0xff,0xff, 0x00,0x00,0xff,0xff, 0xff,0xff,0x00,0xff, 0xff,0xff,0x00,0xff,\n\t};\n\n\tm_InvalidTexture = LoadTextureRaw(4,4,CImageInfo::FORMAT_RGBA,aNullTextureData,CImageInfo::FORMAT_RGBA,TEXLOAD_NORESAMPLE);\n\treturn 0;\n}\n\nvoid CGraphics_Threaded::Shutdown()\n{\n\t// shutdown the backend\n\tm_pBackend->Shutdown();\n\tdelete m_pBackend;\n\tm_pBackend = 0x0;\n\n\t// delete the command buffers\n\tfor(int i = 0; i < NUM_CMDBUFFERS; i++)\n\t\tdelete m_apCommandBuffers[i];\n}\n\nvoid CGraphics_Threaded::Minimize()\n{\n\tm_pBackend->Minimize();\n}\n\nvoid CGraphics_Threaded::Maximize()\n{\n\t// TODO: SDL\n\tm_pBackend->Maximize();\n}\n\nint CGraphics_Threaded::WindowActive()\n{\n\treturn m_pBackend->WindowActive();\n}\n\nint CGraphics_Threaded::WindowOpen()\n{\n\treturn m_pBackend->WindowOpen();\n\n}\n\nvoid CGraphics_Threaded::TakeScreenshot(const char *pFilename)\n{\n\t// TODO: screenshot support\n\tchar aDate[20];\n\tstr_timestamp(aDate, sizeof(aDate));\n\tstr_format(m_aScreenshotName, sizeof(m_aScreenshotName), \"screenshots/%s_%s.png\", pFilename?pFilename:\"screenshot\", aDate);\n\tm_DoScreenshot = true;\n}\n\nvoid CGraphics_Threaded::Swap()\n{\n\t// TODO: screenshot support\n\tif(m_DoScreenshot)\n\t{\n\t\tif(WindowActive())\n\t\t\tScreenshotDirect(m_aScreenshotName);\n\t\tm_DoScreenshot = false;\n\t}\n\n\t// add swap command\n\tCCommandBuffer::SCommand_Swap Cmd;\n\tCmd.m_Finish = g_Config.m_GfxFinish;\n\tm_pCommandBuffer->AddCommand(Cmd);\n\n\t// kick the command buffer\n\tKickCommandBuffer();\n}\n\n// syncronization\nvoid CGraphics_Threaded::InsertSignal(semaphore *pSemaphore)\n{\n\tCCommandBuffer::SCommand_Signal Cmd;\n\tCmd.m_pSemaphore = pSemaphore;\n\tm_pCommandBuffer->AddCommand(Cmd);\n}\n\nbool CGraphics_Threaded::IsIdle()\n{\n\treturn m_pBackend->IsIdle();\n}\n\nvoid CGraphics_Threaded::WaitForIdle()\n{\n\tm_pBackend->WaitForIdle();\n}\n\nint CGraphics_Threaded::GetVideoModes(CVideoMode *pModes, int MaxModes)\n{\n\tif(g_Config.m_GfxDisplayAllModes)\n\t{\n\t\tint Count = sizeof(g_aFakeModes)/sizeof(CVideoMode);\n\t\tmem_copy(pModes, g_aFakeModes, sizeof(g_aFakeModes));\n\t\tif(MaxModes < Count)\n\t\t\tCount = MaxModes;\n\t\treturn Count;\n\t}\n\n\t// add videomodes command\n\tCImageInfo Image;\n\tmem_zero(&Image, sizeof(Image));\n\n\tint NumModes = 0;\n\tCCommandBuffer::SCommand_VideoModes Cmd;\n\tCmd.m_pModes = pModes;\n\tCmd.m_MaxModes = MaxModes;\n\tCmd.m_pNumModes = &NumModes;\n\tm_pCommandBuffer->AddCommand(Cmd);\n\n\t// kick the buffer and wait for the result and return it\n\tKickCommandBuffer();\n\tWaitForIdle();\n\treturn NumModes;\n}\n\nextern IEngineGraphics *CreateEngineGraphicsThreaded() { return new CGraphics_Threaded(); }\n"
  },
  {
    "path": "src/engine/client/graphics_threaded.h",
    "content": "#pragma once\n\n#include <engine/graphics.h>\n\nclass CCommandBuffer\n{\n\tclass CBuffer\n\t{\n\t\tunsigned char *m_pData;\n\t\tunsigned m_Size;\n\t\tunsigned m_Used;\n\tpublic:\n\t\tCBuffer(unsigned BufferSize)\n\t\t{\n\t\t\tm_Size = BufferSize;\n\t\t\tm_pData = new unsigned char[m_Size];\n\t\t\tm_Used = 0;\n\t\t}\n\n\t\t~CBuffer()\n\t\t{\n\t\t\tdelete [] m_pData;\n\t\t\tm_pData = 0x0;\n\t\t\tm_Used = 0;\n\t\t\tm_Size = 0;\n\t\t}\n\n\t\tvoid Reset()\n\t\t{\n\t\t\tm_Used = 0;\n\t\t}\n\n\t\tvoid *Alloc(unsigned Requested)\n\t\t{\n\t\t\tif(Requested + m_Used > m_Size)\n\t\t\t\treturn 0;\n\t\t\tvoid *pPtr = &m_pData[m_Used];\n\t\t\tm_Used += Requested;\n\t\t\treturn pPtr;\n\t\t}\n\n\t\tunsigned char *DataPtr() { return m_pData; }\n\t\tunsigned DataSize() { return m_Size; }\n\t\tunsigned DataUsed() { return m_Used; }\n\t};\n\npublic:\n\tCBuffer m_CmdBuffer;\n\tCBuffer m_DataBuffer;\n\n\tenum\n\t{\n\t\tMAX_TEXTURES=1024*4,\n\t};\n\n\tenum\n\t{\n\t\t// commadn groups\n\t\tCMDGROUP_CORE = 0, // commands that everyone has to implement\n\t\tCMDGROUP_PLATFORM_OPENGL = 10000, // commands specific to a platform\n\t\tCMDGROUP_PLATFORM_SDL = 20000,\n\n\t\t//\n\t\tCMD_NOP = CMDGROUP_CORE,\n\n\t\t//\n\t\tCMD_RUNBUFFER,\n\n\t\t// syncronization\n\t\tCMD_SIGNAL,\n\n\t\t// texture commands\n\t\tCMD_TEXTURE_CREATE,\n\t\tCMD_TEXTURE_DESTROY,\n\t\tCMD_TEXTURE_UPDATE,\n\n\t\t// rendering\n\t\tCMD_CLEAR,\n\t\tCMD_RENDER,\n\n\t\t// swap\n\t\tCMD_SWAP,\n\n\t\t// misc\n\t\tCMD_SCREENSHOT,\n\t\tCMD_VIDEOMODES,\n\n\t};\n\n\tenum\n\t{\n\t\tTEXFORMAT_INVALID = 0,\n\t\tTEXFORMAT_RGB,\n\t\tTEXFORMAT_RGBA,\n\t\tTEXFORMAT_ALPHA,\n\n\t\tTEXFLAG_NOMIPMAPS = 1,\n\t\tTEXFLAG_COMPRESSED = 2,\n\t\tTEXFLAG_QUALITY = 4,\n\t};\n\n\tenum\n\t{\n\t\t//\n\t\tPRIMTYPE_INVALID = 0,\n\t\tPRIMTYPE_LINES,\t\n\t\tPRIMTYPE_QUADS,\n\t};\n\n\tenum\n\t{\n\t\tBLEND_NONE = 0,\n\t\tBLEND_ALPHA,\n\t\tBLEND_ADDITIVE,\n\t};\n\n\tenum\n\t{\n\t\tWRAP_REPEAT = 0,\n\t\tWRAP_CLAMP,\n\t};\n\n\tstruct SPoint { float x, y, z; };\n\tstruct STexCoord { float u, v; };\n\tstruct SColor { float r, g, b, a; };\n\n\tstruct SVertex\n\t{\n\t\tSPoint m_Pos;\n\t\tSTexCoord m_Tex;\n\t\tSColor m_Color;\n\t};\n\n\tstruct SCommand\n\t{\n\tpublic:\n\t\tSCommand(unsigned Cmd) : m_Cmd(Cmd), m_Size(0) {}\n\t\tunsigned m_Cmd;\n\t\tunsigned m_Size;\n\t};\n\n\tstruct SState\n\t{\n\t\tint m_BlendMode;\n\t\tint m_WrapMode;\n\t\tint m_Texture;\n\t\tSPoint m_ScreenTL;\n\t\tSPoint m_ScreenBR;\n\n\t\t// clip\n\t\tbool m_ClipEnable;\n\t\tint m_ClipX;\n\t\tint m_ClipY;\n\t\tint m_ClipW;\n\t\tint m_ClipH;\n\t};\n\t\t\n\tstruct SCommand_Clear : public SCommand\n\t{\n\t\tSCommand_Clear() : SCommand(CMD_CLEAR) {}\n\t\tSColor m_Color;\n\t};\n\t\t\n\tstruct SCommand_Signal : public SCommand\n\t{\n\t\tSCommand_Signal() : SCommand(CMD_SIGNAL) {}\n\t\tsemaphore *m_pSemaphore;\n\t};\n\n\tstruct SCommand_RunBuffer : public SCommand\n\t{\n\t\tSCommand_RunBuffer() : SCommand(CMD_RUNBUFFER) {}\n\t\tCCommandBuffer *m_pOtherBuffer;\n\t};\n\n\tstruct SCommand_Render : public SCommand\n\t{\n\t\tSCommand_Render() : SCommand(CMD_RENDER) {}\n\t\tSState m_State;\n\t\tunsigned m_PrimType;\n\t\tunsigned m_PrimCount;\n\t\tSVertex *m_pVertices; // you should use the command buffer data to allocate vertices for this command\n\t};\n\n\tstruct SCommand_Screenshot : public SCommand\n\t{\n\t\tSCommand_Screenshot() : SCommand(CMD_SCREENSHOT) {}\n\t\tCImageInfo *m_pImage; // processor will fill this out, the one who adds this command must free the data as well\n\t};\n\n\tstruct SCommand_VideoModes : public SCommand\n\t{\n\t\tSCommand_VideoModes() : SCommand(CMD_VIDEOMODES) {}\n\n\t\tCVideoMode *m_pModes; // processor will fill this in\n\t\tint m_MaxModes; // maximum of modes the processor can write to the m_pModes\n\t\tint *m_pNumModes; // processor will write to this pointer\n\t};\n\n\tstruct SCommand_Swap : public SCommand\n\t{\n\t\tSCommand_Swap() : SCommand(CMD_SWAP) {}\n\n\t\tint m_Finish;\n\t};\n\n\tstruct SCommand_Texture_Create : public SCommand\n\t{\n\t\tSCommand_Texture_Create() : SCommand(CMD_TEXTURE_CREATE) {}\n\n\t\t// texture information\n\t\tint m_Slot;\n\n\t\tint m_Width;\n\t\tint m_Height;\n\t\tint m_PixelSize;\n\t\tint m_Format;\n\t\tint m_StoreFormat;\n\t\tint m_Flags;\n\t\tvoid *m_pData; // will be freed by the command processor\n\t};\n\n\tstruct SCommand_Texture_Update : public SCommand\n\t{\n\t\tSCommand_Texture_Update() : SCommand(CMD_TEXTURE_UPDATE) {}\n\n\t\t// texture information\n\t\tint m_Slot;\n\n\t\tint m_X;\n\t\tint m_Y;\n\t\tint m_Width;\n\t\tint m_Height;\n\t\tint m_Format;\n\t\tvoid *m_pData; // will be freed by the command processor\n\t};\n\n\n\tstruct SCommand_Texture_Destroy : public SCommand\n\t{\n\t\tSCommand_Texture_Destroy() : SCommand(CMD_TEXTURE_DESTROY) {}\n\n\t\t// texture information\n\t\tint m_Slot;\n\t};\n\t\n\t//\n\tCCommandBuffer(unsigned CmdBufferSize, unsigned DataBufferSize)\n\t: m_CmdBuffer(CmdBufferSize), m_DataBuffer(DataBufferSize)\n\t{\n\t}\n\n\tvoid *AllocData(unsigned WantedSize)\n\t{\n\t\treturn m_DataBuffer.Alloc(WantedSize);\n\t}\n\n\ttemplate<class T>\n\tbool AddCommand(const T &Command)\n\t{\n\t\t// make sure that we don't do something stupid like ->AddCommand(&Cmd);\n\t\t(void)static_cast<const SCommand *>(&Command);\n\n\t\t// allocate and copy the command into the buffer\n\t\tSCommand *pCmd = (SCommand *)m_CmdBuffer.Alloc(sizeof(Command));\n\t\tif(!pCmd)\n\t\t\treturn false;\n\t\tmem_copy(pCmd, &Command, sizeof(Command));\n\t\tpCmd->m_Size = sizeof(Command);\n\t\treturn true;\n\t}\n\n\tSCommand *GetCommand(unsigned *pIndex)\n\t{\n\t\tif(*pIndex >= m_CmdBuffer.DataUsed())\n\t\t\treturn NULL;\n\n\t\tSCommand *pCommand = (SCommand *)&m_CmdBuffer.DataPtr()[*pIndex];\n\t\t*pIndex += pCommand->m_Size;\n\t\treturn pCommand;\n\t}\n\n\tvoid Reset()\n\t{\n\t\tm_CmdBuffer.Reset();\n\t\tm_DataBuffer.Reset();\n\t}\n};\n\n// interface for the graphics backend\n// all these functions are called on the main thread\nclass IGraphicsBackend\n{\npublic:\n\tenum\n\t{\n\t\tINITFLAG_FULLSCREEN = 1,\n\t\tINITFLAG_VSYNC = 2,\n\t\tINITFLAG_RESIZABLE = 4,\n\t\tINITFLAG_BORDERLESS = 8,\n\t};\n\n\tvirtual ~IGraphicsBackend() {}\n\n\tvirtual int Init(const char *pName, int *Width, int *Height, int FsaaSamples, int Flags, int *pDesktopWidth, int *pDesktopHeight) = 0;\n\tvirtual int Shutdown() = 0;\n\n\tvirtual int MemoryUsage() const = 0;\n\n\tvirtual void Minimize() = 0;\n\tvirtual void Maximize() = 0;\n\tvirtual int WindowActive() = 0;\n\tvirtual int WindowOpen() = 0;\n\n\tvirtual void RunBuffer(CCommandBuffer *pBuffer) = 0;\n\tvirtual bool IsIdle() const = 0;\n\tvirtual void WaitForIdle() = 0;\n};\n\nclass CGraphics_Threaded : public IEngineGraphics\n{\n\tenum\n\t{\n\t\tNUM_CMDBUFFERS = 2,\n\n\t\tMAX_VERTICES = 32*1024,\n\t\tMAX_TEXTURES = 1024*4,\n\t\t\n\t\tDRAWING_QUADS=1,\n\t\tDRAWING_LINES=2\n\t};\n\n\tCCommandBuffer::SState m_State;\n\tIGraphicsBackend *m_pBackend;\n\n\tCCommandBuffer *m_apCommandBuffers[NUM_CMDBUFFERS];\n\tCCommandBuffer *m_pCommandBuffer;\n\tunsigned m_CurrentCommandBuffer;\n\n\t//\n\tclass IStorage *m_pStorage;\n\tclass IConsole *m_pConsole;\n\n\tCCommandBuffer::SVertex m_aVertices[MAX_VERTICES];\n\tint m_NumVertices;\n\n\tCCommandBuffer::SColor m_aColor[4];\n\tCCommandBuffer::STexCoord m_aTexture[4];\n\n\tbool m_RenderEnable;\n\n\tfloat m_Rotation;\n\tint m_Drawing;\n\tbool m_DoScreenshot;\n\tchar m_aScreenshotName[128];\n\n\tCTextureHandle m_InvalidTexture;\n\n\tint m_aTextureIndices[MAX_TEXTURES];\n\tint m_FirstFreeTexture;\n\tint m_TextureMemoryUsage;\n\n\tvoid FlushVertices();\n\tvoid AddVertices(int Count);\n\tvoid Rotate4(const CCommandBuffer::SPoint &rCenter, CCommandBuffer::SVertex *pPoints);\n\n\tvoid KickCommandBuffer();\n\n\tint IssueInit();\n\tint InitWindow();\npublic:\n\tCGraphics_Threaded();\n\n\tvirtual void ClipEnable(int x, int y, int w, int h);\n\tvirtual void ClipDisable();\n\n\tvirtual void BlendNone();\n\tvirtual void BlendNormal();\n\tvirtual void BlendAdditive();\n\n\tvirtual void WrapNormal();\n\tvirtual void WrapClamp();\n\n\tvirtual int MemoryUsage() const;\n\n\tvirtual void MapScreen(float TopLeftX, float TopLeftY, float BottomRightX, float BottomRightY);\n\tvirtual void GetScreen(float *pTopLeftX, float *pTopLeftY, float *pBottomRightX, float *pBottomRightY);\n\n\tvirtual void LinesBegin();\n\tvirtual void LinesEnd();\n\tvirtual void LinesDraw(const CLineItem *pArray, int Num);\n\n\tvirtual int UnloadTexture(IGraphics::CTextureHandle Index);\n\tvirtual IGraphics::CTextureHandle LoadTextureRaw(int Width, int Height, int Format, const void *pData, int StoreFormat, int Flags);\n\tvirtual int LoadTextureRawSub(IGraphics::CTextureHandle TextureID, int x, int y, int Width, int Height, int Format, const void *pData);\n\n\t// simple uncompressed RGBA loaders\n\tvirtual IGraphics::CTextureHandle LoadTexture(const char *pFilename, int StorageType, int StoreFormat, int Flags);\n\tvirtual int LoadPNG(CImageInfo *pImg, const char *pFilename, int StorageType);\n\n\tvoid ScreenshotDirect(const char *pFilename);\n\n\tvirtual void TextureSet(CTextureHandle TextureID);\n\n\tvirtual void Clear(float r, float g, float b);\n\n\tvirtual void QuadsBegin();\n\tvirtual void QuadsEnd();\n\tvirtual void QuadsSetRotation(float Angle);\n\n\tvirtual void SetColorVertex(const CColorVertex *pArray, int Num);\n\tvirtual void SetColor(float r, float g, float b, float a);\n\tvirtual void SetColor4(vec4 TopLeft, vec4 TopRight, vec4 BottomLeft, vec4 BottomRight);\n\n\tvirtual void QuadsSetSubset(float TlU, float TlV, float BrU, float BrV);\n\tvirtual void QuadsSetSubsetFree(\n\t\tfloat x0, float y0, float x1, float y1,\n\t\tfloat x2, float y2, float x3, float y3);\n\n\tvirtual void QuadsDraw(CQuadItem *pArray, int Num);\n\tvirtual void QuadsDrawTL(const CQuadItem *pArray, int Num);\n\tvirtual void QuadsDrawFreeform(const CFreeformItem *pArray, int Num);\n\tvirtual void QuadsText(float x, float y, float Size, const char *pText);\n\n\tvirtual void Minimize();\n\tvirtual void Maximize();\n\n\tvirtual int WindowActive();\n\tvirtual int WindowOpen();\n\n\tvirtual int Init();\n\tvirtual void Shutdown();\n\n\tvirtual void TakeScreenshot(const char *pFilename);\n\tvirtual void Swap();\n\n\tvirtual int GetVideoModes(CVideoMode *pModes, int MaxModes);\n\n\tvirtual int GetDesktopScreenWidth() { return m_DesktopScreenWidth; }\n\tvirtual int GetDesktopScreenHeight() { return m_DesktopScreenHeight; }\n\n\t// syncronization\n\tvirtual void InsertSignal(semaphore *pSemaphore);\n\tvirtual bool IsIdle();\n\tvirtual void WaitForIdle();\n};\n\nextern IGraphicsBackend *CreateGraphicsBackend();\n"
  },
  {
    "path": "src/engine/client/input.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include \"SDL.h\"\n\n#include <base/system.h>\n#include <engine/shared/config.h>\n#include <engine/graphics.h>\n#include <engine/input.h>\n#include <engine/keys.h>\n\n#include \"input.h\"\n\n//print >>f, \"int inp_key_code(const char *key_name) { int i; if (!strcmp(key_name, \\\"-?-\\\")) return -1; else for (i = 0; i < 512; i++) if (!strcmp(key_strings[i], key_name)) return i; return -1; }\"\n\n// this header is protected so you don't include it from anywere\n#define KEYS_INCLUDE\n#include \"keynames.h\"\n#undef KEYS_INCLUDE\n\nvoid CInput::AddEvent(int Unicode, int Key, int Flags)\n{\n\tif(m_NumEvents != INPUT_BUFFER_SIZE)\n\t{\n\t\tm_aInputEvents[m_NumEvents].m_Unicode = Unicode;\n\t\tm_aInputEvents[m_NumEvents].m_Key = Key;\n\t\tm_aInputEvents[m_NumEvents].m_Flags = Flags;\n\t\tm_NumEvents++;\n\t}\n}\n\nCInput::CInput()\n{\n\tmem_zero(m_aInputCount, sizeof(m_aInputCount));\n\tmem_zero(m_aInputState, sizeof(m_aInputState));\n\n\tm_InputCurrent = 0;\n\tm_InputGrabbed = 0;\n\tm_InputDispatched = false;\n\n\tm_LastRelease = 0;\n\tm_ReleaseDelta = -1;\n\n\tm_NumEvents = 0;\n}\n\nvoid CInput::Init()\n{\n\tm_pGraphics = Kernel()->RequestInterface<IEngineGraphics>();\n\tSDL_EnableUNICODE(1);\n\tSDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);\n}\n\nvoid CInput::MouseRelative(float *x, float *y)\n{\n\tint nx = 0, ny = 0;\n\tfloat Sens = g_Config.m_InpMousesens/100.0f;\n\n\tif(g_Config.m_InpGrab)\n\t\tSDL_GetRelativeMouseState(&nx, &ny);\n\telse\n\t{\n\t\tif(m_InputGrabbed)\n\t\t{\n\t\t\tSDL_GetMouseState(&nx,&ny);\n\t\t\tSDL_WarpMouse(Graphics()->ScreenWidth()/2,Graphics()->ScreenHeight()/2);\n\t\t\tnx -= Graphics()->ScreenWidth()/2; ny -= Graphics()->ScreenHeight()/2;\n\t\t}\n\t}\n\n\t*x = nx*Sens;\n\t*y = ny*Sens;\n}\n\nvoid CInput::MouseModeAbsolute()\n{\n\tSDL_ShowCursor(1);\n\tm_InputGrabbed = 0;\n\tif(g_Config.m_InpGrab)\n\t\tSDL_WM_GrabInput(SDL_GRAB_OFF);\n}\n\nvoid CInput::MouseModeRelative()\n{\n\tSDL_ShowCursor(0);\n\tm_InputGrabbed = 1;\n\tif(g_Config.m_InpGrab)\n\t\tSDL_WM_GrabInput(SDL_GRAB_ON);\n}\n\nint CInput::MouseDoubleClick()\n{\n\tif(m_ReleaseDelta >= 0 && m_ReleaseDelta < (time_freq() >> 2))\n\t{\n\t\tm_LastRelease = 0;\n\t\tm_ReleaseDelta = -1;\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nvoid CInput::ClearKeyStates()\n{\n\tmem_zero(m_aInputState, sizeof(m_aInputState));\n\tmem_zero(m_aInputCount, sizeof(m_aInputCount));\n}\n\nint CInput::KeyState(int Key)\n{\n\treturn m_aInputState[m_InputCurrent][Key];\n}\n\nint CInput::Update()\n{\n\tif(m_InputGrabbed && !Graphics()->WindowActive())\n\t\tMouseModeAbsolute();\n\n\t/*if(!input_grabbed && Graphics()->WindowActive())\n\t\tInput()->MouseModeRelative();*/\n\n\tif(m_InputDispatched)\n\t{\n\t\t// clear and begin count on the other one\n\t\tm_InputCurrent^=1;\n\t\tmem_zero(&m_aInputCount[m_InputCurrent], sizeof(m_aInputCount[m_InputCurrent]));\n\t\tmem_zero(&m_aInputState[m_InputCurrent], sizeof(m_aInputState[m_InputCurrent]));\n\t\tm_InputDispatched = false;\n\t}\n\n\t{\n\t\tint i;\n\t\tUint8 *pState = SDL_GetKeyState(&i);\n\t\tif(i >= KEY_LAST)\n\t\t\ti = KEY_LAST-1;\n\t\tmem_copy(m_aInputState[m_InputCurrent], pState, i);\n\t}\n\n\t// these states must always be updated manually because they are not in the GetKeyState from SDL\n\tint i = SDL_GetMouseState(NULL, NULL);\n\tif(i&SDL_BUTTON(1)) m_aInputState[m_InputCurrent][KEY_MOUSE_1] = 1; // 1 is left\n\tif(i&SDL_BUTTON(3)) m_aInputState[m_InputCurrent][KEY_MOUSE_2] = 1; // 3 is right\n\tif(i&SDL_BUTTON(2)) m_aInputState[m_InputCurrent][KEY_MOUSE_3] = 1; // 2 is middle\n\tif(i&SDL_BUTTON(4)) m_aInputState[m_InputCurrent][KEY_MOUSE_4] = 1;\n\tif(i&SDL_BUTTON(5)) m_aInputState[m_InputCurrent][KEY_MOUSE_5] = 1;\n\tif(i&SDL_BUTTON(6)) m_aInputState[m_InputCurrent][KEY_MOUSE_6] = 1;\n\tif(i&SDL_BUTTON(7)) m_aInputState[m_InputCurrent][KEY_MOUSE_7] = 1;\n\tif(i&SDL_BUTTON(8)) m_aInputState[m_InputCurrent][KEY_MOUSE_8] = 1;\n\n\t{\n\t\tSDL_Event Event;\n\n\t\twhile(SDL_PollEvent(&Event))\n\t\t{\n\t\t\tint Key = -1;\n\t\t\tint Action = IInput::FLAG_PRESS;\n\t\t\tswitch (Event.type)\n\t\t\t{\n\t\t\t\t// handle keys\n\t\t\t\tcase SDL_KEYDOWN:\n\t\t\t\t\t// skip private use area of the BMP(contains the unicodes for keyboard function keys on MacOS)\n\t\t\t\t\tif(Event.key.keysym.unicode < 0xE000 || Event.key.keysym.unicode > 0xF8FF)\t// ignore_convention\n\t\t\t\t\t\tAddEvent(Event.key.keysym.unicode, 0, 0); // ignore_convention\n\t\t\t\t\tKey = Event.key.keysym.sym; // ignore_convention\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDL_KEYUP:\n\t\t\t\t\tAction = IInput::FLAG_RELEASE;\n\t\t\t\t\tKey = Event.key.keysym.sym; // ignore_convention\n\t\t\t\t\tbreak;\n\n\t\t\t\t// handle mouse buttons\n\t\t\t\tcase SDL_MOUSEBUTTONUP:\n\t\t\t\t\tAction = IInput::FLAG_RELEASE;\n\n\t\t\t\t\tif(Event.button.button == 1) // ignore_convention\n\t\t\t\t\t{\n\t\t\t\t\t\tm_ReleaseDelta = time_get() - m_LastRelease;\n\t\t\t\t\t\tm_LastRelease = time_get();\n\t\t\t\t\t}\n\n\t\t\t\t\t// fall through\n\t\t\t\tcase SDL_MOUSEBUTTONDOWN:\n\t\t\t\t\tif(Event.button.button == SDL_BUTTON_LEFT) Key = KEY_MOUSE_1; // ignore_convention\n\t\t\t\t\tif(Event.button.button == SDL_BUTTON_RIGHT) Key = KEY_MOUSE_2; // ignore_convention\n\t\t\t\t\tif(Event.button.button == SDL_BUTTON_MIDDLE) Key = KEY_MOUSE_3; // ignore_convention\n\t\t\t\t\tif(Event.button.button == SDL_BUTTON_WHEELUP) Key = KEY_MOUSE_WHEEL_UP; // ignore_convention\n\t\t\t\t\tif(Event.button.button == SDL_BUTTON_WHEELDOWN) Key = KEY_MOUSE_WHEEL_DOWN; // ignore_convention\n\t\t\t\t\tif(Event.button.button == 6) Key = KEY_MOUSE_6; // ignore_convention\n\t\t\t\t\tif(Event.button.button == 7) Key = KEY_MOUSE_7; // ignore_convention\n\t\t\t\t\tif(Event.button.button == 8) Key = KEY_MOUSE_8; // ignore_convention\n\t\t\t\t\tbreak;\n\n\t\t\t\t// other messages\n\t\t\t\tcase SDL_QUIT:\n\t\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\t//\n\t\t\tif(Key != -1)\n\t\t\t{\n\t\t\t\tm_aInputCount[m_InputCurrent][Key].m_Presses++;\n\t\t\t\tif(Action == IInput::FLAG_PRESS)\n\t\t\t\t\tm_aInputState[m_InputCurrent][Key] = 1;\n\t\t\t\tAddEvent(0, Key, Action);\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n\nIEngineInput *CreateEngineInput() { return new CInput; }\n"
  },
  {
    "path": "src/engine/client/input.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_CLIENT_INPUT_H\n#define ENGINE_CLIENT_INPUT_H\n\nclass CInput : public IEngineInput\n{\n\tIEngineGraphics *m_pGraphics;\n\n\tint m_InputGrabbed;\n\n\tint64 m_LastRelease;\n\tint64 m_ReleaseDelta;\n\n\tvoid AddEvent(int Unicode, int Key, int Flags);\n\n\tIEngineGraphics *Graphics() { return m_pGraphics; }\n\npublic:\n\tCInput();\n\n\tvirtual void Init();\n\n\tvirtual void MouseRelative(float *x, float *y);\n\tvirtual void MouseModeAbsolute();\n\tvirtual void MouseModeRelative();\n\tvirtual int MouseDoubleClick();\n\n\tvoid ClearKeyStates();\n\tint KeyState(int Key);\n\n\tint ButtonPressed(int Button) { return m_aInputState[m_InputCurrent][Button]; }\n\n\tvirtual int Update();\n};\n\n#endif\n"
  },
  {
    "path": "src/engine/client/keynames.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n/* AUTO GENERATED! DO NOT EDIT MANUALLY! */\n\n#ifndef KEYS_INCLUDE\n#error do not include this header!\n#endif\n\n#include <string.h>\n\nconst char g_aaKeyStrings[512][16] =\n{\n\t\"first\",\n\t\"&1\",\n\t\"&2\",\n\t\"&3\",\n\t\"&4\",\n\t\"&5\",\n\t\"&6\",\n\t\"&7\",\n\t\"backspace\",\n\t\"tab\",\n\t\"&10\",\n\t\"&11\",\n\t\"clear\",\n\t\"return\",\n\t\"&14\",\n\t\"&15\",\n\t\"&16\",\n\t\"&17\",\n\t\"&18\",\n\t\"pause\",\n\t\"&20\",\n\t\"&21\",\n\t\"&22\",\n\t\"&23\",\n\t\"&24\",\n\t\"&25\",\n\t\"&26\",\n\t\"escape\",\n\t\"&28\",\n\t\"&29\",\n\t\"&30\",\n\t\"&31\",\n\t\"space\",\n\t\"exclaim\",\n\t\"quotedbl\",\n\t\"hash\",\n\t\"dollar\",\n\t\"&37\",\n\t\"ampersand\",\n\t\"quote\",\n\t\"leftparen\",\n\t\"rightparen\",\n\t\"asterisk\",\n\t\"plus\",\n\t\"comma\",\n\t\"minus\",\n\t\"period\",\n\t\"slash\",\n\t\"0\",\n\t\"1\",\n\t\"2\",\n\t\"3\",\n\t\"4\",\n\t\"5\",\n\t\"6\",\n\t\"7\",\n\t\"8\",\n\t\"9\",\n\t\"colon\",\n\t\"semicolon\",\n\t\"less\",\n\t\"equals\",\n\t\"greater\",\n\t\"question\",\n\t\"at\",\n\t\"&65\",\n\t\"&66\",\n\t\"&67\",\n\t\"&68\",\n\t\"&69\",\n\t\"&70\",\n\t\"&71\",\n\t\"&72\",\n\t\"&73\",\n\t\"&74\",\n\t\"&75\",\n\t\"&76\",\n\t\"&77\",\n\t\"&78\",\n\t\"&79\",\n\t\"&80\",\n\t\"&81\",\n\t\"&82\",\n\t\"&83\",\n\t\"&84\",\n\t\"&85\",\n\t\"&86\",\n\t\"&87\",\n\t\"&88\",\n\t\"&89\",\n\t\"&90\",\n\t\"leftbracket\",\n\t\"backslash\",\n\t\"rightbracket\",\n\t\"caret\",\n\t\"underscore\",\n\t\"backquote\",\n\t\"a\",\n\t\"b\",\n\t\"c\",\n\t\"d\",\n\t\"e\",\n\t\"f\",\n\t\"g\",\n\t\"h\",\n\t\"i\",\n\t\"j\",\n\t\"k\",\n\t\"l\",\n\t\"m\",\n\t\"n\",\n\t\"o\",\n\t\"p\",\n\t\"q\",\n\t\"r\",\n\t\"s\",\n\t\"t\",\n\t\"u\",\n\t\"v\",\n\t\"w\",\n\t\"x\",\n\t\"y\",\n\t\"z\",\n\t\"&123\",\n\t\"&124\",\n\t\"&125\",\n\t\"&126\",\n\t\"delete\",\n\t\"&128\",\n\t\"&129\",\n\t\"&130\",\n\t\"&131\",\n\t\"&132\",\n\t\"&133\",\n\t\"&134\",\n\t\"&135\",\n\t\"&136\",\n\t\"&137\",\n\t\"&138\",\n\t\"&139\",\n\t\"&140\",\n\t\"&141\",\n\t\"&142\",\n\t\"&143\",\n\t\"&144\",\n\t\"&145\",\n\t\"&146\",\n\t\"&147\",\n\t\"&148\",\n\t\"&149\",\n\t\"&150\",\n\t\"&151\",\n\t\"&152\",\n\t\"&153\",\n\t\"&154\",\n\t\"&155\",\n\t\"&156\",\n\t\"&157\",\n\t\"&158\",\n\t\"&159\",\n\t\"world_0\",\n\t\"world_1\",\n\t\"world_2\",\n\t\"world_3\",\n\t\"world_4\",\n\t\"world_5\",\n\t\"world_6\",\n\t\"world_7\",\n\t\"world_8\",\n\t\"world_9\",\n\t\"world_10\",\n\t\"world_11\",\n\t\"world_12\",\n\t\"world_13\",\n\t\"world_14\",\n\t\"world_15\",\n\t\"world_16\",\n\t\"world_17\",\n\t\"world_18\",\n\t\"world_19\",\n\t\"world_20\",\n\t\"world_21\",\n\t\"world_22\",\n\t\"world_23\",\n\t\"world_24\",\n\t\"world_25\",\n\t\"world_26\",\n\t\"world_27\",\n\t\"world_28\",\n\t\"world_29\",\n\t\"world_30\",\n\t\"world_31\",\n\t\"world_32\",\n\t\"world_33\",\n\t\"world_34\",\n\t\"world_35\",\n\t\"world_36\",\n\t\"world_37\",\n\t\"world_38\",\n\t\"world_39\",\n\t\"world_40\",\n\t\"world_41\",\n\t\"world_42\",\n\t\"world_43\",\n\t\"world_44\",\n\t\"world_45\",\n\t\"world_46\",\n\t\"world_47\",\n\t\"world_48\",\n\t\"world_49\",\n\t\"world_50\",\n\t\"world_51\",\n\t\"world_52\",\n\t\"world_53\",\n\t\"world_54\",\n\t\"world_55\",\n\t\"world_56\",\n\t\"world_57\",\n\t\"world_58\",\n\t\"world_59\",\n\t\"world_60\",\n\t\"world_61\",\n\t\"world_62\",\n\t\"world_63\",\n\t\"world_64\",\n\t\"world_65\",\n\t\"world_66\",\n\t\"world_67\",\n\t\"world_68\",\n\t\"world_69\",\n\t\"world_70\",\n\t\"world_71\",\n\t\"world_72\",\n\t\"world_73\",\n\t\"world_74\",\n\t\"world_75\",\n\t\"world_76\",\n\t\"world_77\",\n\t\"world_78\",\n\t\"world_79\",\n\t\"world_80\",\n\t\"world_81\",\n\t\"world_82\",\n\t\"world_83\",\n\t\"world_84\",\n\t\"world_85\",\n\t\"world_86\",\n\t\"world_87\",\n\t\"world_88\",\n\t\"world_89\",\n\t\"world_90\",\n\t\"world_91\",\n\t\"world_92\",\n\t\"world_93\",\n\t\"world_94\",\n\t\"world_95\",\n\t\"kp0\",\n\t\"kp1\",\n\t\"kp2\",\n\t\"kp3\",\n\t\"kp4\",\n\t\"kp5\",\n\t\"kp6\",\n\t\"kp7\",\n\t\"kp8\",\n\t\"kp9\",\n\t\"kp_period\",\n\t\"kp_divide\",\n\t\"kp_multiply\",\n\t\"kp_minus\",\n\t\"kp_plus\",\n\t\"kp_enter\",\n\t\"kp_equals\",\n\t\"up\",\n\t\"down\",\n\t\"right\",\n\t\"left\",\n\t\"insert\",\n\t\"home\",\n\t\"end\",\n\t\"pageup\",\n\t\"pagedown\",\n\t\"f1\",\n\t\"f2\",\n\t\"f3\",\n\t\"f4\",\n\t\"f5\",\n\t\"f6\",\n\t\"f7\",\n\t\"f8\",\n\t\"f9\",\n\t\"f10\",\n\t\"f11\",\n\t\"f12\",\n\t\"f13\",\n\t\"f14\",\n\t\"f15\",\n\t\"&297\",\n\t\"&298\",\n\t\"&299\",\n\t\"numlock\",\n\t\"capslock\",\n\t\"scrollock\",\n\t\"rshift\",\n\t\"lshift\",\n\t\"rctrl\",\n\t\"lctrl\",\n\t\"ralt\",\n\t\"lalt\",\n\t\"rmeta\",\n\t\"lmeta\",\n\t\"lsuper\",\n\t\"rsuper\",\n\t\"mode\",\n\t\"compose\",\n\t\"help\",\n\t\"print\",\n\t\"sysreq\",\n\t\"break\",\n\t\"menu\",\n\t\"power\",\n\t\"euro\",\n\t\"undo\",\n\t\"mouse1\",\n\t\"mouse2\",\n\t\"mouse3\",\n\t\"mouse4\",\n\t\"mouse5\",\n\t\"mouse6\",\n\t\"mouse7\",\n\t\"mouse8\",\n\t\"mousewheelup\",\n\t\"mousewheeldown\",\n\t\"&333\",\n\t\"&334\",\n\t\"&335\",\n\t\"&336\",\n\t\"&337\",\n\t\"&338\",\n\t\"&339\",\n\t\"&340\",\n\t\"&341\",\n\t\"&342\",\n\t\"&343\",\n\t\"&344\",\n\t\"&345\",\n\t\"&346\",\n\t\"&347\",\n\t\"&348\",\n\t\"&349\",\n\t\"&350\",\n\t\"&351\",\n\t\"&352\",\n\t\"&353\",\n\t\"&354\",\n\t\"&355\",\n\t\"&356\",\n\t\"&357\",\n\t\"&358\",\n\t\"&359\",\n\t\"&360\",\n\t\"&361\",\n\t\"&362\",\n\t\"&363\",\n\t\"&364\",\n\t\"&365\",\n\t\"&366\",\n\t\"&367\",\n\t\"&368\",\n\t\"&369\",\n\t\"&370\",\n\t\"&371\",\n\t\"&372\",\n\t\"&373\",\n\t\"&374\",\n\t\"&375\",\n\t\"&376\",\n\t\"&377\",\n\t\"&378\",\n\t\"&379\",\n\t\"&380\",\n\t\"&381\",\n\t\"&382\",\n\t\"&383\",\n\t\"&384\",\n\t\"&385\",\n\t\"&386\",\n\t\"&387\",\n\t\"&388\",\n\t\"&389\",\n\t\"&390\",\n\t\"&391\",\n\t\"&392\",\n\t\"&393\",\n\t\"&394\",\n\t\"&395\",\n\t\"&396\",\n\t\"&397\",\n\t\"&398\",\n\t\"&399\",\n\t\"&400\",\n\t\"&401\",\n\t\"&402\",\n\t\"&403\",\n\t\"&404\",\n\t\"&405\",\n\t\"&406\",\n\t\"&407\",\n\t\"&408\",\n\t\"&409\",\n\t\"&410\",\n\t\"&411\",\n\t\"&412\",\n\t\"&413\",\n\t\"&414\",\n\t\"&415\",\n\t\"&416\",\n\t\"&417\",\n\t\"&418\",\n\t\"&419\",\n\t\"&420\",\n\t\"&421\",\n\t\"&422\",\n\t\"&423\",\n\t\"&424\",\n\t\"&425\",\n\t\"&426\",\n\t\"&427\",\n\t\"&428\",\n\t\"&429\",\n\t\"&430\",\n\t\"&431\",\n\t\"&432\",\n\t\"&433\",\n\t\"&434\",\n\t\"&435\",\n\t\"&436\",\n\t\"&437\",\n\t\"&438\",\n\t\"&439\",\n\t\"&440\",\n\t\"&441\",\n\t\"&442\",\n\t\"&443\",\n\t\"&444\",\n\t\"&445\",\n\t\"&446\",\n\t\"&447\",\n\t\"&448\",\n\t\"&449\",\n\t\"&450\",\n\t\"&451\",\n\t\"&452\",\n\t\"&453\",\n\t\"&454\",\n\t\"&455\",\n\t\"&456\",\n\t\"&457\",\n\t\"&458\",\n\t\"&459\",\n\t\"&460\",\n\t\"&461\",\n\t\"&462\",\n\t\"&463\",\n\t\"&464\",\n\t\"&465\",\n\t\"&466\",\n\t\"&467\",\n\t\"&468\",\n\t\"&469\",\n\t\"&470\",\n\t\"&471\",\n\t\"&472\",\n\t\"&473\",\n\t\"&474\",\n\t\"&475\",\n\t\"&476\",\n\t\"&477\",\n\t\"&478\",\n\t\"&479\",\n\t\"&480\",\n\t\"&481\",\n\t\"&482\",\n\t\"&483\",\n\t\"&484\",\n\t\"&485\",\n\t\"&486\",\n\t\"&487\",\n\t\"&488\",\n\t\"&489\",\n\t\"&490\",\n\t\"&491\",\n\t\"&492\",\n\t\"&493\",\n\t\"&494\",\n\t\"&495\",\n\t\"&496\",\n\t\"&497\",\n\t\"&498\",\n\t\"&499\",\n\t\"&500\",\n\t\"&501\",\n\t\"&502\",\n\t\"&503\",\n\t\"&504\",\n\t\"&505\",\n\t\"&506\",\n\t\"&507\",\n\t\"&508\",\n\t\"&509\",\n\t\"&510\",\n\t\"&511\",\n};\n\n"
  },
  {
    "path": "src/engine/client/serverbrowser.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <algorithm> // sort  TODO: remove this\n\n#include <base/math.h>\n#include <base/system.h>\n\n#include <engine/shared/config.h>\n#include <engine/shared/memheap.h>\n#include <engine/shared/network.h>\n#include <engine/shared/protocol.h>\n\n#include <engine/config.h>\n#include <engine/console.h>\n#include <engine/engine.h>\n#include <engine/friends.h>\n#include <engine/masterserver.h>\n\n#include <mastersrv/mastersrv.h>\n\n#include \"serverbrowser.h\"\n\nclass SortWrap\n{\n\ttypedef bool (CServerBrowser::CServerFilter::*SortFunc)(int, int) const;\n\tSortFunc m_pfnSort;\n\tCServerBrowser::CServerFilter *m_pThis;\npublic:\n\tSortWrap(CServerBrowser::CServerFilter *t, SortFunc f) : m_pfnSort(f), m_pThis(t) {}\n\tbool operator()(int a, int b) { return (g_Config.m_BrSortOrder ? (m_pThis->*m_pfnSort)(b, a) : (m_pThis->*m_pfnSort)(a, b)); }\n};\n\nCServerBrowser::CServerBrowser()\n{\n\tm_pMasterServer = 0;\n\n\t// favorites\n\tm_NumFavoriteServers = 0;\n\tm_FavLookup.m_LookupCount = 0;\n\tm_FavLookup.m_Active = false;\n\n\t//\n\tmem_zero(m_aServerlistIp, sizeof(m_aServerlistIp));\n\n\tm_pFirstReqServer = 0; // request list\n\tm_pLastReqServer = 0;\n\tm_NumRequests = 0;\n\n\tm_NeedRefresh = 0;\n\n\tm_NumServers = 0;\n\tm_NumServerCapacity = 0;\n\n\tm_NumPlayers = 0;\n\n\t// the token is to keep server refresh separated from each other\n\tm_CurrentToken = 1;\n\n\tm_ServerlistType = 0;\n\tm_BroadcastTime = 0;\n}\n\nint CServerBrowser::AddFilter(int SortHash, int Ping, int Country, const char* pGametype, const char* pServerAddress)\n{\n\tCServerFilter Filter;\n\tFilter.m_SortHash = SortHash;\n\tFilter.m_Ping = Ping;\n\tFilter.m_Country = Country;\n\tstr_copy(Filter.m_aGametype, pGametype, sizeof(Filter.m_aGametype));\n\tstr_copy(Filter.m_aServerAddress, pServerAddress, sizeof(Filter.m_aServerAddress));\n\tFilter.m_pSortedServerlist = 0;\n\tFilter.m_NumSortedServers = 0;\n\tFilter.m_NumSortedServersCapacity = 0;\n\tFilter.m_NumPlayers = 0;\n\tFilter.m_pServerBrowser = this;\n\tm_lFilters.add(Filter);\n\n\treturn m_lFilters.size()-1;\n}\n\nvoid CServerBrowser::GetFilter(int Index, int *pSortHash, int *pPing, int *pCountry, char* pGametype, char* pServerAddress)\n{\n\tCServerFilter *pFilter = &m_lFilters[Index];\n\t*pSortHash = pFilter->m_SortHash;\n\t*pPing = pFilter->m_Ping;\n\t*pCountry = pFilter->m_Country;\n\tstr_copy(pGametype, pFilter->m_aGametype, sizeof(pFilter->m_aGametype));\n\tstr_copy(pServerAddress, pFilter->m_aServerAddress, sizeof(pFilter->m_aServerAddress));\n}\n\nvoid CServerBrowser::SetFilter(int Index, int SortHash, int Ping, int Country, const char* pGametype, const char* pServerAddress)\n{\n\tCServerFilter *pFilter = &m_lFilters[Index];\n\tpFilter->m_SortHash = SortHash;\n\tpFilter->m_Ping = Ping;\n\tpFilter->m_Country = Country;\n\tstr_copy(pFilter->m_aGametype, pGametype, sizeof(pFilter->m_aGametype));\n\tstr_copy(pFilter->m_aServerAddress, pServerAddress, sizeof(pFilter->m_aServerAddress));\n\n\tpFilter->m_pServerBrowser->Update(true);\n}\n\nvoid CServerBrowser::RemoveFilter(int Index)\n{\n\tm_lFilters.remove_index(Index);\n}\n\nvoid CServerBrowser::SetBaseInfo(class CNetClient *pClient, const char *pNetVersion)\n{\n\tm_pNetClient = pClient;\n\tstr_copy(m_aNetVersion, pNetVersion, sizeof(m_aNetVersion));\n\tm_pMasterServer = Kernel()->RequestInterface<IMasterServer>();\n\tm_pConsole = Kernel()->RequestInterface<IConsole>();\n\tm_pEngine = Kernel()->RequestInterface<IEngine>();\n\tm_pFriends = Kernel()->RequestInterface<IFriends>();\n\tIConfig *pConfig = Kernel()->RequestInterface<IConfig>();\n\tif(pConfig)\n\t\tpConfig->RegisterCallback(ConfigSaveCallback, this);\n\n\tm_pConsole->Register(\"add_favorite\", \"s\", CFGFLAG_CLIENT, ConAddFavorite, this, \"Add a server as a favorite\");\n\tm_pConsole->Register(\"remove_favorite\", \"s\", CFGFLAG_CLIENT, ConRemoveFavorite, this, \"Remove a server from favorites\");\n}\n\nconst CServerInfo *CServerBrowser::SortedGet(int FilterIndex, int Index) const\n{\n\tif(Index < 0 || Index >= m_lFilters[FilterIndex].m_NumSortedServers)\n\t\treturn 0;\n\treturn &m_ppServerlist[m_lFilters[FilterIndex].m_pSortedServerlist[Index]]->m_Info;\n}\n\nconst void *CServerBrowser::GetID(int FilterIndex, int Index) const\n{\n\treturn &m_lFilters[FilterIndex].m_pSortedServerlist[Index];\n}\n\nCServerBrowser::CServerFilter::~CServerFilter()\n{\n\tmem_free(m_pSortedServerlist);\n}\n\nbool CServerBrowser::CServerFilter::SortCompareName(int Index1, int Index2) const\n{\n\tCServerEntry *a = m_pServerBrowser->m_ppServerlist[Index1];\n\tCServerEntry *b = m_pServerBrowser->m_ppServerlist[Index2];\n\t//\tmake sure empty entries are listed last\n\treturn (a->m_GotInfo && b->m_GotInfo) || (!a->m_GotInfo && !b->m_GotInfo) ? str_comp_nocase(a->m_Info.m_aName, b->m_Info.m_aName) < 0 :\n\t\t\ta->m_GotInfo ? true : false;\n}\n\nbool CServerBrowser::CServerFilter::SortCompareMap(int Index1, int Index2) const\n{\n\tCServerEntry *a = m_pServerBrowser->m_ppServerlist[Index1];\n\tCServerEntry *b = m_pServerBrowser->m_ppServerlist[Index2];\n\tint Result = str_comp_nocase(a->m_Info.m_aMap, b->m_Info.m_aMap);\n\treturn Result < 0 || (Result == 0 && (a->m_Info.m_Flags&FLAG_PURE) && !(b->m_Info.m_Flags&FLAG_PURE));\n}\n\nbool CServerBrowser::CServerFilter::SortComparePing(int Index1, int Index2) const\n{\n\tCServerEntry *a = m_pServerBrowser->m_ppServerlist[Index1];\n\tCServerEntry *b = m_pServerBrowser->m_ppServerlist[Index2];\n\treturn a->m_Info.m_Latency < b->m_Info.m_Latency ||\n\t\t(a->m_Info.m_Latency == b->m_Info.m_Latency && (a->m_Info.m_Flags&FLAG_PURE) && !(b->m_Info.m_Flags&FLAG_PURE));\n}\n\nbool CServerBrowser::CServerFilter::SortCompareGametype(int Index1, int Index2) const\n{\n\tCServerEntry *a = m_pServerBrowser->m_ppServerlist[Index1];\n\tCServerEntry *b = m_pServerBrowser->m_ppServerlist[Index2];\n\treturn str_comp_nocase(a->m_Info.m_aGameType, b->m_Info.m_aGameType) < 0;\n}\n\nbool CServerBrowser::CServerFilter::SortCompareNumPlayers(int Index1, int Index2) const\n{\n\tCServerEntry *a = m_pServerBrowser->m_ppServerlist[Index1];\n\tCServerEntry *b = m_pServerBrowser->m_ppServerlist[Index2];\n\treturn a->m_Info.m_NumPlayers < b->m_Info.m_NumPlayers ||\n\t\t(a->m_Info.m_NumPlayers == b->m_Info.m_NumPlayers && !(a->m_Info.m_Flags&FLAG_PURE) && (b->m_Info.m_Flags&FLAG_PURE));\n}\n\nbool CServerBrowser::CServerFilter::SortCompareNumClients(int Index1, int Index2) const\n{\n\tCServerEntry *a = m_pServerBrowser->m_ppServerlist[Index1];\n\tCServerEntry *b = m_pServerBrowser->m_ppServerlist[Index2];\n\treturn a->m_Info.m_NumClients < b->m_Info.m_NumClients ||\n\t\t(a->m_Info.m_NumClients == b->m_Info.m_NumClients && !(a->m_Info.m_Flags&FLAG_PURE) && (b->m_Info.m_Flags&FLAG_PURE));\n}\n\nvoid CServerBrowser::CServerFilter::Filter()\n{\n\tint NumServers = m_pServerBrowser->m_NumServers;\n\tm_NumSortedServers = 0;\n\tm_NumPlayers = 0;\n\n\t// allocate the sorted list\n\tif(m_NumSortedServersCapacity < NumServers)\n\t{\n\t\tif(m_pSortedServerlist)\n\t\t\tmem_free(m_pSortedServerlist);\n\t\tm_NumSortedServersCapacity = max(1000, NumServers+NumServers/2);\n\t\tm_pSortedServerlist = (int *)mem_alloc(m_NumSortedServersCapacity*sizeof(int), 1);\n\t}\n\n\t// filter the servers\n\tfor(int i = 0; i < NumServers; i++)\n\t{\n\t\tint Filtered = 0;\n\n\t\tif(m_SortHash&FILTER_EMPTY && ((m_SortHash&FILTER_SPECTATORS && m_pServerBrowser->m_ppServerlist[i]->m_Info.m_NumPlayers == 0) || m_pServerBrowser->m_ppServerlist[i]->m_Info.m_NumClients == 0))\n\t\t\tFiltered = 1;\n\t\telse if(m_SortHash&FILTER_FULL && ((m_SortHash&FILTER_SPECTATORS && m_pServerBrowser->m_ppServerlist[i]->m_Info.m_NumPlayers == m_pServerBrowser->m_ppServerlist[i]->m_Info.m_MaxPlayers) ||\n\t\t\t\tm_pServerBrowser->m_ppServerlist[i]->m_Info.m_NumClients == m_pServerBrowser->m_ppServerlist[i]->m_Info.m_MaxClients))\n\t\t\tFiltered = 1;\n\t\telse if(m_SortHash&FILTER_PW && m_pServerBrowser->m_ppServerlist[i]->m_Info.m_Flags&FLAG_PASSWORD)\n\t\t\tFiltered = 1;\n\t\telse if(m_SortHash&FILTER_FAVORITE && !m_pServerBrowser->m_ppServerlist[i]->m_Info.m_Favorite)\n\t\t\tFiltered = 1;\n\t\telse if(m_SortHash&FILTER_PURE && !(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_Flags&FLAG_PURE))\n\t\t\tFiltered = 1;\n\t\telse if(m_SortHash&FILTER_PURE_MAP &&  !(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_Flags&FLAG_PUREMAP))\n\t\t\tFiltered = 1;\n\t\telse if(m_SortHash&FILTER_PING && m_Ping < m_pServerBrowser->m_ppServerlist[i]->m_Info.m_Latency)\n\t\t\tFiltered = 1;\n\t\telse if(m_SortHash&FILTER_COMPAT_VERSION && str_comp_num(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aVersion, m_pServerBrowser->m_aNetVersion, 3) != 0)\n\t\t\tFiltered = 1;\n\t\telse if(m_aServerAddress[0] && !str_find_nocase(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aAddress, m_aServerAddress))\n\t\t\tFiltered = 1;\n\t\telse if(m_SortHash&FILTER_GAMETYPE_STRICT && m_aGametype[0] && str_comp_nocase(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aGameType, m_aGametype))\n\t\t\tFiltered = 1;\n\t\telse if(!(m_SortHash&FILTER_GAMETYPE_STRICT) && m_aGametype[0] && !str_find_nocase(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aGameType, m_aGametype))\n\t\t\tFiltered = 1;\n\t\telse\n\t\t{\n\t\t\tif(m_SortHash&FILTER_COUNTRY)\n\t\t\t{\n\t\t\t\tFiltered = 1;\n\t\t\t\t// match against player country\n\t\t\t\tfor(int p = 0; p < m_pServerBrowser->m_ppServerlist[i]->m_Info.m_NumClients; p++)\n\t\t\t\t{\n\t\t\t\t\tif(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aClients[p].m_Country == m_Country)\n\t\t\t\t\t{\n\t\t\t\t\t\tFiltered = 0;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(!Filtered && g_Config.m_BrFilterString[0] != 0)\n\t\t\t{\n\t\t\t\tint MatchFound = 0;\n\n\t\t\t\tm_pServerBrowser->m_ppServerlist[i]->m_Info.m_QuickSearchHit = 0;\n\n\t\t\t\t// match against server name\n\t\t\t\tif(str_find_nocase(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aName, g_Config.m_BrFilterString))\n\t\t\t\t{\n\t\t\t\t\tMatchFound = 1;\n\t\t\t\t\tm_pServerBrowser->m_ppServerlist[i]->m_Info.m_QuickSearchHit |= IServerBrowser::QUICK_SERVERNAME;\n\t\t\t\t}\n\n\t\t\t\t// match against players\n\t\t\t\tfor(int p = 0; p < m_pServerBrowser->m_ppServerlist[i]->m_Info.m_NumClients; p++)\n\t\t\t\t{\n\t\t\t\t\tif(str_find_nocase(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aClients[p].m_aName, g_Config.m_BrFilterString) ||\n\t\t\t\t\t\tstr_find_nocase(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aClients[p].m_aClan, g_Config.m_BrFilterString))\n\t\t\t\t\t{\n\t\t\t\t\t\tMatchFound = 1;\n\t\t\t\t\t\tm_pServerBrowser->m_ppServerlist[i]->m_Info.m_QuickSearchHit |= IServerBrowser::QUICK_PLAYER;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// match against map\n\t\t\t\tif(str_find_nocase(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aMap, g_Config.m_BrFilterString))\n\t\t\t\t{\n\t\t\t\t\tMatchFound = 1;\n\t\t\t\t\tm_pServerBrowser->m_ppServerlist[i]->m_Info.m_QuickSearchHit |= IServerBrowser::QUICK_MAPNAME;\n\t\t\t\t}\n\n\t\t\t\tif(!MatchFound)\n\t\t\t\t\tFiltered = 1;\n\t\t\t}\n\t\t}\n\n\t\tif(Filtered == 0)\n\t\t{\n\t\t\t// check for friend\n\t\t\tm_pServerBrowser->m_ppServerlist[i]->m_Info.m_FriendState = IFriends::FRIEND_NO;\n\t\t\tfor(int p = 0; p < m_pServerBrowser->m_ppServerlist[i]->m_Info.m_NumClients; p++)\n\t\t\t{\n\t\t\t\tm_pServerBrowser->m_ppServerlist[i]->m_Info.m_aClients[p].m_FriendState = m_pServerBrowser->m_pFriends->GetFriendState(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aClients[p].m_aName,\n\t\t\t\t\tm_pServerBrowser->m_ppServerlist[i]->m_Info.m_aClients[p].m_aClan);\n\t\t\t\tm_pServerBrowser->m_ppServerlist[i]->m_Info.m_FriendState = max(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_FriendState, m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aClients[p].m_FriendState);\n\t\t\t}\n\n\t\t\tif(!(m_SortHash&FILTER_FRIENDS) || m_pServerBrowser->m_ppServerlist[i]->m_Info.m_FriendState != IFriends::FRIEND_NO)\n\t\t\t{\n\t\t\t\tm_pSortedServerlist[m_NumSortedServers++] = i;\n\t\t\t\tm_NumPlayers += m_pServerBrowser->m_ppServerlist[i]->m_Info.m_NumPlayers;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint CServerBrowser::CServerFilter::SortHash() const\n{\n\tint i = g_Config.m_BrSort&0xf;\n\ti |= g_Config.m_BrSortOrder<<4;\n\tif(m_SortHash&FILTER_EMPTY) i |= 1<<5;\n\tif(m_SortHash&FILTER_FULL) i |= 1<<6;\n\tif(m_SortHash&FILTER_SPECTATORS) i |= 1<<7;\n\tif(m_SortHash&FILTER_FRIENDS) i |= 1<<8;\n\tif(m_SortHash&FILTER_PW) i |= 1<<9;\n\tif(m_SortHash&FILTER_FAVORITE) i |= 1<<10;\n\tif(m_SortHash&FILTER_COMPAT_VERSION) i |= 1<<11;\n\tif(m_SortHash&FILTER_PURE) i |= 1<<12;\n\tif(m_SortHash&FILTER_PURE_MAP) i |= 1<<13;\n\tif(m_SortHash&FILTER_GAMETYPE_STRICT) i |= 1<<14;\n\tif(m_SortHash&FILTER_COUNTRY) i |= 1<<15;\n\tif(m_SortHash&FILTER_PING) i |= 1<<16;\n\treturn i;\n}\n\nvoid CServerBrowser::CServerFilter::Sort()\n{\n\t// create filtered list\n\tFilter();\n\n\t// sort\n\tswitch(g_Config.m_BrSort)\n\t{\n\tcase IServerBrowser::SORT_NAME:\n\t\tstd::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::CServerFilter::SortCompareName));\n\t\tbreak;\n\tcase IServerBrowser::SORT_PING:\n\t\tstd::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::CServerFilter::SortComparePing));\n\t\tbreak;\n\tcase IServerBrowser::SORT_MAP:\n\t\tstd::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::CServerFilter::SortCompareMap));\n\t\tbreak;\n\tcase IServerBrowser::SORT_NUMPLAYERS:\n\t\tstd::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this,\n\t\t\t\t\tg_Config.m_BrFilterSpectators ? &CServerBrowser::CServerFilter::SortCompareNumPlayers : &CServerBrowser::CServerFilter::SortCompareNumClients));\n\t\tbreak;\n\tcase IServerBrowser::SORT_GAMETYPE:\n\t\tstd::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::CServerFilter::SortCompareGametype));\n\t}\n\n\t// set indexes\n\t/*for(i = 0; i < m_NumSortedServers; i++)\n\t\tm_ppServerlist[m_pSortedServerlist[i]]->m_Info.m_SortedIndex = i;*/\n\n\tm_SortHash = SortHash();\n}\n\nvoid CServerBrowser::RemoveRequest(CServerEntry *pEntry)\n{\n\tif(pEntry->m_pPrevReq || pEntry->m_pNextReq || m_pFirstReqServer == pEntry)\n\t{\n\t\tif(pEntry->m_pPrevReq)\n\t\t\tpEntry->m_pPrevReq->m_pNextReq = pEntry->m_pNextReq;\n\t\telse\n\t\t\tm_pFirstReqServer = pEntry->m_pNextReq;\n\n\t\tif(pEntry->m_pNextReq)\n\t\t\tpEntry->m_pNextReq->m_pPrevReq = pEntry->m_pPrevReq;\n\t\telse\n\t\t\tm_pLastReqServer = pEntry->m_pPrevReq;\n\n\t\tpEntry->m_pPrevReq = 0;\n\t\tpEntry->m_pNextReq = 0;\n\t\tm_NumRequests--;\n\t}\n}\n\ninline int AddrHash(const NETADDR *pAddr)\n{\n\tif(pAddr->type==NETTYPE_IPV4)\n\t\treturn (pAddr->ip[0]+pAddr->ip[1]+pAddr->ip[2]+pAddr->ip[3])&0xFF;\n\telse\n\t\treturn (pAddr->ip[0]+pAddr->ip[1]+pAddr->ip[2]+pAddr->ip[3]+pAddr->ip[4]+pAddr->ip[5]+pAddr->ip[6]+pAddr->ip[7]+\n\t\t\tpAddr->ip[8]+pAddr->ip[9]+pAddr->ip[10]+pAddr->ip[11]+pAddr->ip[12]+pAddr->ip[13]+pAddr->ip[14]+pAddr->ip[15])&0xFF;\n}\n\nCServerBrowser::CServerEntry *CServerBrowser::Find(const NETADDR &Addr)\n{\n\tCServerEntry *pEntry = m_aServerlistIp[AddrHash(&Addr)];\n\n\tfor(; pEntry; pEntry = pEntry->m_pNextIp)\n\t{\n\t\tif(net_addr_comp(&pEntry->m_Addr, &Addr) == 0)\n\t\t\treturn pEntry;\n\t}\n\treturn (CServerEntry*)0;\n}\n\nvoid CServerBrowser::QueueRequest(CServerEntry *pEntry)\n{\n\t// add it to the list of servers that we should request info from\n\tpEntry->m_pPrevReq = m_pLastReqServer;\n\tif(m_pLastReqServer)\n\t\tm_pLastReqServer->m_pNextReq = pEntry;\n\telse\n\t\tm_pFirstReqServer = pEntry;\n\tm_pLastReqServer = pEntry;\n\n\tm_NumRequests++;\n}\n\nvoid CServerBrowser::SetInfo(CServerEntry *pEntry, const CServerInfo &Info)\n{\n\tint Fav = pEntry->m_Info.m_Favorite;\n\tpEntry->m_Info = Info;\n\tpEntry->m_Info.m_Flags &= FLAG_PASSWORD;\n\tif(str_comp(pEntry->m_Info.m_aGameType, \"DM\") == 0 || str_comp(pEntry->m_Info.m_aGameType, \"TDM\") == 0 || str_comp(pEntry->m_Info.m_aGameType, \"CTF\") == 0 ||\n\t\tstr_comp(pEntry->m_Info.m_aGameType, \"SUR\") == 0 ||\tstr_comp(pEntry->m_Info.m_aGameType, \"LMS\") == 0)\n\t\tpEntry->m_Info.m_Flags |= FLAG_PURE;\n\tif(str_comp(pEntry->m_Info.m_aMap, \"dm1\") == 0 || str_comp(pEntry->m_Info.m_aMap, \"dm2\") == 0 || str_comp(pEntry->m_Info.m_aMap, \"dm6\") == 0 ||\n\t\tstr_comp(pEntry->m_Info.m_aMap, \"dm7\") == 0 || str_comp(pEntry->m_Info.m_aMap, \"dm8\") == 0 || str_comp(pEntry->m_Info.m_aMap, \"dm9\") == 0 ||\n\t\tstr_comp(pEntry->m_Info.m_aMap, \"ctf1\") == 0 || str_comp(pEntry->m_Info.m_aMap, \"ctf2\") == 0 || str_comp(pEntry->m_Info.m_aMap, \"ctf3\") == 0 ||\n\t\tstr_comp(pEntry->m_Info.m_aMap, \"ctf4\") == 0 || str_comp(pEntry->m_Info.m_aMap, \"ctf5\") == 0 || str_comp(pEntry->m_Info.m_aMap, \"ctf6\") == 0 ||\n\t\tstr_comp(pEntry->m_Info.m_aMap, \"ctf7\") == 0)\n\t\tpEntry->m_Info.m_Flags |= FLAG_PUREMAP;\n\tpEntry->m_Info.m_Favorite = Fav;\n\tpEntry->m_Info.m_NetAddr = pEntry->m_Addr;\n \n\tm_NumPlayers += pEntry->m_Info.m_NumPlayers;\n\n\tpEntry->m_GotInfo = 1;\n}\n\nCServerBrowser::CServerEntry *CServerBrowser::Add(const NETADDR &Addr)\n{\n\t// create new pEntry\n\tCServerEntry *pEntry = (CServerEntry *)m_ServerlistHeap.Allocate(sizeof(CServerEntry));\n\tmem_zero(pEntry, sizeof(CServerEntry));\n\n\t// set the info\n\tpEntry->m_Addr = Addr;\n\tpEntry->m_Info.m_NetAddr = Addr;\n\n\tpEntry->m_Info.m_Latency = 999;\n\tnet_addr_str(&Addr, pEntry->m_Info.m_aAddress, sizeof(pEntry->m_Info.m_aAddress), true);\n\tstr_copy(pEntry->m_Info.m_aName, pEntry->m_Info.m_aAddress, sizeof(pEntry->m_Info.m_aName));\n\tstr_copy(pEntry->m_Info.m_aHostname, pEntry->m_Info.m_aAddress, sizeof(pEntry->m_Info.m_aHostname));\n\n\t// check if it's a favorite\n\tfor(int i = 0; i < m_NumFavoriteServers; i++)\n\t{\n\t\tif(m_aFavoriteServers[i].m_State >= FAVSTATE_ADDR && net_addr_comp(&Addr, &m_aFavoriteServers[i].m_Addr) == 0)\n\t\t\tpEntry->m_Info.m_Favorite = 1;\n\t}\n\n\t// add to the hash list\n\tint Hash = AddrHash(&Addr);\n\tpEntry->m_pNextIp = m_aServerlistIp[Hash];\n\tm_aServerlistIp[Hash] = pEntry;\n\n\tif(m_NumServers == m_NumServerCapacity)\n\t{\n\t\tif(m_NumServerCapacity == 0)\n\t\t{\n\t\t\t// alloc start size\n\t\t\tm_NumServerCapacity = 1000;\n\t\t\tm_ppServerlist = (CServerEntry **)mem_alloc(m_NumServerCapacity*sizeof(CServerEntry*), 1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// increase size\n\t\t\tm_NumServerCapacity += 100;\n\t\t\tCServerEntry **ppNewlist = (CServerEntry **)mem_alloc(m_NumServerCapacity*sizeof(CServerEntry*), 1);\n\t\t\tmem_copy(ppNewlist, m_ppServerlist, m_NumServers*sizeof(CServerEntry*));\n\t\t\tmem_free(m_ppServerlist);\n\t\t\tm_ppServerlist = ppNewlist;\n\t\t}\n\t}\n\n\t// add to list\n\tm_ppServerlist[m_NumServers] = pEntry;\n\tpEntry->m_Info.m_ServerIndex = m_NumServers;\n\tm_NumServers++;\n\n\treturn pEntry;\n}\n\nvoid CServerBrowser::Set(const NETADDR &Addr, int Type, int Token, const CServerInfo *pInfo)\n{\n\tCServerEntry *pEntry = 0;\n\tif(Type == SET_MASTER_ADD)\n\t{\n\t\tif(m_ServerlistType != IServerBrowser::TYPE_INTERNET)\n\t\t\treturn;\n\n\t\tif(!Find(Addr))\n\t\t{\n\t\t\tpEntry = Add(Addr);\n\t\t\tQueueRequest(pEntry);\n\t\t}\n\t}\n\t/*else if(Type == SET_FAV_ADD)\n\t{\n\t\tif(m_ServerlistType != IServerBrowser::TYPE_FAVORITES)\n\t\t\treturn;\n\n\t\tif(!Find(Addr))\n\t\t{\n\t\t\tpEntry = Add(Addr);\n\t\t\tQueueRequest(pEntry);\n\t\t}\n\t}*/\n\telse if(Type == SET_TOKEN)\n\t{\n\t\tif(Token != m_CurrentToken)\n\t\t\treturn;\n\n\t\tpEntry = Find(Addr);\n\t\tif(!pEntry)\n\t\t\tpEntry = Add(Addr);\n\t\tif(pEntry)\n\t\t{\n\t\t\tSetInfo(pEntry, *pInfo);\n\t\t\tif(m_ServerlistType == IServerBrowser::TYPE_LAN)\n\t\t\t\tpEntry->m_Info.m_Latency = min(static_cast<int>((time_get()-m_BroadcastTime)*1000/time_freq()), 999);\n\t\t\telse\n\t\t\t\tpEntry->m_Info.m_Latency = min(static_cast<int>((time_get()-pEntry->m_RequestTime)*1000/time_freq()), 999);\n\t\t\tRemoveRequest(pEntry);\n\t\t}\n\t}\n\n\tfor(int i = 0; i < m_lFilters.size(); i++)\n\t\tm_lFilters[i].Sort();\n}\n\nvoid CServerBrowser::Refresh(int Type)\n{\n\t// clear out everything\n\tm_ServerlistHeap.Reset();\n\tm_NumServers = 0;\n\tm_NumPlayers = 0;\n\tfor(int i = 0; i < m_lFilters.size(); i++)\n\t{\n\t\tm_lFilters[i].m_NumSortedServers = 0;\n\t\tm_lFilters[i].m_NumPlayers = 0;\n\t}\n\tmem_zero(m_aServerlistIp, sizeof(m_aServerlistIp));\n\tm_pFirstReqServer = 0;\n\tm_pLastReqServer = 0;\n\tm_NumRequests = 0;\n\n\t// next token\n\tm_CurrentToken = (m_CurrentToken+1)&0xff;\n\n\t//\n\tm_ServerlistType = Type;\n\n\tif(Type == IServerBrowser::TYPE_LAN)\n\t{\n\t\tunsigned char Buffer[sizeof(SERVERBROWSE_GETINFO)+1];\n\t\tCNetChunk Packet;\n\t\tint i;\n\n\t\tmem_copy(Buffer, SERVERBROWSE_GETINFO, sizeof(SERVERBROWSE_GETINFO));\n\t\tBuffer[sizeof(SERVERBROWSE_GETINFO)] = m_CurrentToken;\n\n\t\t/* do the broadcast version */\n\t\tPacket.m_ClientID = -1;\n\t\tmem_zero(&Packet, sizeof(Packet));\n\t\tPacket.m_Address.type = m_pNetClient->NetType()|NETTYPE_LINK_BROADCAST;\n\t\tPacket.m_Flags = NETSENDFLAG_CONNLESS;\n\t\tPacket.m_DataSize = sizeof(Buffer);\n\t\tPacket.m_pData = Buffer;\n\t\tm_BroadcastTime = time_get();\n\n\t\tfor(i = 8303; i <= 8310; i++)\n\t\t{\n\t\t\tPacket.m_Address.port = i;\n\t\t\tm_pNetClient->Send(&Packet);\n\t\t}\n\n\t\tif(g_Config.m_Debug)\n\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"client_srvbrowse\", \"broadcasting for servers\");\n\t}\n\telse if(Type == IServerBrowser::TYPE_INTERNET)\n\t\tm_NeedRefresh = 1;\n\t/*else if(Type == IServerBrowser::TYPE_FAVORITES)\n\t{\n\t\tfor(int i = 0; i < m_NumFavoriteServers; i++)\n\t\t\tif(m_aFavoriteServers[i].m_State >= FAVSTATE_ADDR)\n\t\t\t\tSet(m_aFavoriteServers[i].m_Addr, SET_FAV_ADD, -1, 0);\n\t}*/\n}\n\nvoid CServerBrowser::RequestImpl(const NETADDR &Addr, CServerEntry *pEntry) const\n{\n\tunsigned char Buffer[sizeof(SERVERBROWSE_GETINFO)+1];\n\tCNetChunk Packet;\n\n\tif(g_Config.m_Debug)\n\t{\n\t\tchar aAddrStr[NETADDR_MAXSTRSIZE];\n\t\tnet_addr_str(&Addr, aAddrStr, sizeof(aAddrStr), true);\n\t\tchar aBuf[256];\n\t\tstr_format(aBuf, sizeof(aBuf),\"requesting server info from %s\", aAddrStr);\n\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"client_srvbrowse\", aBuf);\n\t}\n\n\tmem_copy(Buffer, SERVERBROWSE_GETINFO, sizeof(SERVERBROWSE_GETINFO));\n\tBuffer[sizeof(SERVERBROWSE_GETINFO)] = m_CurrentToken;\n\n\tPacket.m_ClientID = -1;\n\tPacket.m_Address = Addr;\n\tPacket.m_Flags = NETSENDFLAG_CONNLESS;\n\tPacket.m_DataSize = sizeof(Buffer);\n\tPacket.m_pData = Buffer;\n\n\tm_pNetClient->Send(&Packet);\n\n\tif(pEntry)\n\t\tpEntry->m_RequestTime = time_get();\n}\n\nvoid CServerBrowser::Request(const NETADDR &Addr) const\n{\n\tRequestImpl(Addr, 0);\n}\n\n\nvoid CServerBrowser::Update(bool ForceResort)\n{\n\tint64 Timeout = time_freq();\n\tint64 Now = time_get();\n\tint Count;\n\tCServerEntry *pEntry, *pNext;\n\n\t// do server list requests\n\tif(m_NeedRefresh && !m_pMasterServer->IsRefreshing())\n\t{\n\t\tNETADDR Addr;\n\t\tCNetChunk Packet;\n\t\tint i;\n\n\t\tm_NeedRefresh = 0;\n\n\t\tmem_zero(&Packet, sizeof(Packet));\n\t\tPacket.m_ClientID = -1;\n\t\tPacket.m_Flags = NETSENDFLAG_CONNLESS;\n\t\tPacket.m_DataSize = sizeof(SERVERBROWSE_GETLIST);\n\t\tPacket.m_pData = SERVERBROWSE_GETLIST;\n\n\t\tfor(i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++)\n\t\t{\n\t\t\tif(!m_pMasterServer->IsValid(i))\n\t\t\t\tcontinue;\n\n\t\t\tAddr = m_pMasterServer->GetAddr(i);\n\t\t\tPacket.m_Address = Addr;\n\t\t\tm_pNetClient->Send(&Packet);\n\t\t}\n\n\t\tif(g_Config.m_Debug)\n\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"client_srvbrowse\", \"requesting server list\");\n\t}\n\n\t// do timeouts\n\tpEntry = m_pFirstReqServer;\n\twhile(1)\n\t{\n\t\tif(!pEntry) // no more entries\n\t\t\tbreak;\n\n\t\tpNext = pEntry->m_pNextReq;\n\n\t\tif(pEntry->m_RequestTime && pEntry->m_RequestTime+Timeout < Now)\n\t\t{\n\t\t\t// timeout\n\t\t\tRemoveRequest(pEntry);\n\t\t}\n\n\t\tpEntry = pNext;\n\t}\n\n\t// do timeouts\n\tpEntry = m_pFirstReqServer;\n\tCount = 0;\n\twhile(1)\n\t{\n\t\tif(!pEntry) // no more entries\n\t\t\tbreak;\n\n\t\t// no more then 10 concurrent requests\n\t\tif(Count == g_Config.m_BrMaxRequests)\n\t\t\tbreak;\n\n\t\tif(pEntry->m_RequestTime == 0)\n\t\t\tRequestImpl(pEntry->m_Addr, pEntry);\n\n\t\tCount++;\n\t\tpEntry = pEntry->m_pNextReq;\n\t}\n\n\t// update favorites\n\tUpdateFavorites();\n\n\t// check if we need to resort\n\tfor(int i = 0; i < m_lFilters.size(); i++)\n\t{\n\t\tCServerFilter *pFilter = &m_lFilters[i];\n\t\tif(pFilter->m_SortHash != pFilter->SortHash() || ForceResort)\n\t\t\tpFilter->Sort();\n\t}\n}\n\n\nvoid CServerBrowser::UpdateFavorites()\n{\n\t// check if hostname lookup for favourites is done\n\tif(m_FavLookup.m_Active && m_FavLookup.m_HostLookup.m_Job.Status() == CJob::STATE_DONE)\n\t{\n\t\t// check if favourite has not been removed in the meanwhile\n\t\tif(m_FavLookup.m_FavoriteIndex != -1)\n\t\t{\n\t\t\tif(m_FavLookup.m_HostLookup.m_Job.Result() == 0)\n\t\t\t{\n\t\t\t\tCFavoriteServer *pEntry = FindFavoriteByAddr(m_FavLookup.m_HostLookup.m_Addr, 0);\n\t\t\t\tif(pEntry)\n\t\t\t\t{\n\t\t\t\t\t// address is already in the list -> acquire hostname if existing entry lacks it and drop multiple address entry\n\t\t\t\t\tif(pEntry->m_State != FAVSTATE_HOST)\n\t\t\t\t\t{\n\t\t\t\t\t\tstr_copy(pEntry->m_aHostname, m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_aHostname, sizeof(pEntry->m_aHostname));\n\t\t\t\t\t\tpEntry->m_State = FAVSTATE_HOST;\n\t\t\t\t\t\tdbg_msg(\"test\", \"fav aquired hostname, %s\", m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_aHostname);\n\t\t\t\t\t}\n\t\t\t\t\tRemoveFavoriteEntry(m_FavLookup.m_FavoriteIndex);\n\t\t\t\t\tdbg_msg(\"test\", \"fav removed multiple entry\");\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// address wasn't in the list yet -> add it (optional check if hostname matches given address -> drop entry on fail)\n\t\t\t\t\tif(m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_State == FAVSTATE_LOOKUP ||\n\t\t\t\t\t\tnet_addr_comp(&m_aFavoriteServers[m_NumFavoriteServers].m_Addr, &m_FavLookup.m_HostLookup.m_Addr) == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_Addr = m_FavLookup.m_HostLookup.m_Addr;\n\t\t\t\t\t\tm_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_State = FAVSTATE_HOST;\n\t\t\t\t\t\tCServerEntry *pEntry = Find(m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_Addr);\n\t\t\t\t\t\tif(pEntry)\n\t\t\t\t\t\t\tpEntry->m_Info.m_Favorite = 1;\n\t\t\t\t\t\tdbg_msg(\"test\", \"fav added, %s\", m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_aHostname);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tRemoveFavoriteEntry(m_FavLookup.m_FavoriteIndex);\n\t\t\t\t\t\tdbg_msg(\"test\", \"fav removed entry that failed hostname-address check\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// hostname lookup failed\n\t\t\t\tif(m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_State == FAVSTATE_LOOKUP)\n\t\t\t\t{\n\t\t\t\t\tm_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_State = FAVSTATE_INVALID;\n\t\t\t\t\tdbg_msg(\"test\", \"fav invalid, %s\", m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_aHostname);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tRemoveFavoriteEntry(m_FavLookup.m_FavoriteIndex);\n\t\t\t\t\tdbg_msg(\"test\", \"fav removed invalid check-based entry\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tm_FavLookup.m_Active = false;\n\t}\n\n\t// add hostname lookup for favourites\n\tif(m_FavLookup.m_LookupCount > 0 && !m_FavLookup.m_Active)\n\t{\n\t\tfor(int i = 0; i < m_NumFavoriteServers; i++)\n\t\t{\n\t\t\tif(m_aFavoriteServers[i].m_State <= FAVSTATE_LOOKUPCHECK)\n\t\t\t{\n\t\t\t\tm_pEngine->HostLookup(&m_FavLookup.m_HostLookup, m_aFavoriteServers[i].m_aHostname, m_pNetClient->NetType());\n\t\t\t\tm_FavLookup.m_FavoriteIndex = i;\n\t\t\t\t--m_FavLookup.m_LookupCount;\n\t\t\t\tm_FavLookup.m_Active = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nCServerBrowser::CFavoriteServer *CServerBrowser::FindFavoriteByAddr(const NETADDR &Addr, int *Index)\n{\n\tfor(int i = 0; i < m_NumFavoriteServers; i++)\n\t{\n\t\tif(net_addr_comp(&Addr, &m_aFavoriteServers[i].m_Addr) == 0)\n\t\t{\n\t\t\tif(Index)\n\t\t\t\t*Index = i;\n\t\t\treturn &m_aFavoriteServers[i];\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nCServerBrowser::CFavoriteServer *CServerBrowser::FindFavoriteByHostname(const char *pHostname, int *Index)\n{\n\tfor(int i = 0; i < m_NumFavoriteServers; i++)\n\t{\n\t\tif(str_comp(pHostname, m_aFavoriteServers[i].m_aHostname) == 0)\n\t\t{\n\t\t\tif(Index)\n\t\t\t\t*Index = i;\n\t\t\treturn &m_aFavoriteServers[i];\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n\nvoid CServerBrowser::RemoveFavoriteEntry(int Index)\n{\n\tmem_move(&m_aFavoriteServers[Index], &m_aFavoriteServers[Index+1], sizeof(CFavoriteServer)*(m_NumFavoriteServers-(Index+1)));\n\tm_NumFavoriteServers--;\n}\n\nvoid CServerBrowser::AddFavoriteEx(const char *pHostname, const NETADDR *pAddr, bool DoCheck)\n{\n\tif(m_NumFavoriteServers == MAX_FAVORITES || FindFavoriteByHostname(pHostname, 0))\n\t\treturn;\n\n\t// check if hostname is a net address string\n\tif(net_addr_from_str(&m_aFavoriteServers[m_NumFavoriteServers].m_Addr, pHostname) == 0)\n\t{\n\t\t// make sure that we don't already have the server in our list\n\t\tif(FindFavoriteByAddr(m_aFavoriteServers[m_NumFavoriteServers].m_Addr, 0) != 0)\n\t\t\treturn;\n\n\t\t// check if hostname does not match given address\n\t\tif(DoCheck && net_addr_comp(&m_aFavoriteServers[m_NumFavoriteServers].m_Addr, pAddr) != 0)\n\t\t\treturn;\n\n\t\t// add the server to the list\n\t\tm_aFavoriteServers[m_NumFavoriteServers].m_State = FAVSTATE_ADDR;\n\t\tCServerEntry *pEntry = Find(m_aFavoriteServers[m_NumFavoriteServers].m_Addr);\n\t\tif(pEntry)\n\t\t\tpEntry->m_Info.m_Favorite = 1;\n\t}\n\telse\n\t{\n\t\t// prepare for hostname lookup\n\t\tif(DoCheck)\n\t\t{\n\t\t\tm_aFavoriteServers[m_NumFavoriteServers].m_State = FAVSTATE_LOOKUPCHECK;\n\t\t\tm_aFavoriteServers[m_NumFavoriteServers].m_Addr = *pAddr;\n\t\t}\n\t\telse\n\t\t\tm_aFavoriteServers[m_NumFavoriteServers].m_State = FAVSTATE_LOOKUP;\n\t\t++m_FavLookup.m_LookupCount;\n\t}\n\n\tstr_copy(m_aFavoriteServers[m_NumFavoriteServers].m_aHostname, pHostname, sizeof(m_aFavoriteServers[m_NumFavoriteServers].m_aHostname));\n\t++m_NumFavoriteServers;\n\n\tif(g_Config.m_Debug)\n\t{\n\t\tchar aBuf[256];\n\t\tstr_format(aBuf, sizeof(aBuf), \"added fav '%s' (%s)\", pHostname);\n\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"client_srvbrowse\", aBuf);\n\t}\n\n\t// refresh servers in all filters where favorites are filtered\n\tfor(int i = 0; i < m_lFilters.size(); i++)\n\t{\n\t\tCServerFilter *pFilter = &m_lFilters[i];\n\t\tif(pFilter->m_SortHash&FILTER_FAVORITE)\n\t\t\tpFilter->Sort();\n\t}\n}\n\nvoid CServerBrowser::RemoveFavoriteEx(const char *pHostname, const NETADDR *pAddr)\n{\n\t// find favorite entry\n\tint Index = 0;\n\tCFavoriteServer *pFavEntry = FindFavoriteByHostname(pHostname, &Index);\n\tif(pFavEntry == 0 && pAddr)\n\t\tpFavEntry = FindFavoriteByAddr(*pAddr, &Index);\n\tif(pFavEntry)\n\t{\n\t\tif(pFavEntry->m_State >= FAVSTATE_ADDR)\n\t\t{\n\t\t\t// invalidate favorite state for server entry\n\t\t\tCServerEntry *pEntry = Find(pFavEntry->m_Addr);\n\t\t\tif(pEntry)\n \t\t\t\tpEntry->m_Info.m_Favorite = 0;\n\t\t}\n\t\telse if(pFavEntry->m_State <= FAVSTATE_LOOKUPCHECK && m_FavLookup.m_FavoriteIndex == Index)\n\t\t{\n\t\t\t// skip result on favorite hostname lookup \n\t\t\tm_FavLookup.m_FavoriteIndex = -1;\n\t\t}\n\t\t\n\t\t// remove favorite\n\t\tRemoveFavoriteEntry(Index);\n\t\tif(m_FavLookup.m_FavoriteIndex > Index)\n\t\t\t--m_FavLookup.m_FavoriteIndex;\n\t}\n\n\t// refresh servers in all filters where favorites are filtered\n\tfor(int i = 0; i < m_lFilters.size(); i++)\n\t{\n\t\tCServerFilter *pFilter = &m_lFilters[i];\n\t\tif(pFilter->m_SortHash&FILTER_FAVORITE)\n\t\t\tpFilter->Sort();\n\t}\n}\n\n\nint CServerBrowser::LoadingProgression() const\n{\n\tif(m_NumServers == 0)\n\t\treturn 0;\n\n\tint Servers = m_NumServers;\n\tint Loaded = m_NumServers-m_NumRequests;\n\treturn 100.0f * Loaded/Servers;\n}\n\n\nvoid CServerBrowser::ConAddFavorite(IConsole::IResult *pResult, void *pUserData)\n{\n\tCServerBrowser *pSelf = static_cast<CServerBrowser *>(pUserData);\n\tpSelf->AddFavoriteEx(pResult->GetString(0), 0, false);\n}\n\nvoid CServerBrowser::ConRemoveFavorite(IConsole::IResult *pResult, void *pUserData)\n{\n\tCServerBrowser *pSelf = static_cast<CServerBrowser *>(pUserData);\n\tpSelf->RemoveFavoriteEx(pResult->GetString(0), 0);\n}\n\nvoid CServerBrowser::ConfigSaveCallback(IConfig *pConfig, void *pUserData)\n{\n\tCServerBrowser *pSelf = (CServerBrowser *)pUserData;\n\n\tchar aBuffer[256];\n\tfor(int i = 0; i < pSelf->m_NumFavoriteServers; i++)\n\t{\n\t\tstr_format(aBuffer, sizeof(aBuffer), \"add_favorite %s\", pSelf->m_aFavoriteServers[i].m_aHostname);\n\t\tpConfig->WriteLine(aBuffer);\n\t}\n}\n"
  },
  {
    "path": "src/engine/client/serverbrowser.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_CLIENT_SERVERBROWSER_H\n#define ENGINE_CLIENT_SERVERBROWSER_H\n\n#include <base/tl/array.h>\n#include <engine/serverbrowser.h>\n\nclass CServerBrowser : public IServerBrowser\n{\npublic:\n\tenum\n\t{\n\t\tSET_MASTER_ADD=1,\n\t\tSET_FAV_ADD,\n\t\tSET_TOKEN,\n\t};\n\n\tclass CServerEntry\n\t{\n\tpublic:\n\t\tNETADDR m_Addr;\n\t\tint64 m_RequestTime;\n\t\tint m_GotInfo;\n\t\tCServerInfo m_Info;\n\n\t\tCServerEntry *m_pNextIp; // ip hashed list\n\n\t\tCServerEntry *m_pPrevReq; // request list\n\t\tCServerEntry *m_pNextReq;\n\t};\n\n\tclass CServerFilter\n\t{\n\tpublic:\n\t\tCServerBrowser *m_pServerBrowser;\n\n\t\tint m_SortHash;\n\t\tchar m_aGametype[32];\n\t\tchar m_aServerAddress[16];\n\t\tint m_Ping;\n\t\tint m_Country;\n\n\t\tint m_NumSortedServers;\n\t\tint m_NumSortedServersCapacity;\n\n\t\tint m_NumPlayers;\n\n\t\tint *m_pSortedServerlist;\n\n\t\t~CServerFilter();\n\n\t\t// sorting criterions\n\t\tbool SortCompareName(int Index1, int Index2) const;\n\t\tbool SortCompareMap(int Index1, int Index2) const;\n\t\tbool SortComparePing(int Index1, int Index2) const;\n\t\tbool SortCompareGametype(int Index1, int Index2) const;\n\t\tbool SortCompareNumPlayers(int Index1, int Index2) const;\n\t\tbool SortCompareNumClients(int Index1, int Index2) const;\n\n\t\tvoid Filter();\n\t\tvoid Sort();\n\t\tint SortHash() const;\n\t};\n\n\tarray<CServerFilter> m_lFilters;\n\n\tint AddFilter(int SortHash, int Ping, int Country, const char* pGametype, const char* pServerAddress);\n\tvoid SetFilter(int Index, int SortHash, int Ping, int Country, const char* pGametype, const char* pServerAddress);\n\tvoid GetFilter(int Index, int *pSortHash, int *pPing, int *pCountry, char* pGametype, char* pServerAddress);\n\tvoid RemoveFilter(int Index);\n\t\t\n\tCServerBrowser();\n\n\t// interface functions\n\tvoid Refresh(int Type);\n\tbool IsRefreshing() const { return m_pFirstReqServer != 0; }\n\tbool IsRefreshingMasters() const { return m_pMasterServer->IsRefreshing(); }\n\tint LoadingProgression() const;\n\n\tint NumServers() const { return m_NumServers; }\n\tint NumPlayers() const { return m_NumPlayers; }\n\n\tint NumSortedServers(int Index) const { return m_lFilters[Index].m_NumSortedServers; }\n\tint NumSortedPlayers(int Index) const { return m_lFilters[Index].m_NumPlayers; }\n\tconst CServerInfo *SortedGet(int FilterIndex, int Index) const;\n\tconst void *GetID(int FilterIndex, int Index) const;\n\n\tbool IsFavorite(const NETADDR &Addr) { return FindFavoriteByAddr(Addr, 0) != 0; }\n\tvoid AddFavorite(const CServerInfo *pEntry) { AddFavoriteEx(pEntry->m_aHostname, &pEntry->m_NetAddr, true); }\n\tvoid RemoveFavorite(const CServerInfo *pEntry) { RemoveFavoriteEx(pEntry->m_aHostname, &pEntry->m_NetAddr); }\n\n\t//\n\tvoid Update(bool ForceResort);\n\tvoid Set(const NETADDR &Addr, int Type, int Token, const CServerInfo *pInfo);\n\tvoid Request(const NETADDR &Addr) const;\n\n\tvoid SetBaseInfo(class CNetClient *pClient, const char *pNetVersion);\n\nprivate:\n\tCNetClient *m_pNetClient;\n\tIMasterServer *m_pMasterServer;\n\tclass IConsole *m_pConsole;\n\tclass IEngine *m_pEngine;\n\tclass IFriends *m_pFriends;\n\tchar m_aNetVersion[128];\n\n\tCHeap m_ServerlistHeap;\n\n\t// favourite\n\tenum\n\t{\n\t\tFAVSTATE_LOOKUP=0,\n\t\tFAVSTATE_LOOKUPCHECK,\n\t\tFAVSTATE_INVALID,\n\t\tFAVSTATE_ADDR,\n\t\tFAVSTATE_HOST,\n\n\t\tMAX_FAVORITES=256,\n\t};\n\n\tstruct CFavoriteServer\n\t{\n\t\tchar m_aHostname[128];\n\t\tNETADDR m_Addr;\n\t\tint m_State;\n\t} m_aFavoriteServers[MAX_FAVORITES];\n\n\tint m_NumFavoriteServers;\n\n\tstruct CFavoriteLookup\n\t{\n\t\tclass CHostLookup m_HostLookup;\n\t\tint m_FavoriteIndex;\n\t\tint m_LookupCount;\n\t\tbool m_Active;\n\t} m_FavLookup;\n\n\tvoid UpdateFavorites();\n\tCFavoriteServer *FindFavoriteByAddr(const NETADDR &Addr, int *Index);\n\tCFavoriteServer *FindFavoriteByHostname(const char *pHostname, int *Index);\n\tvoid RemoveFavoriteEntry(int Index);\n\tvoid AddFavoriteEx(const char *pHostname, const NETADDR *pAddr, bool DoCheck);\n\tvoid RemoveFavoriteEx(const char *pHostname, const NETADDR *Addr);\n\n\t//\n\tCServerEntry *m_aServerlistIp[256]; // ip hash list\n\n\tCServerEntry **m_ppServerlist;\n\n\tCServerEntry *m_pFirstReqServer; // request list\n\tCServerEntry *m_pLastReqServer;\n\tint m_NumRequests;\n\n\tint m_NeedRefresh;\n\n\tint m_NumServers;\n\tint m_NumServerCapacity;\n\n\tint m_NumPlayers;\n\n\t// the token is to keep server refresh separated from each other\n\tint m_CurrentToken;\n\n\tint m_ServerlistType;\n\tint64 m_BroadcastTime;\n\n\tCServerEntry *Find(const NETADDR &Addr);\n\tCServerEntry *Add(const NETADDR &Addr);\n\n\tvoid RemoveRequest(CServerEntry *pEntry);\n\tvoid QueueRequest(CServerEntry *pEntry);\n\n\tvoid RequestImpl(const NETADDR &Addr, CServerEntry *pEntry) const;\n\n\tvoid SetInfo(CServerEntry *pEntry, const CServerInfo &Info);\n\n\tstatic void ConAddFavorite(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConRemoveFavorite(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConfigSaveCallback(IConfig *pConfig, void *pUserData);\n};\n\n#endif\n"
  },
  {
    "path": "src/engine/client/sound.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/math.h>\n#include <base/system.h>\n\n#include <engine/graphics.h>\n#include <engine/storage.h>\n\n#include <engine/shared/config.h>\n\n#include \"SDL.h\"\n\n#include \"sound.h\"\n\nextern \"C\" { // wavpack\n\t#include <engine/external/wavpack/wavpack.h>\n}\n#include <math.h>\n\nenum\n{\n\tNUM_SAMPLES = 512,\n\tNUM_VOICES = 64,\n\tNUM_CHANNELS = 16,\n};\n\nstruct CSample\n{\n\tshort *m_pData;\n\tint m_NumFrames;\n\tint m_Rate;\n\tint m_Channels;\n\tint m_LoopStart;\n\tint m_LoopEnd;\n\tint m_PausedAt;\n};\n\nstruct CChannel\n{\n\tint m_Vol;\n\tint m_Pan;\n} ;\n\nstruct CVoice\n{\n\tCSample *m_pSample;\n\tCChannel *m_pChannel;\n\tint m_Tick;\n\tint m_Vol; // 0 - 255\n\tint m_Flags;\n\tint m_X, m_Y;\n} ;\n\nstatic CSample m_aSamples[NUM_SAMPLES] = { {0} };\nstatic CVoice m_aVoices[NUM_VOICES] = { {0} };\nstatic CChannel m_aChannels[NUM_CHANNELS] = { {255, 0} };\n\nstatic LOCK m_SoundLock = 0;\n\nstatic int m_CenterX = 0;\nstatic int m_CenterY = 0;\n\nstatic int m_MixingRate = 48000;\nstatic volatile int m_SoundVolume = 100;\n\nstatic int m_NextVoice = 0;\nstatic int *m_pMixBuffer = 0;\t// buffer only used by the thread callback function\nstatic unsigned m_MaxFrames = 0;\n\n// TODO: there should be a faster way todo this\nstatic short Int2Short(int i)\n{\n\tif(i > 0x7fff)\n\t\treturn 0x7fff;\n\telse if(i < -0x7fff)\n\t\treturn -0x7fff;\n\treturn i;\n}\n\nstatic int IntAbs(int i)\n{\n\tif(i<0)\n\t\treturn -i;\n\treturn i;\n}\n\nstatic void Mix(short *pFinalOut, unsigned Frames)\n{\n\tint MasterVol;\n\tmem_zero(m_pMixBuffer, m_MaxFrames*2*sizeof(int));\n\tFrames = min(Frames, m_MaxFrames);\n\n\t// aquire lock while we are mixing\n\tlock_wait(m_SoundLock);\n\n\tMasterVol = m_SoundVolume;\n\n\tfor(unsigned i = 0; i < NUM_VOICES; i++)\n\t{\n\t\tif(m_aVoices[i].m_pSample)\n\t\t{\n\t\t\t// mix voice\n\t\t\tCVoice *v = &m_aVoices[i];\n\t\t\tint *pOut = m_pMixBuffer;\n\n\t\t\tint Step = v->m_pSample->m_Channels; // setup input sources\n\t\t\tshort *pInL = &v->m_pSample->m_pData[v->m_Tick*Step];\n\t\t\tshort *pInR = &v->m_pSample->m_pData[v->m_Tick*Step+1];\n\n\t\t\tunsigned End = v->m_pSample->m_NumFrames-v->m_Tick;\n\n\t\t\tint Rvol = v->m_pChannel->m_Vol;\n\t\t\tint Lvol = v->m_pChannel->m_Vol;\n\n\t\t\t// make sure that we don't go outside the sound data\n\t\t\tif(Frames < End)\n\t\t\t\tEnd = Frames;\n\n\t\t\t// check if we have a mono sound\n\t\t\tif(v->m_pSample->m_Channels == 1)\n\t\t\t\tpInR = pInL;\n\n\t\t\t// volume calculation\n\t\t\tif(v->m_Flags&ISound::FLAG_POS && v->m_pChannel->m_Pan)\n\t\t\t{\n\t\t\t\t// TODO: we should respect the channel panning value\n\t\t\t\tconst int Range = 1500; // magic value, remove\n\t\t\t\tint dx = v->m_X - m_CenterX;\n\t\t\t\tint dy = v->m_Y - m_CenterY;\n\t\t\t\tint Dist = (int)sqrtf((float)dx*dx+dy*dy); // float here. nasty\n\t\t\t\tint p = IntAbs(dx);\n\t\t\t\tif(Dist >= 0 && Dist < Range)\n\t\t\t\t{\n\t\t\t\t\t// panning\n\t\t\t\t\tif(dx > 0)\n\t\t\t\t\t\tLvol = ((Range-p)*Lvol)/Range;\n\t\t\t\t\telse\n\t\t\t\t\t\tRvol = ((Range-p)*Rvol)/Range;\n\n\t\t\t\t\t// falloff\n\t\t\t\t\tLvol = (Lvol*(Range-Dist))/Range;\n\t\t\t\t\tRvol = (Rvol*(Range-Dist))/Range;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tLvol = 0;\n\t\t\t\t\tRvol = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// process all frames\n\t\t\tfor(unsigned s = 0; s < End; s++)\n\t\t\t{\n\t\t\t\t*pOut++ += (*pInL)*Lvol;\n\t\t\t\t*pOut++ += (*pInR)*Rvol;\n\t\t\t\tpInL += Step;\n\t\t\t\tpInR += Step;\n\t\t\t\tv->m_Tick++;\n\t\t\t}\n\n\t\t\t// free voice if not used any more\n\t\t\tif(v->m_Tick == v->m_pSample->m_NumFrames)\n\t\t\t{\n\t\t\t\tif(v->m_Flags&ISound::FLAG_LOOP)\n\t\t\t\t\tv->m_Tick = 0;\n\t\t\t\telse\n\t\t\t\t\tv->m_pSample = 0;\n\t\t\t}\n\t\t}\n\t}\n\n\n\t// release the lock\n\tlock_release(m_SoundLock);\n\n\t{\n\t\t// clamp accumulated values\n\t\t// TODO: this seams slow\n\t\tfor(unsigned i = 0; i < Frames; i++)\n\t\t{\n\t\t\tint j = i<<1;\n\t\t\tint vl = ((m_pMixBuffer[j]*MasterVol)/101)>>8;\n\t\t\tint vr = ((m_pMixBuffer[j+1]*MasterVol)/101)>>8;\n\n\t\t\tpFinalOut[j] = Int2Short(vl);\n\t\t\tpFinalOut[j+1] = Int2Short(vr);\n\t\t}\n\t}\n\n#if defined(CONF_ARCH_ENDIAN_BIG)\n\tswap_endian(pFinalOut, sizeof(short), Frames * 2);\n#endif\n}\n\nstatic void SdlCallback(void *pUnused, Uint8 *pStream, int Len)\n{\n\t(void)pUnused;\n\tMix((short *)pStream, Len/2/2);\n}\n\n\nint CSound::Init()\n{\n\tm_SoundEnabled = 0;\n\tm_pGraphics = Kernel()->RequestInterface<IEngineGraphics>();\n\tm_pStorage = Kernel()->RequestInterface<IStorage>();\n\n\tSDL_AudioSpec Format;\n\n\tm_SoundLock = lock_create();\n\n\tif(!g_Config.m_SndEnable)\n\t\treturn 0;\n\n\tif(SDL_InitSubSystem(SDL_INIT_AUDIO) < 0)\n\t{\n\t\tdbg_msg(\"gfx\", \"unable to init SDL audio: %s\", SDL_GetError());\n\t\treturn -1;\n\t}\n\n\tm_MixingRate = g_Config.m_SndRate;\n\n\t// Set 16-bit stereo audio at 22Khz\n\tFormat.freq = g_Config.m_SndRate; // ignore_convention\n\tFormat.format = AUDIO_S16; // ignore_convention\n\tFormat.channels = 2; // ignore_convention\n\tFormat.samples = g_Config.m_SndBufferSize; // ignore_convention\n\tFormat.callback = SdlCallback; // ignore_convention\n\tFormat.userdata = NULL; // ignore_convention\n\n\t// Open the audio device and start playing sound!\n\tif(SDL_OpenAudio(&Format, NULL) < 0)\n\t{\n\t\tdbg_msg(\"client/sound\", \"unable to open audio: %s\", SDL_GetError());\n\t\treturn -1;\n\t}\n\telse\n\t\tdbg_msg(\"client/sound\", \"sound init successful\");\n\n\tm_MaxFrames = g_Config.m_SndBufferSize*2;\n\tm_pMixBuffer = (int *)mem_alloc(m_MaxFrames*2*sizeof(int), 1);\n\n\tSDL_PauseAudio(0);\n\n\tm_SoundEnabled = 1;\n\tUpdate(); // update the volume\n\treturn 0;\n}\n\nint CSound::Update()\n{\n\t// update volume\n\tint WantedVolume = g_Config.m_SndVolume;\n\n\tif(!m_pGraphics->WindowActive() && g_Config.m_SndNonactiveMute)\n\t\tWantedVolume = 0;\n\n\tif(WantedVolume != m_SoundVolume)\n\t{\n\t\tlock_wait(m_SoundLock);\n\t\tm_SoundVolume = WantedVolume;\n\t\tlock_release(m_SoundLock);\n\t}\n\n\treturn 0;\n}\n\nint CSound::Shutdown()\n{\n\tSDL_CloseAudio();\n\tSDL_QuitSubSystem(SDL_INIT_AUDIO);\n\tlock_destroy(m_SoundLock);\n\tif(m_pMixBuffer)\n\t{\n\t\tmem_free(m_pMixBuffer);\n\t\tm_pMixBuffer = 0;\n\t}\n\treturn 0;\n}\n\nint CSound::AllocID()\n{\n\t// TODO: linear search, get rid of it\n\tfor(unsigned SampleID = 0; SampleID < NUM_SAMPLES; SampleID++)\n\t{\n\t\tif(m_aSamples[SampleID].m_pData == 0x0)\n\t\t\treturn SampleID;\n\t}\n\n\treturn -1;\n}\n\nvoid CSound::RateConvert(int SampleID)\n{\n\tCSample *pSample = &m_aSamples[SampleID];\n\tint NumFrames = 0;\n\tshort *pNewData = 0;\n\n\t// make sure that we need to convert this sound\n\tif(!pSample->m_pData || pSample->m_Rate == m_MixingRate)\n\t\treturn;\n\n\t// allocate new data\n\tNumFrames = (int)((pSample->m_NumFrames/(float)pSample->m_Rate)*m_MixingRate);\n\tpNewData = (short *)mem_alloc(NumFrames*pSample->m_Channels*sizeof(short), 1);\n\n\tfor(int i = 0; i < NumFrames; i++)\n\t{\n\t\t// resample TODO: this should be done better, like linear atleast\n\t\tfloat a = i/(float)NumFrames;\n\t\tint f = (int)(a*pSample->m_NumFrames);\n\t\tif(f >= pSample->m_NumFrames)\n\t\t\tf = pSample->m_NumFrames-1;\n\n\t\t// set new data\n\t\tif(pSample->m_Channels == 1)\n\t\t\tpNewData[i] = pSample->m_pData[f];\n\t\telse if(pSample->m_Channels == 2)\n\t\t{\n\t\t\tpNewData[i*2] = pSample->m_pData[f*2];\n\t\t\tpNewData[i*2+1] = pSample->m_pData[f*2+1];\n\t\t}\n\t}\n\n\t// free old data and apply new\n\tmem_free(pSample->m_pData);\n\tpSample->m_pData = pNewData;\n\tpSample->m_NumFrames = NumFrames;\n}\n\nint CSound::ReadData(void *pBuffer, int Size)\n{\n\treturn io_read(ms_File, pBuffer, Size);\n}\n\nISound::CSampleHandle CSound::LoadWV(const char *pFilename)\n{\n\tCSample *pSample;\n\tint SampleID = -1;\n\tchar aError[100];\n\tWavpackContext *pContext;\n\n\t// don't waste memory on sound when we are stress testing\n\tif(g_Config.m_DbgStress)\n\t\treturn CSampleHandle();\n\n\t// no need to load sound when we are running with no sound\n\tif(!m_SoundEnabled)\n\t\treturn CSampleHandle();\n\n\tif(!m_pStorage)\n\t\treturn CSampleHandle();\n\n\tms_File = m_pStorage->OpenFile(pFilename, IOFLAG_READ, IStorage::TYPE_ALL);\n\tif(!ms_File)\n\t{\n\t\tdbg_msg(\"sound/wv\", \"failed to open file. filename='%s'\", pFilename);\n\t\treturn CSampleHandle();\n\t}\n\n\tSampleID = AllocID();\n\tif(SampleID < 0)\n\t{\n\t\tio_close(ms_File);\n\t\tms_File = 0;\n\t\treturn CSampleHandle();\n\t}\n\tpSample = &m_aSamples[SampleID];\n\n\tpContext = WavpackOpenFileInput(ReadData, aError);\n\tif (pContext)\n\t{\n\t\tint m_aSamples = WavpackGetNumSamples(pContext);\n\t\tint BitsPerSample = WavpackGetBitsPerSample(pContext);\n\t\tunsigned int SampleRate = WavpackGetSampleRate(pContext);\n\t\tint m_aChannels = WavpackGetNumChannels(pContext);\n\t\tint *pData;\n\t\tint *pSrc;\n\t\tshort *pDst;\n\t\tint i;\n\n\t\tpSample->m_Channels = m_aChannels;\n\t\tpSample->m_Rate = SampleRate;\n\n\t\tif(pSample->m_Channels > 2)\n\t\t{\n\t\t\tdbg_msg(\"sound/wv\", \"file is not mono or stereo. filename='%s'\", pFilename);\n\t\t\tio_close(ms_File);\n\t\t\tms_File = 0;\n\t\t\treturn CSampleHandle();\n\t\t}\n\n\t\t/*\n\t\tif(snd->rate != 44100)\n\t\t{\n\t\t\tdbg_msg(\"sound/wv\", \"file is %d Hz, not 44100 Hz. filename='%s'\", snd->rate, filename);\n\t\t\treturn -1;\n\t\t}*/\n\n\t\tif(BitsPerSample != 16)\n\t\t{\n\t\t\tdbg_msg(\"sound/wv\", \"bps is %d, not 16, filname='%s'\", BitsPerSample, pFilename);\n\t\t\tio_close(ms_File);\n\t\t\tms_File = 0;\n\t\t\treturn CSampleHandle();\n\t\t}\n\n\t\tpData = (int *)mem_alloc(4*m_aSamples*m_aChannels, 1);\n\t\tWavpackUnpackSamples(pContext, pData, m_aSamples); // TODO: check return value\n\t\tpSrc = pData;\n\n\t\tpSample->m_pData = (short *)mem_alloc(2*m_aSamples*m_aChannels, 1);\n\t\tpDst = pSample->m_pData;\n\n\t\tfor (i = 0; i < m_aSamples*m_aChannels; i++)\n\t\t\t*pDst++ = (short)*pSrc++;\n\n\t\tmem_free(pData);\n\n\t\tpSample->m_NumFrames = m_aSamples;\n\t\tpSample->m_LoopStart = -1;\n\t\tpSample->m_LoopEnd = -1;\n\t\tpSample->m_PausedAt = 0;\n\t}\n\telse\n\t{\n\t\tdbg_msg(\"sound/wv\", \"failed to open %s: %s\", pFilename, aError);\n\t}\n\n\tio_close(ms_File);\n\tms_File = NULL;\n\n\tif(g_Config.m_Debug)\n\t\tdbg_msg(\"sound/wv\", \"loaded %s\", pFilename);\n\n\tRateConvert(SampleID);\n\treturn CreateSampleHandle(SampleID);\n}\n\nvoid CSound::SetListenerPos(float x, float y)\n{\n\tm_CenterX = (int)x;\n\tm_CenterY = (int)y;\n}\n\n\nvoid CSound::SetChannel(int ChannelID, float Vol, float Pan)\n{\n\tm_aChannels[ChannelID].m_Vol = (int)(Vol*255.0f);\n\tm_aChannels[ChannelID].m_Pan = (int)(Pan*255.0f); // TODO: this is only on and off right now\n}\n\nint CSound::Play(int ChannelID, CSampleHandle SampleID, int Flags, float x, float y)\n{\n\tif(!SampleID.IsValid())\n\t\treturn -1;\n\n\tint VoiceID = -1;\n\tint i;\n\n\tlock_wait(m_SoundLock);\n\n\t// search for voice\n\tfor(i = 0; i < NUM_VOICES; i++)\n\t{\n\t\tint id = (m_NextVoice + i) % NUM_VOICES;\n\t\tif(!m_aVoices[id].m_pSample)\n\t\t{\n\t\t\tVoiceID = id;\n\t\t\tm_NextVoice = id+1;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// voice found, use it\n\tif(VoiceID != -1)\n\t{\n\t\tm_aVoices[VoiceID].m_pSample = &m_aSamples[SampleID.Id()];\n\t\tm_aVoices[VoiceID].m_pChannel = &m_aChannels[ChannelID];\n\t\tif(Flags & FLAG_LOOP)\n\t\t\tm_aVoices[VoiceID].m_Tick = m_aSamples[SampleID.Id()].m_PausedAt;\n\t\telse\n\t\t\tm_aVoices[VoiceID].m_Tick = 0;\n\t\tm_aVoices[VoiceID].m_Vol = 255;\n\t\tm_aVoices[VoiceID].m_Flags = Flags;\n\t\tm_aVoices[VoiceID].m_X = (int)x;\n\t\tm_aVoices[VoiceID].m_Y = (int)y;\n\t}\n\n\tlock_release(m_SoundLock);\n\treturn VoiceID;\n}\n\nint CSound::PlayAt(int ChannelID, CSampleHandle SampleID, int Flags, float x, float y)\n{\n\treturn Play(ChannelID, SampleID, Flags|ISound::FLAG_POS, x, y);\n}\n\nint CSound::Play(int ChannelID, CSampleHandle SampleID, int Flags)\n{\n\treturn Play(ChannelID, SampleID, Flags, 0, 0);\n}\n\nvoid CSound::Stop(CSampleHandle SampleID)\n{\n\t// TODO: a nice fade out\n\tlock_wait(m_SoundLock);\n\tCSample *pSample = &m_aSamples[SampleID.Id()];\n\tfor(int i = 0; i < NUM_VOICES; i++)\n\t{\n\t\tif(m_aVoices[i].m_pSample == pSample)\n\t\t{\n\t\t\tif(m_aVoices[i].m_Flags & FLAG_LOOP)\n\t\t\t\tm_aVoices[i].m_pSample->m_PausedAt = m_aVoices[i].m_Tick;\n\t\t\telse\n\t\t\t\tm_aVoices[i].m_pSample->m_PausedAt = 0;\n\t\t\tm_aVoices[i].m_pSample = 0;\n\t\t}\n\t}\n\tlock_release(m_SoundLock);\n}\n\nvoid CSound::StopAll()\n{\n\t// TODO: a nice fade out\n\tlock_wait(m_SoundLock);\n\tfor(int i = 0; i < NUM_VOICES; i++)\n\t{\n\t\tif(m_aVoices[i].m_pSample)\n\t\t{\n\t\t\tif(m_aVoices[i].m_Flags & FLAG_LOOP)\n\t\t\t\tm_aVoices[i].m_pSample->m_PausedAt = m_aVoices[i].m_Tick;\n\t\t\telse\n\t\t\t\tm_aVoices[i].m_pSample->m_PausedAt = 0;\n\t\t}\n\t\tm_aVoices[i].m_pSample = 0;\n\t}\n\tlock_release(m_SoundLock);\n}\n\nIOHANDLE CSound::ms_File = 0;\n\nIEngineSound *CreateEngineSound() { return new CSound; }\n\n"
  },
  {
    "path": "src/engine/client/sound.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_CLIENT_SOUND_H\n#define ENGINE_CLIENT_SOUND_H\n\n#include <engine/sound.h>\n\nclass CSound : public IEngineSound\n{\n\tint m_SoundEnabled;\n\npublic:\n\tIEngineGraphics *m_pGraphics;\n\tIStorage *m_pStorage;\n\n\tvirtual int Init();\n\n\tint Update();\n\tint Shutdown();\n\tint AllocID();\n\n\tstatic void RateConvert(int SampleID);\n\n\t// TODO: Refactor: clean this mess up\n\tstatic IOHANDLE ms_File;\n\tstatic int ReadData(void *pBuffer, int Size);\n\n\tvirtual bool IsSoundEnabled() { return m_SoundEnabled != 0; }\n\n\tvirtual CSampleHandle LoadWV(const char *pFilename);\n\n\tvirtual void SetListenerPos(float x, float y);\n\tvirtual void SetChannel(int ChannelID, float Vol, float Pan);\n\n\tint Play(int ChannelID, CSampleHandle SampleID, int Flags, float x, float y);\n\tvirtual int PlayAt(int ChannelID, CSampleHandle SampleID, int Flags, float x, float y);\n\tvirtual int Play(int ChannelID, CSampleHandle SampleID, int Flags);\n\tvirtual void Stop(CSampleHandle SampleID);\n\tvirtual void StopAll();\n};\n\n#endif\n"
  },
  {
    "path": "src/engine/client/text.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n#include <base/math.h>\n#include <engine/graphics.h>\n#include <engine/textrender.h>\n\n#ifdef CONF_FAMILY_WINDOWS\n\t#include <windows.h>\n#endif\n\n// ft2 texture\n#include <ft2build.h>\n#include FT_FREETYPE_H\n\n// TODO: Refactor: clean this up\nenum\n{\n\tMAX_CHARACTERS = 64,\n};\n\n\nstatic int aFontSizes[] = {8,9,10,11,12,13,14,15,16,17,18,19,20,36,64};\n#define NUM_FONT_SIZES (sizeof(aFontSizes)/sizeof(int))\n\nstruct CFontChar\n{\n\tint m_ID;\n\n\t// these values are scaled to the pFont size\n\t// width * font_size == real_size\n\tfloat m_Width;\n\tfloat m_Height;\n\tfloat m_OffsetX;\n\tfloat m_OffsetY;\n\tfloat m_AdvanceX;\n\n\tfloat m_aUvs[4];\n\tint64 m_TouchTime;\n};\n\nstruct CFontSizeData\n{\n\tint m_FontSize;\n\tFT_Face *m_pFace;\n\n\tIGraphics::CTextureHandle m_aTextures[2];\n\tint m_TextureWidth;\n\tint m_TextureHeight;\n\n\tint m_NumXChars;\n\tint m_NumYChars;\n\n\tint m_CharMaxWidth;\n\tint m_CharMaxHeight;\n\n\tCFontChar m_aCharacters[MAX_CHARACTERS*MAX_CHARACTERS];\n\n\tint m_CurrentCharacter;\n};\n\nclass CFont\n{\npublic:\n\tchar m_aFilename[512];\n\tFT_Face m_FtFace;\n\tCFontSizeData m_aSizes[NUM_FONT_SIZES];\n};\n\n\nclass CTextRender : public IEngineTextRender\n{\n\tIGraphics *m_pGraphics;\n\tIGraphics *Graphics() { return m_pGraphics; }\n\n\tint WordLength(const char *pText)\n\t{\n\t\tint s = 1;\n\t\twhile(1)\n\t\t{\n\t\t\tif(*pText == 0)\n\t\t\t\treturn s-1;\n\t\t\tif(*pText == '\\n' || *pText == '\\t' || *pText == ' ')\n\t\t\t\treturn s;\n\t\t\tpText++;\n\t\t\ts++;\n\t\t}\n\t}\n\n\tfloat m_TextR;\n\tfloat m_TextG;\n\tfloat m_TextB;\n\tfloat m_TextA;\n\n\tfloat m_TextOutlineR;\n\tfloat m_TextOutlineG;\n\tfloat m_TextOutlineB;\n\tfloat m_TextOutlineA;\n\n\t//int m_FontTextureFormat;\n\n\tCFont *m_pDefaultFont;\n\n\tFT_Library m_FTLibrary;\n\n\tint GetFontSizeIndex(int Pixelsize)\n\t{\n\t\tfor(unsigned i = 0; i < NUM_FONT_SIZES; i++)\n\t\t{\n\t\t\tif(aFontSizes[i] >= Pixelsize)\n\t\t\t\treturn i;\n\t\t}\n\n\t\treturn NUM_FONT_SIZES-1;\n\t}\n\n\n\n\tvoid Grow(unsigned char *pIn, unsigned char *pOut, int w, int h)\n\t{\n\t\tfor(int y = 0; y < h; y++)\n\t\t\tfor(int x = 0; x < w; x++)\n\t\t\t{\n\t\t\t\tint c = pIn[y*w+x];\n\n\t\t\t\tfor(int sy = -1; sy <= 1; sy++)\n\t\t\t\t\tfor(int sx = -1; sx <= 1; sx++)\n\t\t\t\t\t{\n\t\t\t\t\t\tint GetX = x+sx;\n\t\t\t\t\t\tint GetY = y+sy;\n\t\t\t\t\t\tif (GetX >= 0 && GetY >= 0 && GetX < w && GetY < h)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint Index = GetY*w+GetX;\n\t\t\t\t\t\t\tif(pIn[Index] > c)\n\t\t\t\t\t\t\t\tc = pIn[Index];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\tpOut[y*w+x] = c;\n\t\t\t}\n\t}\n\n\tvoid InitTexture(CFontSizeData *pSizeData, int CharWidth, int CharHeight, int Xchars, int Ychars)\n\t{\n\t\tstatic int FontMemoryUsage = 0;\n\t\tint Width = CharWidth*Xchars;\n\t\tint Height = CharHeight*Ychars;\n\t\tvoid *pMem = mem_alloc(Width*Height, 1);\n\t\tmem_zero(pMem, Width*Height);\n\n\t\tfor(int i = 0; i < 2; i++)\n\t\t{\n\t\t\tif(pSizeData->m_aTextures[i].IsValid())\n\t\t\t{\n\t\t\t\tGraphics()->UnloadTexture(pSizeData->m_aTextures[i]);\n\t\t\t\tFontMemoryUsage -= pSizeData->m_TextureWidth*pSizeData->m_TextureHeight;\n\t\t\t\tpSizeData->m_aTextures[i] = IGraphics::CTextureHandle();\n\t\t\t}\n\n\t\t\tpSizeData->m_aTextures[i] = Graphics()->LoadTextureRaw(Width, Height, CImageInfo::FORMAT_ALPHA, pMem, CImageInfo::FORMAT_ALPHA, IGraphics::TEXLOAD_NOMIPMAPS);\n\t\t\tFontMemoryUsage += Width*Height;\n\t\t}\n\n\t\tpSizeData->m_NumXChars = Xchars;\n\t\tpSizeData->m_NumYChars = Ychars;\n\t\tpSizeData->m_TextureWidth = Width;\n\t\tpSizeData->m_TextureHeight = Height;\n\t\tpSizeData->m_CurrentCharacter = 0;\n\t\t\n\t\tdbg_msg(\"\", \"pFont memory usage: %d\", FontMemoryUsage);\n\n\t\tmem_free(pMem);\n\t}\n\n\tint AdjustOutlineThicknessToFontSize(int OutlineThickness, int FontSize)\n\t{\n\t\tif(FontSize > 36)\n\t\t\tOutlineThickness *= 4;\n\t\telse if(FontSize >= 18)\n\t\t\tOutlineThickness *= 2;\n\t\treturn OutlineThickness;\n\t}\n\n\tvoid IncreaseTextureSize(CFontSizeData *pSizeData)\n\t{\n\t\tif(pSizeData->m_TextureWidth < pSizeData->m_TextureHeight)\n\t\t\tpSizeData->m_NumXChars <<= 1;\n\t\telse\n\t\t\tpSizeData->m_NumYChars <<= 1;\n\t\tInitTexture(pSizeData, pSizeData->m_CharMaxWidth, pSizeData->m_CharMaxHeight, pSizeData->m_NumXChars, pSizeData->m_NumYChars);\n\t}\n\n\n\t// TODO: Refactor: move this into a pFont class\n\tvoid InitIndex(CFont *pFont, int Index)\n\t{\n\t\tCFontSizeData *pSizeData = &pFont->m_aSizes[Index];\n\n\t\tpSizeData->m_FontSize = aFontSizes[Index];\n\t\tFT_Set_Pixel_Sizes(pFont->m_FtFace, 0, pSizeData->m_FontSize);\n\n\t\tint OutlineThickness = AdjustOutlineThicknessToFontSize(1, pSizeData->m_FontSize);\n\n\t\t{\n\t\t\tunsigned GlyphIndex;\n\t\t\tint MaxH = 0;\n\t\t\tint MaxW = 0;\n\n\t\t\tint Charcode = FT_Get_First_Char(pFont->m_FtFace, &GlyphIndex);\n\t\t\twhile(GlyphIndex != 0)\n\t\t\t{\n\t\t\t\t// do stuff\n\t\t\t\tFT_Load_Glyph(pFont->m_FtFace, GlyphIndex, FT_LOAD_DEFAULT);\n\n\t\t\t\tif(pFont->m_FtFace->glyph->metrics.width > MaxW) MaxW = pFont->m_FtFace->glyph->metrics.width; // ignore_convention\n\t\t\t\tif(pFont->m_FtFace->glyph->metrics.height > MaxH) MaxH = pFont->m_FtFace->glyph->metrics.height; // ignore_convention\n\t\t\t\tCharcode = FT_Get_Next_Char(pFont->m_FtFace, Charcode, &GlyphIndex);\n\t\t\t}\n\n\t\t\tMaxW = (MaxW>>6)+2+OutlineThickness*2;\n\t\t\tMaxH = (MaxH>>6)+2+OutlineThickness*2;\n\n\t\t\tfor(pSizeData->m_CharMaxWidth = 1; pSizeData->m_CharMaxWidth < MaxW; pSizeData->m_CharMaxWidth <<= 1);\n\t\t\tfor(pSizeData->m_CharMaxHeight = 1; pSizeData->m_CharMaxHeight < MaxH; pSizeData->m_CharMaxHeight <<= 1);\n\t\t}\n\n\t\t//dbg_msg(\"pFont\", \"init size %d, texture size %d %d\", pFont->sizes[index].font_size, w, h);\n\t\t//FT_New_Face(m_FTLibrary, \"data/fonts/vera.ttf\", 0, &pFont->ft_face);\n\t\tInitTexture(pSizeData, pSizeData->m_CharMaxWidth, pSizeData->m_CharMaxHeight, 8, 8);\n\t}\n\n\tCFontSizeData *GetSize(CFont *pFont, int Pixelsize)\n\t{\n\t\tint Index = GetFontSizeIndex(Pixelsize);\n\t\tif(pFont->m_aSizes[Index].m_FontSize != aFontSizes[Index])\n\t\t\tInitIndex(pFont, Index);\n\t\treturn &pFont->m_aSizes[Index];\n\t}\n\n\n\tvoid UploadGlyph(CFontSizeData *pSizeData, int Texnum, int SlotID, int Chr, const void *pData)\n\t{\n\t\tint x = (SlotID%pSizeData->m_NumXChars) * (pSizeData->m_TextureWidth/pSizeData->m_NumXChars);\n\t\tint y = (SlotID/pSizeData->m_NumXChars) * (pSizeData->m_TextureHeight/pSizeData->m_NumYChars);\n\n\t\tGraphics()->LoadTextureRawSub(pSizeData->m_aTextures[Texnum], x, y,\n\t\t\tpSizeData->m_TextureWidth/pSizeData->m_NumXChars,\n\t\t\tpSizeData->m_TextureHeight/pSizeData->m_NumYChars,\n\t\t\tCImageInfo::FORMAT_ALPHA, pData);\n\t\t/*\n\t\tglBindTexture(GL_TEXTURE_2D, pSizeData->m_aTextures[Texnum]);\n\t\tglTexSubImage2D(GL_TEXTURE_2D, 0, x, y,\n\t\t\tpSizeData->m_TextureWidth/pSizeData->m_NumXChars,\n\t\t\tpSizeData->m_TextureHeight/pSizeData->m_NumYChars,\n\t\t\tm_FontTextureFormat, GL_UNSIGNED_BYTE, pData);*/\n\t}\n\n\t// 32k of data used for rendering glyphs\n\tunsigned char ms_aGlyphData[(1024/8) * (1024/8)];\n\tunsigned char ms_aGlyphDataOutlined[(1024/8) * (1024/8)];\n\n\tint GetSlot(CFontSizeData *pSizeData)\n\t{\n\t\tint CharCount = pSizeData->m_NumXChars*pSizeData->m_NumYChars;\n\t\tif(pSizeData->m_CurrentCharacter < CharCount)\n\t\t{\n\t\t\tint i = pSizeData->m_CurrentCharacter;\n\t\t\tpSizeData->m_CurrentCharacter++;\n\t\t\treturn i;\n\t\t}\n\n\t\t// kick out the oldest\n\t\t// TODO: remove this linear search\n\t\t{\n\t\t\tint Oldest = 0;\n\t\t\tfor(int i = 1; i < CharCount; i++)\n\t\t\t{\n\t\t\t\tif(pSizeData->m_aCharacters[i].m_TouchTime < pSizeData->m_aCharacters[Oldest].m_TouchTime)\n\t\t\t\t\tOldest = i;\n\t\t\t}\n\n\t\t\tif(time_get()-pSizeData->m_aCharacters[Oldest].m_TouchTime < time_freq() &&\n\t\t\t\t(pSizeData->m_NumXChars < MAX_CHARACTERS || pSizeData->m_NumYChars < MAX_CHARACTERS))\n\t\t\t{\n\t\t\t\tIncreaseTextureSize(pSizeData);\n\t\t\t\treturn GetSlot(pSizeData);\n\t\t\t}\n\n\t\t\treturn Oldest;\n\t\t}\n\t}\n\n\tint RenderGlyph(CFont *pFont, CFontSizeData *pSizeData, int Chr)\n\t{\n\t\tFT_Bitmap *pBitmap;\n\t\tint SlotID = 0;\n\t\tint SlotW = pSizeData->m_TextureWidth / pSizeData->m_NumXChars;\n\t\tint SlotH = pSizeData->m_TextureHeight / pSizeData->m_NumYChars;\n\t\tint SlotSize = SlotW*SlotH;\n\t\tint x = 1;\n\t\tint y = 1;\n\t\tint px, py;\n\n\t\tFT_Set_Pixel_Sizes(pFont->m_FtFace, 0, pSizeData->m_FontSize);\n\n\t\tif(FT_Load_Char(pFont->m_FtFace, Chr, FT_LOAD_RENDER|FT_LOAD_NO_BITMAP))\n\t\t{\n\t\t\tdbg_msg(\"pFont\", \"error loading glyph %d\", Chr);\n\t\t\treturn -1;\n\t\t}\n\n\t\tpBitmap = &pFont->m_FtFace->glyph->bitmap; // ignore_convention\n\n\t\t// fetch slot\n\t\tSlotID = GetSlot(pSizeData);\n\t\tif(SlotID < 0)\n\t\t\treturn -1;\n\n\t\t// adjust spacing\n\t\tint OutlineThickness = AdjustOutlineThicknessToFontSize(1, pSizeData->m_FontSize);\n\t\tx += OutlineThickness;\n\t\ty += OutlineThickness;\n\n\t\t// prepare glyph data\n\t\tmem_zero(ms_aGlyphData, SlotSize);\n\n\t\tif(pBitmap->pixel_mode == FT_PIXEL_MODE_GRAY) // ignore_convention\n\t\t{\n\t\t\tfor(py = 0; py < pBitmap->rows; py++) // ignore_convention\n\t\t\t\tfor(px = 0; px < pBitmap->width; px++) // ignore_convention\n\t\t\t\t\tms_aGlyphData[(py+y)*SlotW+px+x] = pBitmap->buffer[py*pBitmap->pitch+px]; // ignore_convention\n\t\t}\n\t\telse if(pBitmap->pixel_mode == FT_PIXEL_MODE_MONO) // ignore_convention\n\t\t{\n\t\t\tfor(py = 0; py < pBitmap->rows; py++) // ignore_convention\n\t\t\t\tfor(px = 0; px < pBitmap->width; px++) // ignore_convention\n\t\t\t\t{\n\t\t\t\t\tif(pBitmap->buffer[py*pBitmap->pitch+px/8]&(1<<(7-(px%8)))) // ignore_convention\n\t\t\t\t\t\tms_aGlyphData[(py+y)*SlotW+px+x] = 255;\n\t\t\t\t}\n\t\t}\n\n\t\tif(0) for(py = 0; py < SlotW; py++)\n\t\t\tfor(px = 0; px < SlotH; px++)\n\t\t\t\tms_aGlyphData[py*SlotW+px] = 255;\n\n\t\t// upload the glyph\n\t\tUploadGlyph(pSizeData, 0, SlotID, Chr, ms_aGlyphData);\n\n\t\tif(OutlineThickness == 1)\n\t\t{\n\t\t\tGrow(ms_aGlyphData, ms_aGlyphDataOutlined, SlotW, SlotH);\n\t\t\tUploadGlyph(pSizeData, 1, SlotID, Chr, ms_aGlyphDataOutlined);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor(int i = OutlineThickness; i > 0; i-=2)\n\t\t\t{\n\t\t\t\tGrow(ms_aGlyphData, ms_aGlyphDataOutlined, SlotW, SlotH);\n\t\t\t\tGrow(ms_aGlyphDataOutlined, ms_aGlyphData, SlotW, SlotH);\n\t\t\t}\n\t\t\tUploadGlyph(pSizeData, 1, SlotID, Chr, ms_aGlyphData);\n\t\t}\n\n\t\t// set char info\n\t\t{\n\t\t\tCFontChar *pFontchr = &pSizeData->m_aCharacters[SlotID];\n\t\t\tfloat Scale = 1.0f/pSizeData->m_FontSize;\n\t\t\tfloat Uscale = 1.0f/pSizeData->m_TextureWidth;\n\t\t\tfloat Vscale = 1.0f/pSizeData->m_TextureHeight;\n\t\t\tint Height = pBitmap->rows + OutlineThickness*2 + 2; // ignore_convention\n\t\t\tint Width = pBitmap->width + OutlineThickness*2 + 2; // ignore_convention\n\n\t\t\tpFontchr->m_ID = Chr;\n\t\t\tpFontchr->m_Height = Height * Scale;\n\t\t\tpFontchr->m_Width = Width * Scale;\n\t\t\tpFontchr->m_OffsetX = (pFont->m_FtFace->glyph->bitmap_left-1) * Scale; // ignore_convention\n\t\t\tpFontchr->m_OffsetY = (pSizeData->m_FontSize - pFont->m_FtFace->glyph->bitmap_top) * Scale; // ignore_convention\n\t\t\tpFontchr->m_AdvanceX = (pFont->m_FtFace->glyph->advance.x>>6) * Scale; // ignore_convention\n\n\t\t\tpFontchr->m_aUvs[0] = (SlotID%pSizeData->m_NumXChars) / (float)(pSizeData->m_NumXChars);\n\t\t\tpFontchr->m_aUvs[1] = (SlotID/pSizeData->m_NumXChars) / (float)(pSizeData->m_NumYChars);\n\t\t\tpFontchr->m_aUvs[2] = pFontchr->m_aUvs[0] + Width*Uscale;\n\t\t\tpFontchr->m_aUvs[3] = pFontchr->m_aUvs[1] + Height*Vscale;\n\t\t}\n\n\t\treturn SlotID;\n\t}\n\n\tCFontChar *GetChar(CFont *pFont, CFontSizeData *pSizeData, int Chr)\n\t{\n\t\tCFontChar *pFontchr = NULL;\n\n\t\t// search for the character\n\t\t// TODO: remove this linear search\n\t\tint i;\n\t\tfor(i = 0; i < pSizeData->m_CurrentCharacter; i++)\n\t\t{\n\t\t\tif(pSizeData->m_aCharacters[i].m_ID == Chr)\n\t\t\t{\n\t\t\t\tpFontchr = &pSizeData->m_aCharacters[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// check if we need to render the character\n\t\tif(!pFontchr)\n\t\t{\n\t\t\tint Index = RenderGlyph(pFont, pSizeData, Chr);\n\t\t\tif(Index >= 0)\n\t\t\t\tpFontchr = &pSizeData->m_aCharacters[Index];\n\t\t}\n\n\t\t// touch the character\n\t\t// TODO: don't call time_get here\n\t\tif(pFontchr)\n\t\t\tpFontchr->m_TouchTime = time_get();\n\n\t\treturn pFontchr;\n\t}\n\n\t// must only be called from the rendering function as the pFont must be set to the correct size\n\tvoid RenderSetup(CFont *pFont, int size)\n\t{\n\t\tFT_Set_Pixel_Sizes(pFont->m_FtFace, 0, size);\n\t}\n\n\tfloat Kerning(CFont *pFont, int Left, int Right)\n\t{\n\t\tFT_Vector Kerning = {0,0};\n\t\tFT_Get_Kerning(pFont->m_FtFace, Left, Right, FT_KERNING_DEFAULT, &Kerning);\n\t\treturn (Kerning.x>>6);\n\t}\n\n\npublic:\n\tCTextRender()\n\t{\n\t\tm_pGraphics = 0;\n\n\t\tm_TextR = 1.0f;\n\t\tm_TextG = 1.0f;\n\t\tm_TextB = 1.0f;\n\t\tm_TextA = 1.0f;\n\t\tm_TextOutlineR = 0.0f;\n\t\tm_TextOutlineG = 0.0f;\n\t\tm_TextOutlineB = 0.0f;\n\t\tm_TextOutlineA = 0.3f;\n\n\t\tm_pDefaultFont = 0;\n\n\t\t// GL_LUMINANCE can be good for debugging\n\t\t//m_FontTextureFormat = GL_ALPHA;\n\t}\n\n\tvirtual void Init()\n\t{\n\t\tm_pGraphics = Kernel()->RequestInterface<IGraphics>();\n\t\tFT_Init_FreeType(&m_FTLibrary);\n\t}\n\n\n\tvirtual CFont *LoadFont(const char *pFilename)\n\t{\n\t\tCFont *pFont = (CFont *)mem_alloc(sizeof(CFont), 1);\n\n\t\tmem_zero(pFont, sizeof(*pFont));\n\t\tstr_copy(pFont->m_aFilename, pFilename, sizeof(pFont->m_aFilename));\n\n\t\tif(FT_New_Face(m_FTLibrary, pFont->m_aFilename, 0, &pFont->m_FtFace))\n\t\t{\n\t\t\tmem_free(pFont);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tfor(unsigned i = 0; i < NUM_FONT_SIZES; i++)\n\t\t\tpFont->m_aSizes[i].m_FontSize = -1;\n\n\t\tdbg_msg(\"textrender\", \"loaded pFont from '%s'\", pFilename);\n\t\treturn pFont;\n\t};\n\n\tvirtual void DestroyFont(CFont *pFont)\n\t{\n\t\tmem_free(pFont);\n\t}\n\n\tvirtual void SetDefaultFont(CFont *pFont)\n\t{\n\t\tdbg_msg(\"textrender\", \"default pFont set %p\", pFont);\n\t\tm_pDefaultFont = pFont;\n\t}\n\n\n\tvirtual void SetCursor(CTextCursor *pCursor, float x, float y, float FontSize, int Flags)\n\t{\n\t\tmem_zero(pCursor, sizeof(*pCursor));\n\t\tpCursor->m_FontSize = FontSize;\n\t\tpCursor->m_StartX = x;\n\t\tpCursor->m_StartY = y;\n\t\tpCursor->m_X = x;\n\t\tpCursor->m_Y = y;\n\t\tpCursor->m_LineCount = 1;\n\t\tpCursor->m_LineWidth = -1;\n\t\tpCursor->m_Flags = Flags;\n\t\tpCursor->m_CharCount = 0;\n\t}\n\n\n\tvirtual void Text(void *pFontSetV, float x, float y, float Size, const char *pText, int MaxWidth)\n\t{\n\t\tCTextCursor Cursor;\n\t\tSetCursor(&Cursor, x, y, Size, TEXTFLAG_RENDER);\n\t\tCursor.m_LineWidth = MaxWidth;\n\t\tTextEx(&Cursor, pText, -1);\n\t}\n\n\tvirtual float TextWidth(void *pFontSetV, float Size, const char *pText, int Length)\n\t{\n\t\tCTextCursor Cursor;\n\t\tSetCursor(&Cursor, 0, 0, Size, 0);\n\t\tTextEx(&Cursor, pText, Length);\n\t\treturn Cursor.m_X;\n\t}\n\n\tvirtual int TextLineCount(void *pFontSetV, float Size, const char *pText, float LineWidth)\n\t{\n\t\tCTextCursor Cursor;\n\t\tSetCursor(&Cursor, 0, 0, Size, 0);\n\t\tCursor.m_LineWidth = LineWidth;\n\t\tTextEx(&Cursor, pText, -1);\n\t\treturn Cursor.m_LineCount;\n\t}\n\n\tvirtual void TextColor(float r, float g, float b, float a)\n\t{\n\t\tm_TextR = r;\n\t\tm_TextG = g;\n\t\tm_TextB = b;\n\t\tm_TextA = a;\n\t}\n\n\tvirtual void TextOutlineColor(float r, float g, float b, float a)\n\t{\n\t\tm_TextOutlineR = r;\n\t\tm_TextOutlineG = g;\n\t\tm_TextOutlineB = b;\n\t\tm_TextOutlineA = a;\n\t}\n\n\tvirtual void TextEx(CTextCursor *pCursor, const char *pText, int Length)\n\t{\n\t\tCFont *pFont = pCursor->m_pFont;\n\t\tCFontSizeData *pSizeData = NULL;\n\n\t\t//dbg_msg(\"textrender\", \"rendering text '%s'\", text);\n\n\t\tfloat ScreenX0, ScreenY0, ScreenX1, ScreenY1;\n\t\tfloat FakeToScreenX, FakeToScreenY;\n\t\tint ActualX, ActualY;\n\n\t\tint ActualSize;\n\t\tint i;\n\t\tint GotNewLine = 0;\n\t\tfloat DrawX = 0.0f, DrawY = 0.0f;\n\t\tint LineCount = 0;\n\t\tfloat CursorX, CursorY;\n\n\t\tfloat Size = pCursor->m_FontSize;\n\n\t\t// to correct coords, convert to screen coords, round, and convert back\n\t\tGraphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1);\n\n\t\tFakeToScreenX = (Graphics()->ScreenWidth()/(ScreenX1-ScreenX0));\n\t\tFakeToScreenY = (Graphics()->ScreenHeight()/(ScreenY1-ScreenY0));\n\t\tActualX = (int)(pCursor->m_X * FakeToScreenX);\n\t\tActualY = (int)(pCursor->m_Y * FakeToScreenY);\n\n\t\tCursorX = ActualX / FakeToScreenX;\n\t\tCursorY = ActualY / FakeToScreenY;\n\n\t\t// same with size\n\t\tActualSize = (int)(Size * FakeToScreenY);\n\t\tSize = ActualSize / FakeToScreenY;\n\n\t\t// fetch pFont data\n\t\tif(!pFont)\n\t\t\tpFont = m_pDefaultFont;\n\n\t\tif(!pFont)\n\t\t\treturn;\n\n\t\tpSizeData = GetSize(pFont, ActualSize);\n\t\tRenderSetup(pFont, ActualSize);\n\n\t\tfloat Scale = 1/pSizeData->m_FontSize;\n\n\t\t// set length\n\t\tif(Length < 0)\n\t\t\tLength = str_length(pText);\n\n\t\t// if we don't want to render, we can just skip the first outline pass\n\t\ti = 1;\n\t\tif(pCursor->m_Flags&TEXTFLAG_RENDER)\n\t\t\ti = 0;\n\n\t\tfor(;i < 2; i++)\n\t\t{\n\t\t\tconst char *pCurrent = (char *)pText;\n\t\t\tconst char *pEnd = pCurrent+Length;\n\t\t\tDrawX = CursorX;\n\t\t\tDrawY = CursorY;\n\t\t\tLineCount = pCursor->m_LineCount;\n\n\t\t\tif(pCursor->m_Flags&TEXTFLAG_RENDER)\n\t\t\t{\n\t\t\t\t// TODO: Make this better\n\t\t\t\tif (i == 0)\n\t\t\t\t\tGraphics()->TextureSet(pSizeData->m_aTextures[1]);\n\t\t\t\telse\n\t\t\t\t\tGraphics()->TextureSet(pSizeData->m_aTextures[0]);\n\n\t\t\t\tGraphics()->QuadsBegin();\n\t\t\t\tif (i == 0)\n\t\t\t\t\tGraphics()->SetColor(m_TextOutlineR, m_TextOutlineG, m_TextOutlineB, m_TextOutlineA*m_TextA);\n\t\t\t\telse\n\t\t\t\t\tGraphics()->SetColor(m_TextR, m_TextG, m_TextB, m_TextA);\n\t\t\t}\n\n\t\t\twhile(pCurrent < pEnd && (pCursor->m_MaxLines < 1 || LineCount <= pCursor->m_MaxLines))\n\t\t\t{\n\t\t\t\tint NewLine = 0;\n\t\t\t\tconst char *pBatchEnd = pEnd;\n\t\t\t\tif(pCursor->m_LineWidth > 0 && !(pCursor->m_Flags&TEXTFLAG_STOP_AT_END))\n\t\t\t\t{\n\t\t\t\t\tint Wlen = min(WordLength((char *)pCurrent), (int)(pEnd-pCurrent));\n\t\t\t\t\tCTextCursor Compare = *pCursor;\n\t\t\t\t\tCompare.m_X = DrawX;\n\t\t\t\t\tCompare.m_Y = DrawY;\n\t\t\t\t\tCompare.m_Flags &= ~TEXTFLAG_RENDER;\n\t\t\t\t\tCompare.m_LineWidth = -1;\n\t\t\t\t\tTextEx(&Compare, pCurrent, Wlen);\n\n\t\t\t\t\tif(Compare.m_X-DrawX > pCursor->m_LineWidth)\n\t\t\t\t\t{\n\t\t\t\t\t\t// word can't be fitted in one line, cut it\n\t\t\t\t\t\tCTextCursor Cutter = *pCursor;\n\t\t\t\t\t\tCutter.m_CharCount = 0;\n\t\t\t\t\t\tCutter.m_X = DrawX;\n\t\t\t\t\t\tCutter.m_Y = DrawY;\n\t\t\t\t\t\tCutter.m_Flags &= ~TEXTFLAG_RENDER;\n\t\t\t\t\t\tCutter.m_Flags |= TEXTFLAG_STOP_AT_END;\n\n\t\t\t\t\t\tTextEx(&Cutter, (const char *)pCurrent, Wlen);\n\t\t\t\t\t\tWlen = Cutter.m_CharCount;\n\t\t\t\t\t\tNewLine = 1;\n\n\t\t\t\t\t\tif(Wlen <= 3) // if we can't place 3 chars of the word on this line, take the next\n\t\t\t\t\t\t\tWlen = 0;\n\t\t\t\t\t}\n\t\t\t\t\telse if(Compare.m_X-pCursor->m_StartX > pCursor->m_LineWidth)\n\t\t\t\t\t{\n\t\t\t\t\t\tNewLine = 1;\n\t\t\t\t\t\tWlen = 0;\n\t\t\t\t\t}\n\n\t\t\t\t\tpBatchEnd = pCurrent + Wlen;\n\t\t\t\t}\n\n\t\t\t\tconst char *pTmp = pCurrent;\n\t\t\t\tint NextCharacter = str_utf8_decode(&pTmp);\n\t\t\t\twhile(pCurrent < pBatchEnd)\n\t\t\t\t{\n\t\t\t\t\tint Character = NextCharacter;\n\t\t\t\t\tpCurrent = pTmp;\n\t\t\t\t\tNextCharacter = str_utf8_decode(&pTmp);\n\n\t\t\t\t\tif(Character == '\\n')\n\t\t\t\t\t{\n\t\t\t\t\t\tDrawX = pCursor->m_StartX;\n\t\t\t\t\t\tDrawY += Size;\n\t\t\t\t\t\tDrawX = (int)(DrawX * FakeToScreenX) / FakeToScreenX; // realign\n\t\t\t\t\t\tDrawY = (int)(DrawY * FakeToScreenY) / FakeToScreenY;\n\t\t\t\t\t\t++LineCount;\n\t\t\t\t\t\tif(pCursor->m_MaxLines > 0 && LineCount > pCursor->m_MaxLines)\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tCFontChar *pChr = GetChar(pFont, pSizeData, Character);\n\t\t\t\t\tif(pChr)\n\t\t\t\t\t{\n\t\t\t\t\t\tfloat Advance = pChr->m_AdvanceX + Kerning(pFont, Character, NextCharacter)*Scale;\n\t\t\t\t\t\tif(pCursor->m_Flags&TEXTFLAG_STOP_AT_END && DrawX+Advance*Size-pCursor->m_StartX > pCursor->m_LineWidth)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// we hit the end of the line, no more to render or count\n\t\t\t\t\t\t\tpCurrent = pEnd;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif(pCursor->m_Flags&TEXTFLAG_RENDER)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tGraphics()->QuadsSetSubset(pChr->m_aUvs[0], pChr->m_aUvs[1], pChr->m_aUvs[2], pChr->m_aUvs[3]);\n\t\t\t\t\t\t\tIGraphics::CQuadItem QuadItem(DrawX+pChr->m_OffsetX*Size, DrawY+pChr->m_OffsetY*Size, pChr->m_Width*Size, pChr->m_Height*Size);\n\t\t\t\t\t\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tDrawX += Advance*Size;\n\t\t\t\t\t\tpCursor->m_CharCount++;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(NewLine)\n\t\t\t\t{\n\t\t\t\t\tDrawX = pCursor->m_StartX;\n\t\t\t\t\tDrawY += Size;\n\t\t\t\t\tGotNewLine = 1;\n\t\t\t\t\tDrawX = (int)(DrawX * FakeToScreenX) / FakeToScreenX; // realign\n\t\t\t\t\tDrawY = (int)(DrawY * FakeToScreenY) / FakeToScreenY;\n\t\t\t\t\t++LineCount;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(pCursor->m_Flags&TEXTFLAG_RENDER)\n\t\t\t\tGraphics()->QuadsEnd();\n\t\t}\n\n\t\tpCursor->m_X = DrawX;\n\t\tpCursor->m_LineCount = LineCount;\n\n\t\tif(GotNewLine)\n\t\t\tpCursor->m_Y = DrawY;\n\t}\n\n};\n\nIEngineTextRender *CreateEngineTextRender() { return new CTextRender; }\n"
  },
  {
    "path": "src/engine/client.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_CLIENT_H\n#define ENGINE_CLIENT_H\n#include \"kernel.h\"\n\n#include \"message.h\"\n#include \"graphics.h\"\n\nclass IClient : public IInterface\n{\n\tMACRO_INTERFACE(\"client\", 0)\nprotected:\n\t// quick access to state of the client\n\tint m_State;\n\n\t// quick access to time variables\n\tint m_PrevGameTick;\n\tint m_CurGameTick;\n\tfloat m_GameIntraTick;\n\tfloat m_GameTickTime;\n\n\tint m_CurMenuTick;\n\tint64 m_MenuStartTime;\n\n\tint m_PredTick;\n\tfloat m_PredIntraTick;\n\n\tfloat m_LocalTime;\n\tfloat m_RenderFrameTime;\n\n\tint m_GameTickSpeed;\npublic:\n\n\tclass CSnapItem\n\t{\n\tpublic:\n\t\tint m_Type;\n\t\tint m_ID;\n\t\tint m_DataSize;\n\t};\n\n\t/* Constants: Client States\n\t\tSTATE_OFFLINE - The client is offline.\n\t\tSTATE_CONNECTING - The client is trying to connect to a server.\n\t\tSTATE_LOADING - The client has connected to a server and is loading resources.\n\t\tSTATE_ONLINE - The client is connected to a server and running the game.\n\t\tSTATE_DEMOPLAYBACK - The client is playing a demo\n\t\tSTATE_QUITING - The client is quiting.\n\t*/\n\n\tenum\n\t{\n\t\tSTATE_OFFLINE=0,\n\t\tSTATE_CONNECTING,\n\t\tSTATE_LOADING,\n\t\tSTATE_ONLINE,\n\t\tSTATE_DEMOPLAYBACK,\n\t\tSTATE_QUITING,\n\t};\n\n\t//\n\tinline int State() const { return m_State; }\n\n\t// tick time access\n\tinline int PrevGameTick() const { return m_PrevGameTick; }\n\tinline int GameTick() const { return m_CurGameTick; }\n\tinline int MenuTick() const { return m_CurMenuTick; }\n\tinline int PredGameTick() const { return m_PredTick; }\n\tinline float IntraGameTick() const { return m_GameIntraTick; }\n\tinline float PredIntraGameTick() const { return m_PredIntraTick; }\n\tinline float GameTickTime() const { return m_GameTickTime; }\n\tinline int GameTickSpeed() const { return m_GameTickSpeed; }\n\n\t// other time access\n\tinline float RenderFrameTime() const { return m_RenderFrameTime; }\n\tinline float LocalTime() const { return m_LocalTime; }\n\n\t// actions\n\tvirtual void Connect(const char *pAddress) = 0;\n\tvirtual void Disconnect() = 0;\n\tvirtual void Quit() = 0;\n\tvirtual const char *DemoPlayer_Play(const char *pFilename, int StorageType) = 0;\n\tvirtual void DemoRecorder_Start(const char *pFilename, bool WithTimestamp) = 0;\n\tvirtual void DemoRecorder_HandleAutoStart() = 0;\n\tvirtual void DemoRecorder_Stop() = 0;\n\tvirtual void RecordGameMessage(bool State) = 0;\n\tvirtual void AutoScreenshot_Start() = 0;\n\tvirtual void ServerBrowserUpdate() = 0;\n\n\t// networking\n\tvirtual void EnterGame() = 0;\n\n\t//\n\tvirtual int MapDownloadAmount() = 0;\n\tvirtual int MapDownloadTotalsize() = 0;\n\n\t// input\n\tvirtual int *GetInput(int Tick) = 0;\n\n\t// remote console\n\tvirtual void RconAuth(const char *pUsername, const char *pPassword) = 0;\n\tvirtual bool RconAuthed() = 0;\n\tvirtual bool UseTempRconCommands() = 0;\n\tvirtual void Rcon(const char *pLine) = 0;\n\n\t// server info\n\tvirtual void GetServerInfo(class CServerInfo *pServerInfo) = 0;\n\n\t// snapshot interface\n\n\tenum\n\t{\n\t\tSNAP_CURRENT=0,\n\t\tSNAP_PREV=1\n\t};\n\n\t// TODO: Refactor: should redo this a bit i think, too many virtual calls\n\tvirtual int SnapNumItems(int SnapID) = 0;\n\tvirtual void *SnapFindItem(int SnapID, int Type, int ID) = 0;\n\tvirtual void *SnapGetItem(int SnapID, int Index, CSnapItem *pItem) = 0;\n\tvirtual void SnapInvalidateItem(int SnapID, int Index) = 0;\n\t\n\tvirtual void *SnapNewItem(int Type, int ID, int Size) = 0;\n\n\tvirtual void SnapSetStaticsize(int ItemType, int Size) = 0;\n\n\tvirtual int SendMsg(CMsgPacker *pMsg, int Flags) = 0;\n\n\ttemplate<class T>\n\tint SendPackMsg(T *pMsg, int Flags)\n\t{\n\t\tCMsgPacker Packer(pMsg->MsgID(), false);\n\t\tif(pMsg->Pack(&Packer))\n\t\t\treturn -1;\n\t\treturn SendMsg(&Packer, Flags);\n\t}\n\n\t//\n\tvirtual const char *ErrorString() = 0;\n\tvirtual const char *LatestVersion() = 0;\n\tvirtual bool ConnectionProblems() = 0;\n\n\tvirtual bool SoundInitFailed() = 0;\n\n\tvirtual IGraphics::CTextureHandle GetDebugFont() = 0; // TODO: remove this function\n};\n\nclass IGameClient : public IInterface\n{\n\tMACRO_INTERFACE(\"gameclient\", 0)\nprotected:\npublic:\n\tvirtual void OnConsoleInit() = 0;\n\n\tvirtual void OnRconLine(const char *pLine) = 0;\n\tvirtual void OnInit() = 0;\n\tvirtual void OnNewSnapshot() = 0;\n\tvirtual void OnDemoRecSnap() = 0;\n\tvirtual void OnEnterGame() = 0;\n\tvirtual void OnShutdown() = 0;\n\tvirtual void OnRender() = 0;\n\tvirtual void OnStateChange(int NewState, int OldState) = 0;\n\tvirtual void OnConnected() = 0;\n\tvirtual void OnMessage(int MsgID, CUnpacker *pUnpacker) = 0;\n\tvirtual void OnPredict() = 0;\n\tvirtual void OnActivateEditor() = 0;\n\n\tvirtual int OnSnapInput(int *pData) = 0;\n\n\tvirtual const char *GetItemName(int Type) = 0;\n\tvirtual const char *Version() = 0;\n\tvirtual const char *NetVersion() = 0;\n\n};\n\nextern IGameClient *CreateGameClient();\n#endif\n"
  },
  {
    "path": "src/engine/config.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_CONFIG_H\n#define ENGINE_CONFIG_H\n\n#include \"kernel.h\"\n\nclass IConfig : public IInterface\n{\n\tMACRO_INTERFACE(\"config\", 0)\npublic:\n\ttypedef void (*SAVECALLBACKFUNC)(IConfig *pConfig, void *pUserData);\n\n\tvirtual void Init() = 0;\n\tvirtual void Reset() = 0;\n\tvirtual void RestoreStrings() = 0;\n\tvirtual void Save() = 0;\n\n\tvirtual void RegisterCallback(SAVECALLBACKFUNC pfnFunc, void *pUserData) = 0;\n\n\tvirtual void WriteLine(const char *pLine) = 0;\n};\n\nextern IConfig *CreateConfig();\n\n#endif\n"
  },
  {
    "path": "src/engine/console.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_CONSOLE_H\n#define ENGINE_CONSOLE_H\n\n#include \"kernel.h\"\n\nclass IConsole : public IInterface\n{\n\tMACRO_INTERFACE(\"console\", 0)\npublic:\n\n\t//\tTODO: rework/cleanup\n\tenum\n\t{\n\t\tOUTPUT_LEVEL_STANDARD=0,\n\t\tOUTPUT_LEVEL_ADDINFO,\n\t\tOUTPUT_LEVEL_DEBUG,\n\n\t\tACCESS_LEVEL_ADMIN=0,\n\t\tACCESS_LEVEL_MOD,\n\n\t\tTEMPCMD_NAME_LENGTH=32,\n\t\tTEMPCMD_HELP_LENGTH=96,\n\t\tTEMPCMD_PARAMS_LENGTH=16,\n\n\t\tMAX_PRINT_CB=4,\n\t};\n\n\t// TODO: rework this interface to reduce the amount of virtual calls\n\tclass IResult\n\t{\n\tprotected:\n\t\tunsigned m_NumArgs;\n\tpublic:\n\t\tIResult() { m_NumArgs = 0; }\n\t\tvirtual ~IResult() {}\n\n\t\tvirtual int GetInteger(unsigned Index) = 0;\n\t\tvirtual float GetFloat(unsigned Index) = 0;\n\t\tvirtual const char *GetString(unsigned Index) = 0;\n\n\t\tint NumArguments() const { return m_NumArgs; }\n\t};\n\n\tclass CCommandInfo\n\t{\n\tprotected:\n\t\tint m_AccessLevel;\n\tpublic:\n\t\tCCommandInfo() { m_AccessLevel = ACCESS_LEVEL_ADMIN; }\n\t\tvirtual ~CCommandInfo() {}\n\t\tconst char *m_pName;\n\t\tconst char *m_pHelp;\n\t\tconst char *m_pParams;\n\n\t\tvirtual const CCommandInfo *NextCommandInfo(int AccessLevel, int FlagMask) const = 0;\n\n\t\tint GetAccessLevel() const { return m_AccessLevel; }\n\t};\n\n\ttypedef void (*FPrintCallback)(const char *pStr, void *pUser);\n\ttypedef void (*FPossibleCallback)(const char *pCmd, void *pUser);\n\ttypedef void (*FCommandCallback)(IResult *pResult, void *pUserData);\n\ttypedef void (*FChainCommandCallback)(IResult *pResult, void *pUserData, FCommandCallback pfnCallback, void *pCallbackUserData);\n\n\tvirtual const CCommandInfo *FirstCommandInfo(int AccessLevel, int Flagmask) const = 0;\n\tvirtual const CCommandInfo *GetCommandInfo(const char *pName, int FlagMask, bool Temp) = 0;\n\tvirtual void PossibleCommands(const char *pStr, int FlagMask, bool Temp, FPossibleCallback pfnCallback, void *pUser) = 0;\n\tvirtual void ParseArguments(int NumArgs, const char **ppArguments) = 0;\n\n\tvirtual void Register(const char *pName, const char *pParams, int Flags, FCommandCallback pfnFunc, void *pUser, const char *pHelp) = 0;\n\tvirtual void RegisterTemp(const char *pName, const char *pParams, int Flags, const char *pHelp) = 0;\n\tvirtual void DeregisterTemp(const char *pName) = 0;\n\tvirtual void DeregisterTempAll() = 0;\n\tvirtual void Chain(const char *pName, FChainCommandCallback pfnChainFunc, void *pUser) = 0;\n\tvirtual void StoreCommands(bool Store) = 0;\n\n\tvirtual bool LineIsValid(const char *pStr) = 0;\n\tvirtual void ExecuteLine(const char *Sptr) = 0;\n\tvirtual void ExecuteLineFlag(const char *Sptr, int FlasgMask) = 0;\n\tvirtual void ExecuteLineStroked(int Stroke, const char *pStr) = 0;\n\tvirtual void ExecuteFile(const char *pFilename) = 0;\n\n\tvirtual int RegisterPrintCallback(int OutputLevel, FPrintCallback pfnPrintCallback, void *pUserData) = 0;\n\tvirtual void SetPrintOutputLevel(int Index, int OutputLevel) = 0;\n\tvirtual void Print(int Level, const char *pFrom, const char *pStr) = 0;\n\n\tvirtual void SetAccessLevel(int AccessLevel) = 0;\n};\n\nextern IConsole *CreateConsole(int FlagMask);\n\n#endif // FILE_ENGINE_CONSOLE_H\n"
  },
  {
    "path": "src/engine/demo.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_DEMO_H\n#define ENGINE_DEMO_H\n\n#include \"kernel.h\"\n\nenum\n{\n\tMAX_TIMELINE_MARKERS=64\n};\n\nstruct CDemoHeader\n{\n\tunsigned char m_aMarker[7];\n\tunsigned char m_Version;\n\tchar m_aNetversion[64];\n\tchar m_aMapName[64];\n\tunsigned char m_aMapSize[4];\n\tunsigned char m_aMapCrc[4];\n\tchar m_aType[8];\n\tchar m_aLength[4];\n\tchar m_aTimestamp[20];\n\tchar m_aNumTimelineMarkers[4];\n\tchar m_aTimelineMarkers[MAX_TIMELINE_MARKERS][4];\n};\n\nclass IDemoPlayer : public IInterface\n{\n\tMACRO_INTERFACE(\"demoplayer\", 0)\npublic:\n\tclass CInfo\n\t{\n\tpublic:\n\t\tbool m_Paused;\n\t\tfloat m_Speed;\n\n\t\tint m_FirstTick;\n\t\tint m_CurrentTick;\n\t\tint m_LastTick;\n\n\t\tint m_NumTimelineMarkers;\n\t\tint m_aTimelineMarkers[MAX_TIMELINE_MARKERS];\n\t};\n\n\tenum\n\t{\n\t\tDEMOTYPE_INVALID=0,\n\t\tDEMOTYPE_CLIENT,\n\t\tDEMOTYPE_SERVER,\n\t};\n\n\t~IDemoPlayer() {}\n\tvirtual void SetSpeed(float Speed) = 0;\n\tvirtual int SetPos(float Percent) = 0;\n\tvirtual void Pause() = 0;\n\tvirtual void Unpause() = 0;\n\tvirtual const CInfo *BaseInfo() const = 0;\n\tvirtual void GetDemoName(char *pBuffer, int BufferSize) const = 0;\n\tvirtual bool GetDemoInfo(class IStorage *pStorage, const char *pFilename, int StorageType, CDemoHeader *pDemoHeader) const = 0;\n\tvirtual int GetDemoType() const = 0;\n};\n\nclass IDemoRecorder : public IInterface\n{\n\tMACRO_INTERFACE(\"demorecorder\", 0)\npublic:\n\t~IDemoRecorder() {}\n\tvirtual bool IsRecording() const = 0;\n\tvirtual int Stop() = 0;\n\tvirtual int Length() const = 0;\n};\n\n#endif\n"
  },
  {
    "path": "src/engine/docs/client_time.txt",
    "content": "Title: Time on the client\n\ntick, intratick\npredtick, predintratick\n\n prevtick              tick                 predtick\n   4                     8                    14\n   |---------------------|---------------------|\n   0 <- intratick    ->  1\n   0 <- ticktime(in s)-> X\n                         0 <- predintratick?-> 1\n"
  },
  {
    "path": "src/engine/docs/prediction.txt",
    "content": "Title: Prediction\n\nThe engine calls <modc_predict> when reprediction is required. This happens usally when new data has arrived from the server. <modc_predict> should to prediction from the current snapshot and current snapshot tick (<client_tick> + 1) upto and including the tick returned by <client_predtick>.\n\nPredicted input sent to the server can be retrived by calling <client_get_input> with the corresponding tick that you want the input for. Here is a simple example of how it might look.\n\n> void modc_predict()\n> {\n> \tint tick;\n> \tprediction_reset();\n>\n> \tfor(tick = client_tick()+1; tick <= client_predtick(); tick++)\n> \t{\n> \t\tMY_INPUT *input = (MY_INPUT *)client_get_input();\n> \t\tif(input)\n> \t\t\tprediction_apply_input(input);\n> \t\tprediction_tick();\n> \t}\n> }\n"
  },
  {
    "path": "src/engine/docs/server_op.txt",
    "content": "Title: Server Operation\n\nSection: Init\n\nSection: Running\n\nHere is an graph over how the server operates on each refresh.\n\n(start code)\nload map\ninit mod\n\nwhile running\n\tif map change then\n\t\tload new map\n\t\tshutdown mod <mods_shutdown>\n\t\treset clients to init state\n\t\tinit mod <mods_init>\n\tend if\n\n\tif new tick then\n\t\tcall <mods_tick>\n\t\tfor each client do\n\t\t\tcreate snapshot <mods_snap>\n\t\t\tsend snapshot\n\t\tend for\n\tend\n\n\tprocess new network messages\nend while\n\nunload map\n(end)\n\n\n\nSection: Reinit\n\nSection: Shutdown\n"
  },
  {
    "path": "src/engine/docs/snapshots.txt",
    "content": "Title: Snapshots\n\nSection: Overview\n\nTopic: Definitions\n\n- *Snapshot*. A is a serialized game state from which a client can render the game from. They are sent from the server at a regular interval and is created specificly for each client in order to reduce bandwidth.\n- *Delta Snapshot*. A set of data that can be applied to a snapshot in order to create a new snapshot with the updated game state.\n\nTopic: Structure\n\nA snapshot contains a series of items. Each item have a type, id and data.\n\n- *Type*. Type of item. Could be projectile or character for example.\n- *Id*. A unique id so the client can identify the item between two snapshots.\n- *Data*. A series of 32-bit integers that contains the per item type specific data.\n\nSection: Server Side\n\nTopic: Creating\n\nItems can be added when <mods_snap> is called using the <snap_new_item> function to insert an item to the snapshot. The server can not inspect the snapshot that is in progress of being created.\n\nSection: Client Side\n\nTopic: Inspection\n<modc_newsnapshot> is called when a new snapshot has arrived for processing. <snap_num_items>, <snap_get_item> and <snap_find_item> can be used to inspect the current and previous snapshot. This can be done anywhere while the client is running and not just in the <modc_newsnapshot> function. The client can also call <snap_invalidate_item> if an item contains improper information that could harm the operation of the client. This should however be done in <modc_newsnapshot> to assure that no bad data propagates into the rest of the client.\n\nTopic: Rendering\nDOCTODO\n\nSection: In depth\n\nTopic: Compression\n\nAfter a snapshot have been created, compression is applyed to reduce the bandwidth. There are several steps taken inorder to reduce the size of the size of the snapshot.\n\n- *Delta*. The server looks in a clients backlog of snapshots to find a previous acked snapshot. It then compares the two snapshots and creates a delta snapshot containing the changes from the previous acked snapshot to the new one.\n- *Variable Integers*. The delta snapshot which is only consisting of 32-bit integers is then encoded into variable integers similar to UTF-8. Each byte has a bit that tells the decoder that it needs one more byte to decode the 32-bit integer. The first byte also contains a bit for telling the sign of the integer.\n\n> ESDDDDDD EDDDDDDD EDDDDDDD EDDDDDDD\n\n> E = extend\n> S = sign\n> D = data bit\n\n- *Huffman*. The last step is to compress the buffer with a huffman encoder. It uses a static tree that is weighted towards 0 because it's where most of the data will be because of the delta compression.\n\nTopic: Interval\n\nThe interval for how often a client recives a snapshot changes during the course of the connection. There are three different snapshot rates.\n\n- *Init*. 5 snapshots per second. Used when a client is connecting and used until the client has acknowlaged a snapshot. This mechanism is used because the first snapshot because no delta compression can be done.\n\n- *Full*. Snapshot for every tick or every even tick depending on server configuration. This is used during normal gameplay and everything is running smooth.\n\n- *Recovery*. 1 snapshot each second. A client enters recovery rate when it havn't acknowlaged a snapshot over 1 second. This is to let the client to beable to recover if it has a slow connection.\n\n"
  },
  {
    "path": "src/engine/editor.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_EDITOR_H\n#define ENGINE_EDITOR_H\n#include \"kernel.h\"\n\nclass IEditor : public IInterface\n{\n\tMACRO_INTERFACE(\"editor\", 0)\npublic:\n\n\tvirtual ~IEditor() {}\n\tvirtual void Init() = 0;\n\tvirtual void UpdateAndRender() = 0;\n\tvirtual bool HasUnsavedData() = 0;\n};\n\nextern IEditor *CreateEditor();\n#endif\n"
  },
  {
    "path": "src/engine/engine.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_ENGINE_H\n#define ENGINE_ENGINE_H\n\n#include \"kernel.h\"\n#include <engine/shared/jobs.h>\n\nclass CHostLookup\n{\npublic:\n\tCJob m_Job;\n\tchar m_aHostname[128];\n\tint m_Nettype;\n\tNETADDR m_Addr;\n};\n\nclass IEngine : public IInterface\n{\n\tMACRO_INTERFACE(\"engine\", 0)\n\nprotected:\n\tclass CJobPool m_JobPool;\n\npublic:\n\tvirtual void Init() = 0;\n\tvirtual void InitLogfile() = 0;\n\tvirtual void HostLookup(CHostLookup *pLookup, const char *pHostname, int Nettype) = 0;\n\tvirtual void AddJob(CJob *pJob, JOBFUNC pfnFunc, void *pData) = 0;\n};\n\nextern IEngine *CreateEngine(const char *pAppname);\n\n#endif\n"
  },
  {
    "path": "src/engine/external/important.txt",
    "content": "The source code under this directory are external libraries\nwith their own licences. The source you find here is stripped\nof unnessesary information. Please visit their websites for\nmore information and official releases.\n\n"
  },
  {
    "path": "src/engine/external/json-parser/json.c",
    "content": "\n/* vim: set et ts=3 sw=3 ft=c:\n *\n * Copyright (C) 2012 James McLaughlin et al.  All rights reserved.\n * https://github.com/udp/json-parser\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *   notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *   notice, this list of conditions and the following disclaimer in the\n *   documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n */\n\n#include \"json.h\"\n\n#ifdef _MSC_VER\n   #ifndef _CRT_SECURE_NO_WARNINGS\n      #define _CRT_SECURE_NO_WARNINGS\n   #endif\n#endif\n\n#ifdef __cplusplus\n   const struct _json_value json_value_none; /* zero-d by ctor */\n#else\n   const struct _json_value json_value_none = { 0 };\n#endif\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\ntypedef unsigned short json_uchar;\n\nstatic unsigned char hex_value (json_char c)\n{\n   if (c >= 'A' && c <= 'F')\n      return (c - 'A') + 10;\n\n   if (c >= 'a' && c <= 'f')\n      return (c - 'a') + 10;\n\n   if (c >= '0' && c <= '9')\n      return c - '0';\n\n   return 0xFF;\n}\n\ntypedef struct\n{\n   json_settings settings;\n   int first_pass;\n\n   unsigned long used_memory;\n\n   unsigned int uint_max;\n   unsigned long ulong_max;\n\n} json_state;\n\nstatic void * json_alloc (json_state * state, unsigned long size, int zero)\n{\n   void * mem;\n\n   if ((state->ulong_max - state->used_memory) < size)\n      return 0;\n\n   if (state->settings.max_memory\n         && (state->used_memory += size) > state->settings.max_memory)\n   {\n      return 0;\n   }\n\n   if (! (mem = zero ? calloc (size, 1) : malloc (size)))\n      return 0;\n\n   return mem;\n}\n\nstatic int new_value\n   (json_state * state, json_value ** top, json_value ** root, json_value ** alloc, json_type type)\n{\n   json_value * value;\n   int values_size;\n\n   if (!state->first_pass)\n   {\n      value = *top = *alloc;\n      *alloc = (*alloc)->_reserved.next_alloc;\n\n      if (!*root)\n         *root = value;\n\n      switch (value->type)\n      {\n         case json_array:\n\n            if (! (value->u.array.values = (json_value **) json_alloc\n               (state, value->u.array.length * sizeof (json_value *), 0)) )\n            {\n               return 0;\n            }\n\n            value->u.array.length = 0;\n            break;\n\n         case json_object:\n\n            values_size = sizeof (*value->u.object.values) * value->u.object.length;\n\n            if (! ((*(void **) &value->u.object.values) = json_alloc\n                  (state, values_size + ((unsigned long) value->u.object.values), 0)) )\n            {\n               return 0;\n            }\n\n            value->_reserved.object_mem = (*(char **) &value->u.object.values) + values_size;\n\n            value->u.object.length = 0;\n            break;\n\n         case json_string:\n\n            if (! (value->u.string.ptr = (json_char *) json_alloc\n               (state, (value->u.string.length + 1) * sizeof (json_char), 0)) )\n            {\n               return 0;\n            }\n\n            value->u.string.length = 0;\n            break;\n\n         default:\n            break;\n      };\n\n      return 1;\n   }\n\n   value = (json_value *) json_alloc (state, sizeof (json_value), 1);\n\n   if (!value)\n      return 0;\n\n   if (!*root)\n      *root = value;\n\n   value->type = type;\n   value->parent = *top;\n\n   if (*alloc)\n      (*alloc)->_reserved.next_alloc = value;\n\n   *alloc = *top = value;\n\n   return 1;\n}\n\n#define e_off \\\n   ((int) (i - cur_line_begin))\n\n#define whitespace \\\n   case '\\n': ++ cur_line;  cur_line_begin = i; \\\n   case ' ': case '\\t': case '\\r'\n\n#define string_add(b)  \\\n   do { if (!state.first_pass) string [string_length] = b;  ++ string_length; } while (0);\n\nconst static long\n   flag_next = 1,  flag_reproc = 2,  flag_need_comma = 4,  flag_seek_value = 8, \n   flag_escaped = 16,  flag_string = 32,  flag_need_colon = 64,  flag_done = 128,\n   flag_num_negative = 256,  flag_num_zero = 512,  flag_num_e = 1024,  \n   flag_num_e_got_sign = 2048,  flag_num_e_negative = 4096;\n\njson_value * json_parse_ex (json_settings * settings, const json_char * json, char * error_buf)\n{\n   json_char error [128];\n   unsigned int cur_line;\n   const json_char * cur_line_begin, * i;\n   json_value * top, * root, * alloc = 0;\n   json_state state;\n   long flags;\n   long num_digits, num_fraction, num_e;\n\n   error[0] = '\\0';\n   num_digits = num_fraction = num_e = 0;\n\n   memset (&state, 0, sizeof (json_state));\n   memcpy (&state.settings, settings, sizeof (json_settings));\n\n   memset (&state.uint_max, 0xFF, sizeof (state.uint_max));\n   memset (&state.ulong_max, 0xFF, sizeof (state.ulong_max));\n\n   state.uint_max -= 8; /* limit of how much can be added before next check */\n   state.ulong_max -= 8;\n\n   for (state.first_pass = 1; state.first_pass >= 0; -- state.first_pass)\n   {\n      json_uchar uchar;\n      unsigned char uc_b1, uc_b2, uc_b3, uc_b4;\n      json_char * string;\n      unsigned int string_length;\n\n      top = root = 0;\n      flags = flag_seek_value;\n\t  string_length = 0;\n\t  string = 0;\n\n      cur_line = 1;\n      cur_line_begin = json;\n\n      for (i = json ;; ++ i)\n      {\n         json_char b = *i;\n\n         if (flags & flag_done)\n         {\n            if (!b)\n               break;\n\n            switch (b)\n            {\n               whitespace:\n                  continue;\n\n               default:\n                  sprintf (error, \"%d:%d: Trailing garbage: `%c`\", cur_line, e_off, b);\n                  goto e_failed;\n            };\n         }\n\n         if (flags & flag_string)\n         {\n            if (!b)\n            {  sprintf (error, \"Unexpected EOF in string (at %d:%d)\", cur_line, e_off);\n               goto e_failed;\n            }\n\n            if (string_length > state.uint_max)\n               goto e_overflow;\n\n            if (flags & flag_escaped)\n            {\n               flags &= ~ flag_escaped;\n\n               switch (b)\n               {\n                  case 'b':  string_add ('\\b');  break;\n                  case 'f':  string_add ('\\f');  break;\n                  case 'n':  string_add ('\\n');  break;\n                  case 'r':  string_add ('\\r');  break;\n                  case 't':  string_add ('\\t');  break;\n                  case 'u':\n\n                    if ((uc_b1 = hex_value (*++ i)) == 0xFF || (uc_b2 = hex_value (*++ i)) == 0xFF\n                          || (uc_b3 = hex_value (*++ i)) == 0xFF || (uc_b4 = hex_value (*++ i)) == 0xFF)\n                    {\n                        sprintf (error, \"Invalid character value `%c` (at %d:%d)\", b, cur_line, e_off);\n                        goto e_failed;\n                    }\n\n                    uc_b1 = uc_b1 * 16 + uc_b2;\n                    uc_b2 = uc_b3 * 16 + uc_b4;\n\n                    uchar = ((json_char) uc_b1) * 256 + uc_b2;\n\n                    if (sizeof (json_char) >= sizeof (json_uchar) || (uc_b1 == 0 && uc_b2 <= 0x7F))\n                    {\n                       string_add ((json_char) uchar);\n                       break;\n                    }\n\n                    if (uchar <= 0x7FF)\n                    {\n                        if (state.first_pass)\n                           string_length += 2;\n                        else\n                        {  string [string_length ++] = 0xC0 | ((uc_b2 & 0xC0) >> 6) | ((uc_b1 & 0x7) << 2);\n                           string [string_length ++] = 0x80 | (uc_b2 & 0x3F);\n                        }\n\n                        break;\n                    }\n\n                    if (state.first_pass)\n                       string_length += 3;\n                    else\n                    {  string [string_length ++] = 0xE0 | ((uc_b1 & 0xF0) >> 4);\n                       string [string_length ++] = 0x80 | ((uc_b1 & 0xF) << 2) | ((uc_b2 & 0xC0) >> 6);\n                       string [string_length ++] = 0x80 | (uc_b2 & 0x3F);\n                    }\n\n                    break;\n\n                  default:\n                     string_add (b);\n               };\n\n               continue;\n            }\n\n            if (b == '\\\\')\n            {\n               flags |= flag_escaped;\n               continue;\n            }\n\n            if (b == '\"')\n            {\n               if (!state.first_pass)\n                  string [string_length] = 0;\n\n               flags &= ~ flag_string;\n               string = 0;\n\n               switch (top->type)\n               {\n                  case json_string:\n\n                     top->u.string.length = string_length;\n                     flags |= flag_next;\n\n                     break;\n\n                  case json_object:\n\n                     if (state.first_pass)\n                        (*(json_char **) &top->u.object.values) += string_length + 1;\n                     else\n                     {  \n                        top->u.object.values [top->u.object.length].name\n                           = (json_char *) top->_reserved.object_mem;\n\n                        (*(json_char **) &top->_reserved.object_mem) += string_length + 1;\n                     }\n\n                     flags |= flag_seek_value | flag_need_colon;\n                     continue;\n\n                  default:\n                     break;\n               };\n            }\n            else\n            {\n               string_add (b);\n               continue;\n            }\n         }\n\n         if (flags & flag_seek_value)\n         {\n            switch (b)\n            {\n               whitespace:\n                  continue;\n\n               case ']':\n\n                  if (top->type == json_array)\n                     flags = (flags & ~ (flag_need_comma | flag_seek_value)) | flag_next;\n                  else if (!state.settings.settings & json_relaxed_commas)\n                  {  sprintf (error, \"%d:%d: Unexpected ]\", cur_line, e_off);\n                     goto e_failed;\n                  }\n\n                  break;\n\n               default:\n\n                  if (flags & flag_need_comma)\n                  {\n                     if (b == ',')\n                     {  flags &= ~ flag_need_comma;\n                        continue;\n                     }\n                     else\n                     {  sprintf (error, \"%d:%d: Expected , before %c\", cur_line, e_off, b);\n                        goto e_failed;\n                     }\n                  }\n\n                  if (flags & flag_need_colon)\n                  {\n                     if (b == ':')\n                     {  flags &= ~ flag_need_colon;\n                        continue;\n                     }\n                     else\n                     {  sprintf (error, \"%d:%d: Expected : before %c\", cur_line, e_off, b);\n                        goto e_failed;\n                     }\n                  }\n\n                  flags &= ~ flag_seek_value;\n\n                  switch (b)\n                  {\n                     case '{':\n\n                        if (!new_value (&state, &top, &root, &alloc, json_object))\n                           goto e_alloc_failure;\n\n                        continue;\n\n                     case '[':\n\n                        if (!new_value (&state, &top, &root, &alloc, json_array))\n                           goto e_alloc_failure;\n\n                        flags |= flag_seek_value;\n                        continue;\n\n                     case '\"':\n\n                        if (!new_value (&state, &top, &root, &alloc, json_string))\n                           goto e_alloc_failure;\n\n                        flags |= flag_string;\n\n                        string = top->u.string.ptr;\n                        string_length = 0;\n\n                        continue;\n\n                     case 't':\n\n                        if (*(++ i) != 'r' || *(++ i) != 'u' || *(++ i) != 'e')\n                           goto e_unknown_value;\n\n                        if (!new_value (&state, &top, &root, &alloc, json_boolean))\n                           goto e_alloc_failure;\n\n                        top->u.boolean = 1;\n\n                        flags |= flag_next;\n                        break;\n\n                     case 'f':\n\n                        if (*(++ i) != 'a' || *(++ i) != 'l' || *(++ i) != 's' || *(++ i) != 'e')\n                           goto e_unknown_value;\n\n                        if (!new_value (&state, &top, &root, &alloc, json_boolean))\n                           goto e_alloc_failure;\n\n                        flags |= flag_next;\n                        break;\n\n                     case 'n':\n\n                        if (*(++ i) != 'u' || *(++ i) != 'l' || *(++ i) != 'l')\n                           goto e_unknown_value;\n\n                        if (!new_value (&state, &top, &root, &alloc, json_null))\n                           goto e_alloc_failure;\n\n                        flags |= flag_next;\n                        break;\n\n                     default:\n\n                        if (isdigit (b) || b == '-')\n                        {\n                           if (!new_value (&state, &top, &root, &alloc, json_integer))\n                              goto e_alloc_failure;\n\n                           if (!state.first_pass)\n                           {\n                              while (isdigit (b) || b == '+' || b == '-'\n                                        || b == 'e' || b == 'E' || b == '.')\n                              {\n                                 b = *++ i;\n                              }\n\n                              flags |= flag_next | flag_reproc;\n                              break;\n                           }\n\n                           flags &= ~ (flag_num_negative | flag_num_e |\n                                        flag_num_e_got_sign | flag_num_e_negative |\n                                           flag_num_zero);\n\n                           num_digits = 0;\n                           num_fraction = 0;\n                           num_e = 0;\n\n                           if (b != '-')\n                           {\n                              flags |= flag_reproc;\n                              break;\n                           }\n\n                           flags |= flag_num_negative;\n                           continue;\n                        }\n                        else\n                        {  sprintf (error, \"%d:%d: Unexpected %c when seeking value\", cur_line, e_off, b);\n                           goto e_failed;\n                        }\n                  };\n            };\n         }\n         else\n         {\n            switch (top->type)\n            {\n            case json_object:\n               \n               switch (b)\n               {\n                  whitespace:\n                     continue;\n\n                  case '\"':\n\n                     if (flags & flag_need_comma && (!state.settings.settings & json_relaxed_commas))\n                     {\n                        sprintf (error, \"%d:%d: Expected , before \\\"\", cur_line, e_off);\n                        goto e_failed;\n                     }\n\n                     flags |= flag_string;\n\n                     string = (json_char *) top->_reserved.object_mem;\n                     string_length = 0;\n\n                     break;\n                  \n                  case '}':\n\n                     flags = (flags & ~ flag_need_comma) | flag_next;\n                     break;\n\n                  case ',':\n\n                     if (flags & flag_need_comma)\n                     {\n                        flags &= ~ flag_need_comma;\n                        break;\n                     }\n\n                  default:\n\n                     sprintf (error, \"%d:%d: Unexpected `%c` in object\", cur_line, e_off, b);\n                     goto e_failed;\n               };\n\n               break;\n\n            case json_integer:\n            case json_double:\n\n               if (isdigit (b))\n               {\n                  ++ num_digits;\n\n                  if (top->type == json_integer || flags & flag_num_e)\n                  {\n                     if (! (flags & flag_num_e))\n                     {\n                        if (flags & flag_num_zero)\n                        {  sprintf (error, \"%d:%d: Unexpected `0` before `%c`\", cur_line, e_off, b);\n                           goto e_failed;\n                        }\n\n                        if (num_digits == 1 && b == '0')\n                           flags |= flag_num_zero;\n                     }\n                     else\n                     {\n                        flags |= flag_num_e_got_sign;\n                        num_e = (num_e * 10) + (b - '0');\n                        continue;\n                     }\n\n                     top->u.integer = (top->u.integer * 10) + (b - '0');\n                     continue;\n                  }\n\n                  num_fraction = (num_fraction * 10) + (b - '0');\n                  continue;\n               }\n\n               if (b == '+' || b == '-')\n               {\n                  if ( (flags & flag_num_e) && !(flags & flag_num_e_got_sign))\n                  {\n                     flags |= flag_num_e_got_sign;\n\n                     if (b == '-')\n                        flags |= flag_num_e_negative;\n\n                     continue;\n                  }\n               }\n               else if (b == '.' && top->type == json_integer)\n               {\n                  if (!num_digits)\n                  {  sprintf (error, \"%d:%d: Expected digit before `.`\", cur_line, e_off);\n                     goto e_failed;\n                  }\n\n                  top->type = json_double;\n                  top->u.dbl = top->u.integer;\n\n                  num_digits = 0;\n                  continue;\n               }\n\n               if (! (flags & flag_num_e))\n               {\n                  if (top->type == json_double)\n                  {\n                     if (!num_digits)\n                     {  sprintf (error, \"%d:%d: Expected digit after `.`\", cur_line, e_off);\n                        goto e_failed;\n                     }\n\n                     top->u.dbl += ((double) num_fraction) / (pow (10, num_digits));\n                  }\n\n                  if (b == 'e' || b == 'E')\n                  {\n                     flags |= flag_num_e;\n\n                     if (top->type == json_integer)\n                     {\n                        top->type = json_double;\n                        top->u.dbl = top->u.integer;\n                     }\n\n                     num_digits = 0;\n                     flags &= ~ flag_num_zero;\n\n                     continue;\n                  }\n               }\n               else\n               {\n                  if (!num_digits)\n                  {  sprintf (error, \"%d:%d: Expected digit after `e`\", cur_line, e_off);\n                     goto e_failed;\n                  }\n\n                  top->u.dbl *= pow (10, flags & flag_num_e_negative ? - num_e : num_e);\n               }\n\n               if (flags & flag_num_negative)\n               {\n                  if (top->type == json_integer)\n                     top->u.integer = - top->u.integer;\n                  else\n                     top->u.dbl = - top->u.dbl;\n               }\n\n               flags |= flag_next | flag_reproc;\n               break;\n\n            default:\n               break;\n            };\n         }\n\n         if (flags & flag_reproc)\n         {\n            flags &= ~ flag_reproc;\n            -- i;\n         }\n\n         if (flags & flag_next)\n         {\n            flags = (flags & ~ flag_next) | flag_need_comma;\n\n            if (!top->parent)\n            {\n               /* root value done */\n\n               flags |= flag_done;\n               continue;\n            }\n\n            if (top->parent->type == json_array)\n               flags |= flag_seek_value;\n               \n            if (!state.first_pass)\n            {\n               json_value * parent = top->parent;\n\n               switch (parent->type)\n               {\n                  case json_object:\n\n                     parent->u.object.values\n                        [parent->u.object.length].value = top;\n\n                     break;\n\n                  case json_array:\n\n                     parent->u.array.values\n                           [parent->u.array.length] = top;\n\n                     break;\n\n                  default:\n                     break;\n               };\n            }\n\n            if ( (++ top->parent->u.array.length) > state.uint_max)\n               goto e_overflow;\n\n            top = top->parent;\n\n            continue;\n         }\n      }\n\n      alloc = root;\n   }\n\n   return root;\n\ne_unknown_value:\n\n   sprintf (error, \"%d:%d: Unknown value\", cur_line, e_off);\n   goto e_failed;\n\ne_alloc_failure:\n\n   strcpy (error, \"Memory allocation failure\");\n   goto e_failed;\n\ne_overflow:\n\n   sprintf (error, \"%d:%d: Too long (caught overflow)\", cur_line, e_off);\n   goto e_failed;\n\ne_failed:\n\n   if (error_buf)\n   {\n      if (*error)\n         strcpy (error_buf, error);\n      else\n         strcpy (error_buf, \"Unknown error\");\n   }\n\n   if (state.first_pass)\n      alloc = root;\n\n   while (alloc)\n   {\n      top = alloc->_reserved.next_alloc;\n      free (alloc);\n      alloc = top;\n   }\n\n   if (!state.first_pass)\n      json_value_free (root);\n\n   return 0;\n}\n\njson_value * json_parse (const json_char * json)\n{\n   json_settings settings;\n   memset (&settings, 0, sizeof (json_settings));\n\n   return json_parse_ex (&settings, json, 0);\n}\n\nvoid json_value_free (json_value * value)\n{\n   json_value * cur_value;\n\n   if (!value)\n      return;\n\n   value->parent = 0;\n\n   while (value)\n   {\n      switch (value->type)\n      {\n         case json_array:\n\n            if (!value->u.array.length)\n            {\n               free (value->u.array.values);\n               break;\n            }\n\n            value = value->u.array.values [-- value->u.array.length];\n            continue;\n\n         case json_object:\n\n            if (!value->u.object.length)\n            {\n               free (value->u.object.values);\n               break;\n            }\n\n            value = value->u.object.values [-- value->u.object.length].value;\n            continue;\n\n         case json_string:\n\n            free (value->u.string.ptr);\n            break;\n\n         default:\n            break;\n      };\n\n      cur_value = value;\n      value = value->parent;\n      free (cur_value);\n   }\n}\n\n"
  },
  {
    "path": "src/engine/external/json-parser/json.h",
    "content": "\n/* vim: set et ts=3 sw=3 ft=c:\n *\n * Copyright (C) 2012 James McLaughlin et al.  All rights reserved.\n * https://github.com/udp/json-parser\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *   notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *   notice, this list of conditions and the following disclaimer in the\n *   documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n */\n\n#ifndef _JSON_H\n#define _JSON_H\n\n#ifndef json_char\n   #define json_char char\n#endif\n\n#ifdef __cplusplus\n\n   #include <string.h>\n\n   extern \"C\"\n   {\n\n#endif\n\ntypedef struct\n{\n   unsigned long max_memory;\n   int settings;\n\n} json_settings;\n\n#define json_relaxed_commas 1\n\ntypedef enum\n{\n   json_none,\n   json_object,\n   json_array,\n   json_integer,\n   json_double,\n   json_string,\n   json_boolean,\n   json_null\n\n} json_type;\n\nextern const struct _json_value json_value_none;\n\ntypedef struct _json_value\n{\n   struct _json_value * parent;\n\n   json_type type;\n\n   union\n   {\n      int boolean;\n      long integer;\n      double dbl;\n\n      struct\n      {\n         unsigned int length;\n         json_char * ptr; /* null terminated */\n\n      } string;\n\n      struct\n      {\n         unsigned int length;\n\n         struct\n         {\n            json_char * name;\n            struct _json_value * value;\n\n         } * values;\n\n      } object;\n\n      struct\n      {\n         unsigned int length;\n         struct _json_value ** values;\n\n      } array;\n\n   } u;\n\n   union\n   {\n      struct _json_value * next_alloc;\n      void * object_mem;\n\n   } _reserved;\n\n\n   /* Some C++ operator sugar */\n\n   #ifdef __cplusplus\n\n      public:\n\n         inline _json_value ()\n         {  memset (this, 0, sizeof (_json_value));\n         }\n\n         inline const struct _json_value &operator [] (int index) const\n         {\n            if (type != json_array || index < 0\n                     || ((unsigned int) index) >= u.array.length)\n            {\n               return json_value_none;\n            }\n\n            return *u.array.values [index];\n         }\n\n         inline const struct _json_value &operator [] (const char * index) const\n         { \n            if (type != json_object)\n               return json_value_none;\n\n            for (unsigned int i = 0; i < u.object.length; ++ i)\n               if (!strcmp (u.object.values [i].name, index))\n                  return *u.object.values [i].value;\n\n            return json_value_none;\n         }\n\n         inline operator const char * () const\n         {  \n            switch (type)\n            {\n               case json_string:\n                  return u.string.ptr;\n\n               default:\n                  return \"\";\n            };\n         }\n\n         inline operator long () const\n         {  return u.integer;\n         }\n\n         inline operator bool () const\n         {  return u.boolean != 0;\n         }\n\n   #endif\n\n} json_value;\n\njson_value * json_parse\n   (const json_char * json);\n\njson_value * json_parse_ex\n   (json_settings * settings, const json_char * json, char * error);\n\nvoid json_value_free (json_value *);\n\n\n#ifdef __cplusplus\n   } /* extern \"C\" */\n#endif\n\n#endif\n\n\n"
  },
  {
    "path": "src/engine/external/pnglite/VERSION",
    "content": "0.1.17"
  },
  {
    "path": "src/engine/external/pnglite/pnglite.c",
    "content": "/*  pnglite.c - pnglite library\r\n    For conditions of distribution and use, see copyright notice in pnglite.h\r\n*/\r\n#define DO_CRC_CHECKS 1\r\n#define USE_ZLIB 1\r\n\r\n#if USE_ZLIB\r\n#include <zlib.h>\r\n#else\r\n#include \"zlite.h\"\r\n#endif\r\n\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <string.h>\r\n#include \"pnglite.h\"\r\n\r\n\r\n\r\nstatic png_alloc_t png_alloc;\r\nstatic png_free_t png_free;\r\n\r\nstatic size_t file_read(png_t* png, void* out, size_t size, size_t numel)\r\n{\r\n\tsize_t result;\r\n\tif(png->read_fun)\r\n\t{\r\n\t\tresult = png->read_fun(out, size, numel, png->user_pointer);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tif(!out)\r\n\t\t{\r\n\t\t\tresult = fseek(png->user_pointer, (long)(size*numel), SEEK_CUR);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tresult = fread(out, size, numel, png->user_pointer);\r\n\t\t}\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\nstatic size_t file_write(png_t* png, void* p, size_t size, size_t numel)\r\n{\r\n\tsize_t result;\r\n\r\n\tif(png->write_fun)\r\n\t{\r\n\t\tresult = png->write_fun(p, size, numel, png->user_pointer);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tresult = fwrite(p, size, numel, png->user_pointer);\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\nstatic int file_read_ul(png_t* png, unsigned *out)\r\n{\r\n\tunsigned char buf[4];\r\n\r\n\tif(file_read(png, buf, 1, 4) != 4)\r\n\t\treturn PNG_FILE_ERROR;\r\n\r\n\t*out = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];\r\n\r\n\treturn PNG_NO_ERROR;\r\n}\r\n\r\nstatic int file_write_ul(png_t* png, unsigned in)\r\n{\r\n\tunsigned char buf[4];\r\n\r\n\tbuf[0] = (in>>24) & 0xff;\r\n\tbuf[1] = (in>>16) & 0xff;\r\n\tbuf[2] = (in>>8) & 0xff;\r\n\tbuf[3] = (in) & 0xff;\r\n\r\n\tif(file_write(png, buf, 1, 4) != 4)\r\n\t\treturn PNG_FILE_ERROR;\r\n\r\n\treturn PNG_NO_ERROR;\r\n}\r\n\t\r\n\r\nstatic unsigned get_ul(unsigned char* buf)\r\n{\r\n\tunsigned result;\r\n\tunsigned char foo[4];\r\n\r\n\tmemcpy(foo, buf, 4);\r\n\r\n\tresult = (foo[0]<<24) | (foo[1]<<16) | (foo[2]<<8) | foo[3];\r\n\r\n\treturn result;\r\n}\r\n\r\nstatic unsigned set_ul(unsigned char* buf, unsigned in)\r\n{\r\n\tbuf[0] = (in>>24) & 0xff;\r\n\tbuf[1] = (in>>16) & 0xff;\r\n\tbuf[2] = (in>>8) & 0xff;\r\n\tbuf[3] = (in) & 0xff;\r\n\r\n\treturn PNG_NO_ERROR;\r\n}\r\n\r\nint png_init(png_alloc_t pngalloc, png_free_t pngfree)\r\n{\r\n\tif(pngalloc)\r\n\t\tpng_alloc = pngalloc;\r\n\telse\r\n\t\tpng_alloc = (png_alloc_t)&malloc;\r\n\r\n\tif(pngfree)\r\n\t\tpng_free = pngfree;\r\n\telse\r\n\t\tpng_free = &free;\r\n\r\n\treturn PNG_NO_ERROR;\r\n}\r\n\r\nstatic int png_get_bpp(png_t* png)\r\n{\r\n\tint bpp;\r\n\r\n\tswitch(png->color_type)\r\n\t{\r\n\tcase PNG_GREYSCALE:\r\n\t\tbpp = 1; break;\r\n\tcase PNG_TRUECOLOR:\r\n\t\tbpp = 3; break;\r\n\tcase PNG_INDEXED:\r\n\t\tbpp = 1; break;\r\n\tcase PNG_GREYSCALE_ALPHA:\r\n\t\tbpp = 2; break;\r\n\tcase PNG_TRUECOLOR_ALPHA:\r\n\t\tbpp = 4; break;\r\n\tdefault:\r\n\t\treturn PNG_FILE_ERROR;\r\n\t}\r\n\r\n\tbpp *= png->depth/8;\r\n\r\n\treturn bpp;\r\n}\r\n\r\nstatic int png_read_ihdr(png_t* png)\r\n{\r\n\tint result;\r\n\tunsigned length;\r\n#if DO_CRC_CHECKS\r\n\tunsigned orig_crc;\r\n\tunsigned calc_crc;\r\n#endif\r\n\tunsigned char ihdr[13+4];\t\t /* length should be 13, make room for type (IHDR) */\r\n\r\n\tfile_read_ul(png, &length);\r\n\r\n\tif(length != 13)\r\n\t{\r\n\t\tprintf(\"%d\\n\", length);\r\n\t\treturn PNG_CRC_ERROR;\r\n\t}\r\n\r\n\tif(file_read(png, ihdr, 1, 13+4) != 13+4)\r\n\t\treturn PNG_EOF_ERROR;\r\n#if DO_CRC_CHECKS\r\n\tresult = file_read_ul(png, &orig_crc);\r\n\tif(result != PNG_NO_ERROR)\r\n\t\treturn result;\r\n\r\n\tcalc_crc = crc32(0L, 0, 0);\r\n\tcalc_crc = crc32(calc_crc, ihdr, 13+4);\r\n\r\n\tif(orig_crc != calc_crc)\r\n\t\treturn PNG_CRC_ERROR;\r\n#else\r\n\tresult = file_read_ul(png);\r\n\tif(result != PNG_NO_ERROR)\r\n\t\treturn result; \r\n#endif\r\n\r\n\tpng->width = get_ul(ihdr+4);\r\n\tpng->height = get_ul(ihdr+8);\r\n\tpng->depth = ihdr[12];\r\n\tpng->color_type = ihdr[13];\r\n\tpng->compression_method = ihdr[14];\r\n\tpng->filter_method = ihdr[15];\r\n\tpng->interlace_method = ihdr[16];\r\n\r\n\tif(png->color_type == PNG_INDEXED)\r\n\t\treturn PNG_NOT_SUPPORTED;\r\n\r\n\tif(png->depth != 8 && png->depth != 16)\r\n\t\treturn PNG_NOT_SUPPORTED;\r\n\r\n\tif(png->interlace_method)\r\n\t\treturn PNG_NOT_SUPPORTED;\r\n\t\r\n\treturn PNG_NO_ERROR;\r\n}\r\n\r\nstatic int png_write_ihdr(png_t* png)\r\n{\r\n\tunsigned char ihdr[13+4];\r\n\tunsigned char *p = ihdr;\r\n\tunsigned crc;\r\n\t\r\n\tfile_write(png, \"\\x89\\x50\\x4E\\x47\\x0D\\x0A\\x1A\\x0A\", 1, 8);\r\n\r\n\tfile_write_ul(png, 13);\r\n    \r\n\t*p = 'I';\t\t\tp++;\r\n\t*p = 'H';\t\t\tp++;\r\n\t*p = 'D';\t\t\tp++;\r\n\t*p = 'R';\t\t\tp++;\r\n\tset_ul(p, png->width);\tp+=4;\r\n\tset_ul(p, png->height);\tp+=4;\r\n\t*p = png->depth;\t\t\tp++;\r\n\t*p = png->color_type;\tp++;\r\n\t*p = 0;\t\t\t\tp++;\r\n\t*p = 0;\t\t\t\tp++;\r\n\t*p = 0;\t\t\t\tp++;\r\n\r\n\tfile_write(png, ihdr, 1, 13+4);\r\n\r\n\tcrc = crc32(0L, 0, 0);\r\n\tcrc = crc32(crc, ihdr, 13+4);\r\n\r\n\tfile_write_ul(png, crc);\r\n\r\n\treturn PNG_NO_ERROR;\r\n}\r\n\r\nvoid png_print_info(png_t* png)\r\n{\r\n\tprintf(\"PNG INFO:\\n\");\r\n\tprintf(\"\\twidth:\\t\\t%d\\n\", png->width);\r\n\tprintf(\"\\theight:\\t\\t%d\\n\", png->height);\r\n\tprintf(\"\\tdepth:\\t\\t%d\\n\", png->depth);\r\n\tprintf(\"\\tcolor:\\t\\t\");\r\n\r\n\tswitch(png->color_type)\r\n\t{\r\n\tcase PNG_GREYSCALE:\t\t\tprintf(\"greyscale\\n\"); break;\r\n\tcase PNG_TRUECOLOR:\t\t\tprintf(\"truecolor\\n\"); break;\r\n\tcase PNG_INDEXED:\t\t\tprintf(\"palette\\n\"); break;\r\n\tcase PNG_GREYSCALE_ALPHA:\tprintf(\"greyscale with alpha\\n\"); break;\r\n\tcase PNG_TRUECOLOR_ALPHA:\tprintf(\"truecolor with alpha\\n\"); break;\r\n\tdefault:\t\t\t\t\tprintf(\"unknown, this is not good\\n\"); break;\r\n\t}\r\n\r\n\tprintf(\"\\tcompression:\\t%s\\n\",\tpng->compression_method?\"unknown, this is not good\":\"inflate/deflate\");\r\n\tprintf(\"\\tfilter:\\t\\t%s\\n\",\t\tpng->filter_method?\"unknown, this is not good\":\"adaptive\");\r\n\tprintf(\"\\tinterlace:\\t%s\\n\",\tpng->interlace_method?\"interlace\":\"no interlace\");\r\n}\r\n\r\nint png_open_read(png_t* png, png_read_callback_t read_fun, void* user_pointer)\r\n{\r\n\tchar header[8];\r\n\tint result;\r\n\r\n\tpng->read_fun = read_fun;\r\n\tpng->write_fun = 0;\r\n\tpng->user_pointer = user_pointer;\r\n\r\n\tif(!read_fun && !user_pointer)\r\n\t\treturn PNG_WRONG_ARGUMENTS;\r\n\r\n\tif(file_read(png, header, 1, 8) != 8)\r\n\t\treturn PNG_EOF_ERROR;\r\n\r\n\tif(memcmp(header, \"\\x89\\x50\\x4E\\x47\\x0D\\x0A\\x1A\\x0A\", 8) != 0)\r\n\t\treturn PNG_HEADER_ERROR;\r\n\r\n\tresult = png_read_ihdr(png);\r\n\r\n\tpng->bpp = (unsigned char)png_get_bpp(png);\r\n\tif(png->bpp < 0)\r\n\t\tresult = png->bpp;\r\n\r\n\treturn result;\r\n}\r\n\r\nint png_open_write(png_t* png, png_write_callback_t write_fun, void* user_pointer)\r\n{\r\n\tpng->write_fun = write_fun;\r\n\tpng->read_fun = 0;\r\n\tpng->user_pointer = user_pointer;\r\n\r\n\tif(!write_fun && !user_pointer)\r\n\t\treturn PNG_WRONG_ARGUMENTS;\r\n\r\n\treturn PNG_NO_ERROR;\r\n}\r\n\r\nint png_open(png_t* png, png_read_callback_t read_fun, void* user_pointer)\r\n{\r\n\treturn png_open_read(png, read_fun, user_pointer);\r\n}\r\n\r\nint png_open_file_read(png_t *png, const char* filename)\r\n{\r\n\tFILE* fp = fopen(filename, \"rb\");\r\n\r\n\tif(!fp)\r\n\t\treturn PNG_FILE_ERROR;\r\n\r\n\treturn png_open_read(png, 0, fp);\r\n}\r\n\r\nint png_open_file_write(png_t *png, const char* filename)\r\n{\r\n\tFILE* fp = fopen(filename, \"wb\");\r\n\r\n\tif(!fp)\r\n\t\treturn PNG_FILE_ERROR;\r\n\r\n\treturn png_open_write(png, 0, fp);\r\n}\r\n\r\nint png_open_file(png_t *png, const char* filename)\r\n{\r\n\treturn png_open_file_read(png, filename);\r\n}\r\n\r\nint png_close_file(png_t* png)\r\n{\r\n\tfclose(png->user_pointer);\r\n\r\n\treturn PNG_NO_ERROR;\r\n}\r\n\r\nstatic int png_init_deflate(png_t* png, unsigned char* data, int datalen)\r\n{\r\n\tz_stream *stream;\r\n\tpng->zs = png_alloc(sizeof(z_stream));\r\n\r\n\tstream = png->zs;\r\n\r\n\tif(!stream)\r\n\t\treturn PNG_MEMORY_ERROR;\r\n\r\n\tmemset(stream, 0, sizeof(z_stream));\r\n\r\n\tif(deflateInit(stream, Z_DEFAULT_COMPRESSION) != Z_OK)\r\n\t\treturn PNG_ZLIB_ERROR;\r\n\r\n\tstream->next_in = data;\r\n\tstream->avail_in = datalen;\r\n\r\n\treturn PNG_NO_ERROR;\r\n}\r\n\r\nstatic int png_init_inflate(png_t* png)\r\n{\r\n#if USE_ZLIB\r\n\tz_stream *stream;\r\n\tpng->zs = png_alloc(sizeof(z_stream));\r\n#else\r\n\tzl_stream *stream;\r\n\tpng->zs = png_alloc(sizeof(zl_stream));\r\n#endif\r\n\r\n\tstream = png->zs;\r\n\r\n\tif(!stream)\r\n\t\treturn PNG_MEMORY_ERROR;\r\n\r\n\t\r\n\r\n#if USE_ZLIB\r\n\tmemset(stream, 0, sizeof(z_stream));\r\n\tif(inflateInit(stream) != Z_OK)\r\n\t\treturn PNG_ZLIB_ERROR;\r\n#else\r\n\tmemset(stream, 0, sizeof(zl_stream));\r\n\tif(z_inflateInit(stream) != Z_OK)\r\n\t\treturn PNG_ZLIB_ERROR;\r\n#endif\r\n\r\n\tstream->next_out = png->png_data;\r\n\tstream->avail_out = png->png_datalen;\r\n\r\n\treturn PNG_NO_ERROR;\r\n}\r\n\r\nstatic int png_end_deflate(png_t* png)\r\n{\r\n\tz_stream *stream = png->zs;\r\n\r\n\tif(!stream)\r\n\t\treturn PNG_MEMORY_ERROR;\r\n\r\n\tdeflateEnd(stream);\r\n\r\n\tpng_free(png->zs);\r\n\tpng->zs = 0;\r\n\r\n\treturn PNG_NO_ERROR;\r\n}\r\n\r\nstatic int png_end_inflate(png_t* png)\r\n{\r\n#if USE_ZLIB\r\n\tz_stream *stream = png->zs;\r\n#else\r\n\tzl_stream *stream = png->zs;\r\n#endif\r\n\r\n\tif(!stream)\r\n\t\treturn PNG_MEMORY_ERROR;\r\n\r\n#if USE_ZLIB\r\n\tif(inflateEnd(stream) != Z_OK)\r\n#else\r\n\tif(z_inflateEnd(stream) != Z_OK)\r\n#endif\r\n\t{\r\n\t\tprintf(\"ZLIB says: %s\\n\", stream->msg);\r\n\t\treturn PNG_ZLIB_ERROR;\r\n\t}\r\n\r\n\tpng_free(png->zs);\r\n\tpng->zs = 0;\r\n\r\n\treturn PNG_NO_ERROR;\r\n}\r\n\r\nstatic int png_inflate(png_t* png, char* data, int len)\r\n{\r\n\tint result;\r\n#if USE_ZLIB\r\n\tz_stream *stream = png->zs;\r\n#else\r\n\tzl_stream *stream = png->zs;\r\n#endif\r\n\r\n\tif(!stream)\r\n\t\treturn PNG_MEMORY_ERROR;\r\n\r\n\tstream->next_in = (unsigned char*)data;\r\n\tstream->avail_in = len;\r\n\t\r\n#if USE_ZLIB\r\n\tresult = inflate(stream, Z_SYNC_FLUSH);\r\n#else\r\n\tresult = z_inflate(stream);\r\n#endif\r\n\r\n\tif(result != Z_STREAM_END && result != Z_OK)\r\n\t{\r\n\t\tprintf(\"%s\\n\", stream->msg);\r\n\t\treturn PNG_ZLIB_ERROR;\r\n\t}\r\n\r\n\tif(stream->avail_in != 0)\r\n\t\treturn PNG_ZLIB_ERROR;\r\n\r\n\treturn PNG_NO_ERROR;\r\n}\r\n\r\nstatic int png_deflate(png_t* png, char* outdata, int outlen, int *outwritten)\r\n{\r\n\tint result;\r\n\r\n\tz_stream *stream = png->zs;\r\n\r\n\r\n\tif(!stream)\r\n\t\treturn PNG_MEMORY_ERROR;\r\n\r\n\tstream->next_out = (unsigned char*)outdata;\r\n\tstream->avail_out = outlen;\r\n\r\n\tresult = deflate(stream, Z_SYNC_FLUSH);\r\n\r\n\t*outwritten = outlen - stream->avail_out;\r\n\r\n\tif(result != Z_STREAM_END && result != Z_OK)\r\n\t{\r\n\t\tprintf(\"%s\\n\", stream->msg);\r\n\t\treturn PNG_ZLIB_ERROR;\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\nstatic int png_write_idats(png_t* png, unsigned char* data)\r\n{\r\n\tunsigned char *chunk;\r\n\tunsigned long written;\r\n\tunsigned long crc;\r\n\tunsigned size = png->width * png->height * png->bpp + png->height;\r\n\t\r\n\t(void)png_init_deflate;\r\n\t(void)png_end_deflate;\r\n\t(void)png_deflate;\r\n\r\n\tchunk = png_alloc(size+8);\r\n\tmemcpy(chunk, \"IDAT\", 4);\r\n\t\r\n\twritten = size;\r\n\tcompress(chunk+4, &written, data, size);\r\n\t\r\n\tcrc = crc32(0L, Z_NULL, 0);\r\n\tcrc = crc32(crc, chunk, written+4);\r\n\tset_ul(chunk+written+4, crc);\r\n\tfile_write_ul(png, written);\r\n\tfile_write(png, chunk, 1, written+8);\r\n\tpng_free(chunk);\r\n\r\n\tfile_write_ul(png, 0);\r\n\tfile_write(png, \"IEND\", 1, 4);\r\n\tcrc = crc32(0L, (const unsigned char *)\"IEND\", 4);\r\n\tfile_write_ul(png, crc);\r\n\t\r\n\treturn PNG_NO_ERROR;\r\n}\r\n\r\nstatic int png_read_idat(png_t* png, unsigned firstlen) \r\n{\r\n\tunsigned type = 0;\r\n\tchar *chunk;\r\n\tint result;\r\n\tunsigned length = firstlen;\r\n\tunsigned old_len = length;\r\n\r\n#if DO_CRC_CHECKS\r\n\tunsigned orig_crc;\r\n\tunsigned calc_crc;\r\n#endif\r\n\r\n\tchunk = png_alloc(firstlen); \r\n\tif(!chunk)\r\n\t\treturn PNG_MEMORY_ERROR;\r\n\r\n\tresult = png_init_inflate(png);\r\n\r\n\tif(result != PNG_NO_ERROR)\r\n\t{\r\n\t\tpng_end_inflate(png);\r\n\t\tpng_free(chunk); \r\n\t\treturn result;\r\n\t}\r\n\r\n\tdo\r\n\t{\r\n\t\tif(file_read(png, chunk, 1, length) != length)\r\n\t\t{\r\n\t\t\tpng_end_inflate(png);\r\n\t\t\tpng_free(chunk); \r\n\t\t\treturn PNG_FILE_ERROR;\r\n\t\t}\r\n\r\n#if DO_CRC_CHECKS\r\n\t\tcalc_crc = crc32(0L, Z_NULL, 0);\r\n\t\tcalc_crc = crc32(calc_crc, (unsigned char*)\"IDAT\", 4);\r\n\t\tcalc_crc = crc32(calc_crc, (unsigned char*)chunk, length);\r\n\r\n\t\tfile_read_ul(png, &orig_crc);\r\n\r\n\t\tif(orig_crc != calc_crc)\r\n\t\t{\r\n\t\t\tresult = PNG_CRC_ERROR;\r\n\t\t\tbreak;\r\n\t\t}\r\n#else\r\n\t\tfile_read_ul(png);\r\n#endif\r\n\r\n\t\tresult = png_inflate(png, chunk, length);\r\n\r\n\t\tif(result != PNG_NO_ERROR) break;\r\n\t\t\r\n\t\tfile_read_ul(png, &length);\r\n\r\n\t\tif(length > old_len)\r\n\t\t{\r\n\t\t\tpng_free(chunk); \r\n\t\t\tchunk = png_alloc(length);\r\n\t\t\tif(!chunk)\r\n\t\t\t{\r\n\t\t\t\tpng_end_inflate(png);\r\n\t\t\t\treturn PNG_MEMORY_ERROR;\r\n\t\t\t}\r\n\t\t\told_len = length;\r\n\t\t}\r\n\r\n\t\tif(file_read(png, &type, 1, 4) != 4)\r\n\t\t{\r\n\t\t\tresult = PNG_FILE_ERROR;\r\n\t\t\tbreak;\r\n\t\t}\r\n\r\n\t}while(type == *(unsigned int*)\"IDAT\");\r\n\r\n\tif(type == *(unsigned int*)\"IEND\")\r\n\t\tresult = PNG_DONE;\r\n\r\n\tpng_free(chunk);\r\n\tpng_end_inflate(png);\r\n\r\n\treturn result;\r\n}\r\n\r\nstatic int png_process_chunk(png_t* png)\r\n{\r\n\tint result = PNG_NO_ERROR;\r\n\tunsigned type;\r\n\tunsigned length;\r\n\r\n\tfile_read_ul(png, &length);\r\n\r\n\tif(file_read(png, &type, 1, 4) != 4)\r\n\t\treturn PNG_FILE_ERROR;\r\n\r\n\tif(type == *(unsigned int*)\"IDAT\")\t/* if we found an idat, all other idats should be followed with no other chunks in between */\r\n\t{\r\n\t\tif(!png->png_data)\r\n\t\t{\r\n\t\t\tpng->png_datalen = png->width * png->height * png->bpp + png->height;\r\n\t\t\tpng->png_data = png_alloc(png->png_datalen);\r\n\t\t}\r\n\t\telse\r\n\t\t\treturn PNG_FILE_ERROR;\r\n\t\t\r\n\t\tif(!png->png_data)\r\n\t\t\treturn PNG_MEMORY_ERROR;\r\n\r\n\t\treturn png_read_idat(png, length);\r\n\t}\r\n\telse if(type == *(unsigned int*)\"IEND\")\r\n\t{\r\n\t\treturn PNG_DONE;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tfile_read(png, 0, 1, length + 4);\t\t/* unknown chunk */\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\nstatic void png_filter_sub(int stride, unsigned char* in, unsigned char* out, int len)\r\n{\r\n\tint i;\r\n\tunsigned char a = 0;\r\n\r\n\tfor(i = 0; i < len; i++)\r\n\t{\r\n\t\tif(i >= stride)\r\n\t\t\ta = out[i - stride];\r\n\t\t\r\n\t\tout[i] = in[i] + a;\r\n\t}\r\n}\r\n\r\nstatic void png_filter_up(int stride, unsigned char* in, unsigned char* out, unsigned char* prev_line, int len)\r\n{\r\n\tint i;\r\n\r\n\tif(prev_line) \r\n    { \r\n        for(i = 0; i < len; i++) \r\n            out[i] = in[i] + prev_line[i]; \r\n    } \r\n    else \r\n        memcpy(out, in, len);\r\n}\r\n\r\nstatic void png_filter_average(int stride, unsigned char* in, unsigned char* out, unsigned char* prev_line, int len)\r\n{\r\n\tint i;\r\n\tunsigned char a = 0;\r\n\tunsigned char b = 0;\r\n\tunsigned int sum = 0;\r\n\r\n\tfor(i = 0; i < len; i++)\r\n\t{\r\n\t\tif(prev_line)\r\n\t\t\tb = prev_line[i];\r\n\r\n\t\tif(i >= stride)\r\n\t\t\ta = out[i - stride];\r\n\r\n\t\tsum = a;\r\n\t\tsum += b;\r\n\r\n\t\tout[i] = (char)(in[i] + sum/2);\r\n\t}\r\n}\r\n\r\nstatic unsigned char png_paeth(unsigned char a, unsigned char b, unsigned char c)\r\n{\r\n\tint p = (int)a + b - c;\r\n\tint pa = abs(p - a);\r\n\tint pb = abs(p - b);\r\n\tint pc = abs(p - c);\r\n\r\n\tint pr;\r\n\r\n\tif(pa <= pb && pa <= pc)\r\n\t\tpr = a;\r\n\telse if(pb <= pc)\r\n\t\tpr = b;\r\n\telse\r\n\t\tpr = c;\r\n\r\n\treturn (char)pr;\r\n}\r\n\r\nstatic void png_filter_paeth(int stride, unsigned char* in, unsigned char* out, unsigned char* prev_line, int len)\r\n{\r\n\tint i;\r\n\tunsigned char a;\r\n\tunsigned char b;\r\n\tunsigned char c;\r\n\r\n\tfor(i = 0; i < len; i++)\r\n\t{\r\n\t\tif(prev_line && i >= stride)\r\n\t\t{\r\n\t\t\ta = out[i - stride];\r\n\t\t\tb = prev_line[i];\r\n\t\t\tc = prev_line[i - stride];\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tif(prev_line)\r\n\t\t\t\tb = prev_line[i];\r\n\t\t\telse\r\n\t\t\t\tb = 0;\r\n\t\r\n\t\t\tif(i >= stride)\r\n\t\t\t\ta = out[i - stride];\r\n\t\t\telse\r\n\t\t\t\ta = 0;\r\n\r\n\t\t\tc = 0;\r\n\t\t}\r\n\r\n\t\tout[i] = in[i] + png_paeth(a, b, c);\r\n\t}\r\n}\r\n\r\nstatic int png_filter(png_t* png, unsigned char* data)\r\n{\r\n\r\n\r\n\treturn PNG_NO_ERROR;\r\n}\r\n\r\nstatic int png_unfilter(png_t* png, unsigned char* data)\r\n{\r\n\tunsigned i;\r\n\tunsigned pos = 0;\r\n\tunsigned outpos = 0;\r\n\tunsigned char *filtered = png->png_data;\r\n\r\n\tint stride = png->bpp;\r\n\r\n\twhile(pos < png->png_datalen)\r\n\t{\r\n\t\tunsigned char filter = filtered[pos];\r\n\r\n\t\tpos++;\r\n\r\n\t\tif(png->depth == 16)\r\n\t\t{\r\n\t\t\tfor(i = 0; i < png->width * stride; i+=2)\r\n\t\t\t{\r\n\t\t\t\t*(short*)(filtered+pos+i) = (filtered[pos+i] << 8) | filtered[pos+i+1];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tswitch(filter)\r\n\t\t{\r\n\t\tcase 0: /* none */\r\n\t\t\tmemcpy(data+outpos, filtered+pos, png->width * stride);\r\n\t\t\tbreak;\r\n\t\tcase 1: /* sub */\r\n\t\t\tpng_filter_sub(stride, filtered+pos, data+outpos, png->width * stride);\r\n\t\t\tbreak;\r\n\t\tcase 2: /* up */\r\n\t\t\tif(outpos)\r\n\t\t\t\tpng_filter_up(stride, filtered+pos, data+outpos, data + outpos - (png->width*stride), png->width*stride);\r\n\t\t\telse\r\n\t\t\t\tpng_filter_up(stride, filtered+pos, data+outpos, 0, png->width*stride);\r\n\t\t\tbreak;\r\n\t\tcase 3: /* average */\r\n\t\t\tif(outpos)\r\n\t\t\t\tpng_filter_average(stride, filtered+pos, data+outpos, data + outpos - (png->width*stride), png->width*stride);\r\n\t\t\telse\r\n\t\t\t\tpng_filter_average(stride, filtered+pos, data+outpos, 0, png->width*stride);\r\n\t\t\tbreak;\r\n\t\tcase 4: /* paeth */\r\n\t\t\tif(outpos)\r\n\t\t\t\tpng_filter_paeth(stride, filtered+pos, data+outpos, data + outpos - (png->width*stride), png->width*stride);\r\n\t\t\telse\r\n\t\t\t\tpng_filter_paeth(stride, filtered+pos, data+outpos, 0, png->width*stride);\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\treturn PNG_UNKNOWN_FILTER;\r\n\t\t}\r\n\r\n\t\toutpos += png->width * stride;\r\n\t\tpos += png->width * stride;\r\n\t}\r\n\r\n\treturn PNG_NO_ERROR;\r\n}\r\n\r\nint png_get_data(png_t* png, unsigned char* data)\r\n{\r\n\tint result = PNG_NO_ERROR;\r\n\tpng->png_data = 0;\r\n\tpng->zs = 0;\r\n\r\n\twhile(result == PNG_NO_ERROR)\r\n\t{\r\n\t\tresult = png_process_chunk(png);\r\n\t}\r\n\r\n\tif(result != PNG_DONE)\r\n\t{\r\n\t\tif(!png->png_data)\r\n\t\t{\r\n\t\t\tpng_free(png->png_data);\r\n\t\t\tpng->png_data = 0;\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult = png_unfilter(png, data);\r\n\r\n\tpng_free(png->png_data); \r\n\tpng->png_data = 0;\r\n\r\n\treturn result;\r\n}\r\n\r\nint png_set_data(png_t* png, unsigned width, unsigned height, char depth, int color, unsigned char* data)\r\n{\r\n\tint i;\r\n\tunsigned char *filtered;\r\n\tpng->width = width;\r\n\tpng->height = height;\r\n\tpng->depth = depth;\r\n\tpng->color_type = color;\r\n\tpng->bpp = png_get_bpp(png);\r\n\r\n\tfiltered = png_alloc(width * height * png->bpp + height);\r\n\r\n\tfor(i = 0; i < png->height; i++)\r\n\t{\r\n\t\tfiltered[i*png->width*png->bpp+i] = 0;\r\n\t\tmemcpy(&filtered[i*png->width*png->bpp+i+1], data + i * png->width*png->bpp, png->width*png->bpp);\r\n\t}\r\n\r\n\tpng_filter(png, filtered);\r\n\tpng_write_ihdr(png);\r\n\tpng_write_idats(png, filtered);\r\n\t\r\n\tpng_free(filtered);\r\n\treturn PNG_NO_ERROR;\r\n}\r\n\r\n\r\nchar* png_error_string(int error)\r\n{\r\n\tswitch(error)\r\n\t{\r\n\tcase PNG_NO_ERROR:\r\n\t\treturn \"No error\";\r\n\tcase PNG_FILE_ERROR:\r\n\t\treturn \"Unknown file error.\";\r\n\tcase PNG_HEADER_ERROR:\r\n\t\treturn \"No PNG header found. Are you sure this is a PNG?\";\r\n\tcase PNG_IO_ERROR:\r\n\t\treturn \"Failure while reading file.\";\r\n\tcase PNG_EOF_ERROR:\r\n\t\treturn \"Reached end of file.\";\r\n\tcase PNG_CRC_ERROR:\r\n\t\treturn \"CRC or chunk length error.\";\r\n\tcase PNG_MEMORY_ERROR:\r\n\t\treturn \"Could not allocate memory.\";\r\n\tcase PNG_ZLIB_ERROR:\r\n\t\treturn \"zlib reported an error.\";\r\n\tcase PNG_UNKNOWN_FILTER:\r\n\t\treturn \"Unknown filter method used in scanline.\";\r\n\tcase PNG_DONE:\r\n\t\treturn \"PNG done\";\r\n\tcase PNG_NOT_SUPPORTED:\r\n\t\treturn \"The PNG is unsupported by pnglite, too bad for you!\";\r\n\tcase PNG_WRONG_ARGUMENTS:\r\n\t\treturn \"Wrong combination of arguments passed to png_open. You must use either a read_function or supply a file pointer to use.\";\r\n\tdefault:\r\n\t\treturn \"Unknown error.\";\r\n\t};\r\n}\r\n"
  },
  {
    "path": "src/engine/external/pnglite/pnglite.h",
    "content": "/*  pnglite.h - Interface for pnglite library\r\n\tCopyright (c) 2007 Daniel Karling\r\n\r\n\tThis software is provided 'as-is', without any express or implied\r\n\twarranty. In no event will the authors be held liable for any damages\r\n\tarising from the use of this software.\r\n\r\n\tPermission is granted to anyone to use this software for any purpose,\r\n\tincluding commercial applications, and to alter it and redistribute it\r\n\tfreely, subject to the following restrictions:\r\n\r\n\t1. The origin of this software must not be misrepresented; you must not\r\n\t   claim that you wrote the original software. If you use this software\r\n\t   in a product, an acknowledgment in the product documentation would be\r\n\t   appreciated but is not required.  \r\n\r\n\t2. Altered source versions must be plainly marked as such, and must not be\r\n\t   misrepresented as being the original software.\r\n\r\n\t3. This notice may not be removed or altered from any source\r\n\t   distribution.\r\n\r\n\tDaniel Karling\r\n\tdaniel.karling@gmail.com\r\n */\r\n\r\n/*\r\n\tNOTICE:\r\n\tThis is a modified version which contains changes that address\r\n\tcompiler warnings and increase stability.\r\n*/\r\n\r\n#ifndef _PNGLITE_H_\r\n#define _PNGLITE_H_\r\n\r\n#ifdef __cplusplus\r\nextern \"C\"{\r\n#endif\r\n\r\n/*\r\n\tEnumerations for pnglite.\r\n\tNegative numbers are error codes and 0 and up are okay responses.\r\n*/\r\n\r\nenum\r\n{\r\n\tPNG_DONE\t\t\t\t= 1,\r\n\tPNG_NO_ERROR\t\t\t= 0,\r\n\tPNG_FILE_ERROR\t\t\t= -1,\r\n\tPNG_HEADER_ERROR\t\t= -2,\r\n\tPNG_IO_ERROR\t\t\t= -3,\r\n\tPNG_EOF_ERROR\t\t\t= -4,\r\n\tPNG_CRC_ERROR\t\t\t= -5,\r\n\tPNG_MEMORY_ERROR\t\t= -6,\r\n\tPNG_ZLIB_ERROR\t\t\t= -7,\r\n\tPNG_UNKNOWN_FILTER\t\t= -8,\r\n\tPNG_NOT_SUPPORTED\t\t= -9,\r\n\tPNG_WRONG_ARGUMENTS\t\t= -10\r\n};\r\n\r\n/*\r\n\tThe five different kinds of color storage in PNG files.\r\n*/\r\n\r\nenum\r\n{\r\n\tPNG_GREYSCALE\t\t\t= 0,\r\n\tPNG_TRUECOLOR\t\t\t= 2,\r\n\tPNG_INDEXED\t\t\t\t= 3,\r\n\tPNG_GREYSCALE_ALPHA\t\t= 4,\r\n\tPNG_TRUECOLOR_ALPHA\t\t= 6\r\n};\r\n\r\n/*\r\n\tTypedefs for callbacks.\r\n*/\r\n\r\ntypedef unsigned (*png_write_callback_t)(void* input, unsigned long size, unsigned long numel, void* user_pointer);\r\ntypedef unsigned (*png_read_callback_t)(void* output, unsigned long size, unsigned long numel, void* user_pointer);\r\ntypedef void (*png_free_t)(void* p);\r\ntypedef void * (*png_alloc_t)(unsigned long s);\r\n\r\ntypedef struct\r\n{\r\n\tvoid*\t\t\t\t\tzs;\t\t\t\t/* pointer to z_stream */\r\n\tpng_read_callback_t\t\tread_fun;\r\n\tpng_write_callback_t\twrite_fun;\r\n\tvoid*\t\t\t\t\tuser_pointer;\r\n\r\n\tunsigned char*\t\t\tpng_data;\r\n\tunsigned\t\t\t\tpng_datalen;\r\n\r\n\tunsigned\t\t\t\twidth;\r\n\tunsigned\t\t\t\theight;\r\n\tunsigned char\t\t\tdepth;\r\n\tunsigned char\t\t\tcolor_type;\r\n\tunsigned char\t\t\tcompression_method;\r\n\tunsigned char\t\t\tfilter_method;\r\n\tunsigned char\t\t\tinterlace_method;\r\n\tunsigned char\t\t\tbpp;\r\n}png_t;\r\n\r\n/*\r\n\tFunction: png_init\r\n\r\n\tThis function initializes pnglite. The parameters can be used to set your own memory allocation routines following these formats:\r\n\r\n\t> void* (*custom_alloc)(unsigned long s)\r\n\t> void (*custom_free)(void* p)\r\n\tParameters:\r\n\t\tpngalloc - Pointer to custom allocation routine. If 0 is passed, malloc from libc will be used.\r\n\t\tpngfree - Pointer to custom free routine. If 0 is passed, free from libc will be used.\r\n\r\n\tReturns:\r\n\t\tAlways returns PNG_NO_ERROR.\r\n*/\r\n\r\nint png_init(png_alloc_t pngalloc, png_free_t pngfree);\r\n\r\n/*\r\n\tFunction: png_open_file\r\n\r\n\tThis function is used to open a png file with the internal file IO system. This function should be used instead of\r\n\tpng_open if no custom read function is used.\r\n\r\n\tParameters:\r\n\t\tpng - Empty png_t struct.\r\n\t\tfilename - Filename of the file to be opened.\r\n\r\n\tReturns:\r\n\t\tPNG_NO_ERROR on success, otherwise an error code.\r\n*/\r\n\r\nint png_open_file(png_t *png, const char* filename);\r\n\r\nint png_open_file_read(png_t *png, const char* filename);\r\nint png_open_file_write(png_t *png, const char* filename);\r\n\r\n/*\r\n\tFunction: png_open\r\n\r\n\tThis function reads or writes a png from/to the specified callback. The callbacks should be of the format:\r\n\r\n\t> unsigned long (*png_write_callback_t)(void* input, unsigned long size, unsigned long numel, void* user_pointer);\r\n\t> unsigned long (*png_read_callback_t)(void* output, unsigned long size, unsigned long numel, void* user_pointer).\r\n\r\n\tOnly one callback has to be specified. The read callback in case of PNG reading, otherwise the write callback.\r\n\r\n\tWriting:\r\n\tThe callback will be called like fwrite.\r\n\r\n\tReading:\r\n\tThe callback will be called each time pnglite needs more data. The callback should read as much data as requested, \r\n\tor return 0. This should always be possible if the PNG is sane.\tIf the output-buffer is a null-pointer the callback \r\n\tshould only skip ahead the specified number of elements. If the callback is a null-pointer the user_pointer will be \r\n\ttreated as a file pointer (use png_open_file instead).\r\n\r\n\tParameters:\r\n\t\tpng - png_t struct\r\n\t\tread_fun - Callback function for reading.\r\n\t\tuser_pointer - User pointer to be passed to read_fun.\r\n\r\n\tReturns:\r\n\t\tPNG_NO_ERROR on success, otherwise an error code.\r\n*/\r\n\r\nint png_open(png_t* png, png_read_callback_t read_fun, void* user_pointer);\r\n\r\nint png_open_read(png_t* png, png_read_callback_t read_fun, void* user_pointer);\r\nint png_open_write(png_t* png, png_write_callback_t write_fun, void* user_pointer);\r\n\r\n/*\r\n\tFunction: png_print_info\r\n\r\n\tThis function prints some info about the opened png file to stdout.\r\n\r\n\tParameters:\r\n\t\tpng - png struct to get info from.\r\n*/\r\n\r\nvoid png_print_info(png_t* png);\r\n\r\n/*\r\n\tFunction: png_error_string\r\n\r\n\tThis function translates an error code to a human readable string.\r\n\r\n\tParameters:\r\n\t\terror - Error code.\r\n\r\n\tReturns:\r\n\t\tPointer to string.\r\n*/\r\n\r\nchar* png_error_string(int error);\r\n\r\n/*\r\n\tFunction: png_get_data\r\n\r\n\tThis function decodes the opened png file and stores the result in data. data should be big enough to hold the decoded png. Required size will be:\r\n\t\r\n\t> width*height*(bytes per pixel)\r\n\r\n\tParameters:\r\n\t\tdata - Where to store result.\r\n\r\n\tReturns:\r\n\t\tPNG_NO_ERROR on success, otherwise an error code.\r\n*/\r\n\r\nint png_get_data(png_t* png, unsigned char* data);\r\n\r\nint png_set_data(png_t* png, unsigned width, unsigned height, char depth, int color, unsigned char* data);\r\n\r\n/*\r\n\tFunction: png_close_file\r\n\r\n\tCloses an open png file pointer. Should only be used when the png has been opened with png_open_file.\r\n\r\n\tParameters:\r\n\t\tpng - png to close.\r\n\t\r\n\tReturns:\r\n\t\tPNG_NO_ERROR\r\n*/\r\n\r\nint png_close_file(png_t* png);\r\n\r\n#ifdef __cplusplus\r\n}\r\n#endif\r\n#endif\r\n"
  },
  {
    "path": "src/engine/external/wavpack/VERSION",
    "content": "4.40"
  },
  {
    "path": "src/engine/external/wavpack/arm.S",
    "content": "////////////////////////////////////////////////////////////////////////////\n//                           **** WAVPACK ****                            //\n//                  Hybrid Lossless Wavefile Compressor                   //\n//              Copyright (c) 1998 - 2006 Conifer Software.               //\n//                          All Rights Reserved.                          //\n//      Distributed under the BSD Software License (see license.txt)      //\n////////////////////////////////////////////////////////////////////////////\n\n/* This is an assembly optimized version of the following WavPack function:\n *\n * void decorr_stereo_pass_cont (struct decorr_pass *dpp,\n *                               long *buffer, long sample_count);\n *\n * It performs a single pass of stereo decorrelation on the provided buffer.\n * Note that this version of the function requires that the 8 previous stereo\n * samples are visible and correct. In other words, it ignores the \"samples_*\"\n * fields in the decorr_pass structure and gets the history data directly\n * from the buffer. It does, however, return the appropriate history samples\n * to the decorr_pass structure before returning.\n *\n * This is written to work on a ARM7TDMI processor. This version only uses the\n * 32-bit multiply-accumulate instruction and so will overflow with 24-bit\n * WavPack files.\n */\n        .text\n        .align\n        .global         decorr_stereo_pass_cont_arm\n\n/*\n * on entry:\n *\n * r0 = struct decorr_pass *dpp\n * r1 = long *buffer\n * r2 = long sample_count\n */\n\ndecorr_stereo_pass_cont_arm:\n\n        stmfd   sp!, {r4 - r8, r10, r11, lr}\n        mov     r5, r0                  @ r5 = dpp\n        mov     r11, #512               @ r11 = 512 for rounding\n        ldrsh   r6, [r0, #2]            @ r6 = dpp->delta\n        ldrsh   r4, [r0, #4]            @ r4 = dpp->weight_A\n        ldrsh   r0, [r0, #6]            @ r0 = dpp->weight_B\n        cmp     r2, #0                  @ exit if no samples to process\n        beq     common_exit\n\n        add     r7, r1, r2, asl #3      @ r7 = buffer ending position\n        ldrsh   r2, [r5, #0]            @ r2 = dpp->term\n        cmp     r2, #0\n        bmi     minus_term\n\n        ldr     lr, [r1, #-16]          @ load 2 sample history from buffer\n        ldr     r10, [r1, #-12]         @  for terms 2, 17, and 18\n        ldr     r8, [r1, #-8]\n        ldr     r3, [r1, #-4]\n        cmp     r2, #17\n        beq     term_17_loop\n        cmp     r2, #18\n        beq     term_18_loop\n        cmp     r2, #2\n        beq     term_2_loop\n        b       term_default_loop       @ else handle default (1-8, except 2)\n\nminus_term:\n        mov     r10, #1024              @ r10 = -1024 for weight clipping\n        rsb     r10, r10, #0            @  (only used for negative terms)\n        cmn     r2, #1\n        beq     term_minus_1\n        cmn     r2, #2\n        beq     term_minus_2\n        cmn     r2, #3\n        beq     term_minus_3\n        b       common_exit\n\n/*\n ******************************************************************************\n * Loop to handle term = 17 condition\n *\n * r0 = dpp->weight_B           r8 = previous left sample\n * r1 = bptr                    r9 = \n * r2 = current sample          r10 = second previous left sample\n * r3 = previous right sample   r11 = 512 (for rounding)\n * r4 = dpp->weight_A           ip = current decorrelation value\n * r5 = dpp                     sp =\n * r6 = dpp->delta              lr = second previous right sample\n * r7 = eptr                    pc =\n *******************************************************************************\n */\n\nterm_17_loop:\n        rsbs    ip, lr, r8, asl #1      @ decorr value = (2 * prev) - 2nd prev\n        mov     lr, r8                  @ previous becomes 2nd previous\n        ldr     r2, [r1], #4            @ get sample & update pointer\n        mla     r8, ip, r4, r11         @ mult decorr value by weight, round,\n        add     r8, r2, r8, asr #10     @  shift, and add to new sample\n        strne   r8, [r1, #-4]           @ if change possible, store sample back\n        cmpne   r2, #0\n        beq     .L325\n        teq     ip, r2                  @ update weight based on signs\n        submi   r4, r4, r6\n        addpl   r4, r4, r6\n\n.L325:  rsbs    ip, r10, r3, asl #1     @ do same thing for right channel\n        mov     r10, r3\n        ldr     r2, [r1], #4\n        mla     r3, ip, r0, r11\n        add     r3, r2, r3, asr #10\n        strne   r3, [r1, #-4]\n        cmpne   r2, #0\n        beq     .L329\n        teq     ip, r2\n        submi   r0, r0, r6\n        addpl   r0, r0, r6\n\n.L329:  cmp     r7, r1                  @ loop back if more samples to do\n        bhi     term_17_loop\n        b       store_1718              @ common exit for terms 17 & 18\n\n/*\n ******************************************************************************\n * Loop to handle term = 18 condition\n *\n * r0 = dpp->weight_B           r8 = previous left sample\n * r1 = bptr                    r9 = \n * r2 = current sample          r10 = second previous left sample\n * r3 = previous right sample   r11 = 512 (for rounding)\n * r4 = dpp->weight_A           ip = decorrelation value\n * r5 = dpp                     sp =\n * r6 = dpp->delta              lr = second previous right sample\n * r7 = eptr                    pc =\n *******************************************************************************\n */\n\nterm_18_loop:\n        sub     ip, r8, lr              @ decorr value =\n        mov     lr, r8                  @  ((3 * prev) - 2nd prev) >> 1\n        adds    ip, r8, ip, asr #1\n        ldr     r2, [r1], #4            @ get sample & update pointer\n        mla     r8, ip, r4, r11         @ mult decorr value by weight, round,\n        add     r8, r2, r8, asr #10     @  shift, and add to new sample\n        strne   r8, [r1, #-4]           @ if change possible, store sample back\n        cmpne   r2, #0\n        beq     .L337\n        teq     ip, r2                  @ update weight based on signs\n        submi   r4, r4, r6\n        addpl   r4, r4, r6\n\n.L337:  sub     ip, r3, r10             @ do same thing for right channel\n        mov     r10, r3\n        adds    ip, r3, ip, asr #1\n        ldr     r2, [r1], #4\n        mla     r3, ip, r0, r11\n        add     r3, r2, r3, asr #10\n        strne   r3, [r1, #-4]\n        cmpne   r2, #0\n        beq     .L341\n        teq     ip, r2\n        submi   r0, r0, r6\n        addpl   r0, r0, r6\n\n.L341:  cmp     r7, r1                  @ loop back if more samples to do\n        bhi     term_18_loop\n\n/* common exit for terms 17 & 18 */\n\nstore_1718:\n        str     r3, [r5, #40]           @ store sample history into struct\n        str     r8, [r5, #8]\n        str     r10, [r5, #44]\n        str     lr, [r5, #12]\n        b       common_exit             @ and return\n\n/*\n ******************************************************************************\n * Loop to handle term = 2 condition\n * (note that this case can be handled by the default term handler (1-8), but\n * this special case is faster because it doesn't have to read memory twice)\n *\n * r0 = dpp->weight_B           r8 = previous left sample\n * r1 = bptr                    r9 = \n * r2 = current sample          r10 = second previous left sample\n * r3 = previous right sample   r11 = 512 (for rounding)\n * r4 = dpp->weight_A           ip = decorrelation value\n * r5 = dpp                     sp =\n * r6 = dpp->delta              lr = second previous right sample\n * r7 = eptr                    pc =\n *******************************************************************************\n */\n\nterm_2_loop:\n        movs    ip, lr                  @ get decorrelation value & test\n        mov     lr, r8                  @ previous becomes 2nd previous\n        ldr     r2, [r1], #4            @ get sample & update pointer\n        mla     r8, ip, r4, r11         @ mult decorr value by weight, round,\n        add     r8, r2, r8, asr #10     @  shift, and add to new sample\n        strne   r8, [r1, #-4]           @ if change possible, store sample back\n        cmpne   r2, #0\n        beq     .L225\n        teq     ip, r2                  @ update weight based on signs\n        submi   r4, r4, r6\n        addpl   r4, r4, r6\n\n.L225:  movs    ip, r10                 @ do same thing for right channel\n        mov     r10, r3\n        ldr     r2, [r1], #4\n        mla     r3, ip, r0, r11\n        add     r3, r2, r3, asr #10\n        strne   r3, [r1, #-4]\n        cmpne   r2, #0\n        beq     .L229\n        teq     ip, r2\n        submi   r0, r0, r6\n        addpl   r0, r0, r6\n\n.L229:  cmp     r7, r1                  @ loop back if more samples to do\n        bhi     term_2_loop\n        b       default_term_exit       @ this exit updates all dpp->samples\n\n/*\n ******************************************************************************\n * Loop to handle default term condition\n *\n * r0 = dpp->weight_B           r8 = result accumulator\n * r1 = bptr                    r9 = \n * r2 = dpp->term               r10 =\n * r3 = decorrelation value     r11 = 512 (for rounding)\n * r4 = dpp->weight_A           ip = current sample\n * r5 = dpp                     sp =\n * r6 = dpp->delta              lr =\n * r7 = eptr                    pc =\n *******************************************************************************\n */\n\nterm_default_loop:\n        ldr     ip, [r1]                @ get original sample\n        ldr     r3, [r1, -r2, asl #3]   @ get decorrelation value based on term\n        mla     r8, r3, r4, r11         @ mult decorr value by weight, round,\n        add     r8, ip, r8, asr #10     @  shift and add to new sample\n        str     r8, [r1], #4            @ store update sample\n        cmp     r3, #0\n        cmpne   ip, #0\n        beq     .L350\n        teq     ip, r3                  @ update weight based on signs\n        submi   r4, r4, r6\n        addpl   r4, r4, r6\n\n.L350:  ldr     ip, [r1]                @ do the same thing for right channel\n        ldr     r3, [r1, -r2, asl #3]\n        mla     r8, r3, r0, r11\n        add     r8, ip, r8, asr #10\n        str     r8, [r1], #4\n        cmp     r3, #0\n        cmpne   ip, #0\n        beq     .L354\n        teq     ip, r3\n        submi   r0, r0, r6\n        addpl   r0, r0, r6\n\n.L354:  cmp     r7, r1                  @ loop back if more samples to do\n        bhi     term_default_loop\n\n/*\n * This exit is used by terms 1-8 to store the previous 8 samples into the decorr\n * structure (even if they are not all used for the given term)\n */\n\ndefault_term_exit:\n        ldrsh   r3, [r5, #0]\n        sub     ip, r3, #1\n        mov     lr, #7\n\n.L358:  and     r3, ip, #7\n        add     r3, r5, r3, asl #2\n        ldr     r2, [r1, #-4]\n        str     r2, [r3, #40]\n        ldr     r2, [r1, #-8]!\n        str     r2, [r3, #8]\n        sub     ip, ip, #1\n        sub     lr, lr, #1\n        cmn     lr, #1\n        bne     .L358\n        b       common_exit\n\n/*\n ******************************************************************************\n * Loop to handle term = -1 condition\n *\n * r0 = dpp->weight_B           r8 =\n * r1 = bptr                    r9 = \n * r2 = intermediate result     r10 = -1024 (for clipping)\n * r3 = previous right sample   r11 = 512 (for rounding)\n * r4 = dpp->weight_A           ip = current sample\n * r5 = dpp                     sp =\n * r6 = dpp->delta              lr = updated left sample\n * r7 = eptr                    pc =\n *******************************************************************************\n */\n\nterm_minus_1:\n        ldr     r3, [r1, #-4]\n\nterm_minus_1_loop:\n        ldr     ip, [r1]                @ for left channel the decorrelation value\n        mla     r2, r3, r4, r11         @  is the previous right sample (in r3)\n        add     lr, ip, r2, asr #10\n        str     lr, [r1], #8\n        cmp     r3, #0\n        cmpne   ip, #0\n        beq     .L361\n        teq     ip, r3                  @ update weight based on signs\n        submi   r4, r4, r6\n        addpl   r4, r4, r6\n        cmp     r4, #1024\n        movgt   r4, #1024\n        cmp     r4, r10\n        movlt   r4, r10\n\n.L361:  ldr     r2, [r1, #-4]           @ for right channel the decorrelation value\n        mla     r3, lr, r0, r11         @  is the just updated right sample (in lr)\n        add     r3, r2, r3, asr #10\n        str     r3, [r1, #-4]\n        cmp     lr, #0\n        cmpne   r2, #0\n        beq     .L369\n        teq     r2, lr\n        submi   r0, r0, r6\n        addpl   r0, r0, r6\n        cmp     r0, #1024               @ then clip weight to +/-1024\n        movgt   r0, #1024\n        cmp     r0, r10\n        movlt   r0, r10\n\n.L369:  cmp     r7, r1                  @ loop back if more samples to do\n        bhi     term_minus_1_loop\n\n        str     r3, [r5, #8]            @ else store right sample and exit\n        b       common_exit\n\n/*\n ******************************************************************************\n * Loop to handle term = -2 condition\n * (note that the channels are processed in the reverse order here)\n *\n * r0 = dpp->weight_B           r8 =\n * r1 = bptr                    r9 = \n * r2 = intermediate result     r10 = -1024 (for clipping)\n * r3 = previous left sample    r11 = 512 (for rounding)\n * r4 = dpp->weight_A           ip = current sample\n * r5 = dpp                     sp =\n * r6 = dpp->delta              lr = updated right sample\n * r7 = eptr                    pc =\n *******************************************************************************\n */\n\nterm_minus_2:\n        ldr     r3, [r1, #-8]\n\nterm_minus_2_loop:\n        ldr     ip, [r1, #4]            @ for right channel the decorrelation value\n        mla     r2, r3, r0, r11         @  is the previous left sample (in r3)\n        add     lr, ip, r2, asr #10\n        str     lr, [r1, #4]\n        cmp     r3, #0\n        cmpne   ip, #0\n        beq     .L380\n        teq     ip, r3                  @ update weight based on signs\n        submi   r0, r0, r6\n        addpl   r0, r0, r6\n        cmp     r0, #1024               @ then clip weight to +/-1024\n        movgt   r0, #1024\n        cmp     r0, r10\n        movlt   r0, r10\n\n.L380:  ldr     r2, [r1, #0]            @ for left channel the decorrelation value\n        mla     r3, lr, r4, r11         @  is the just updated left sample (in lr)\n        add     r3, r2, r3, asr #10\n        str     r3, [r1], #8\n        cmp     lr, #0\n        cmpne   r2, #0\n        beq     .L388\n        teq     r2, lr\n        submi   r4, r4, r6\n        addpl   r4, r4, r6\n        cmp     r4, #1024\n        movgt   r4, #1024\n        cmp     r4, r10\n        movlt   r4, r10\n\n.L388:  cmp     r7, r1                  @ loop back if more samples to do\n        bhi     term_minus_2_loop\n\n        str     r3, [r5, #40]           @ else store left channel and exit\n        b       common_exit\n\n/*\n ******************************************************************************\n * Loop to handle term = -3 condition\n *\n * r0 = dpp->weight_B           r8 = previous left sample\n * r1 = bptr                    r9 = \n * r2 = current left sample     r10 = -1024 (for clipping)\n * r3 = previous right sample   r11 = 512 (for rounding)\n * r4 = dpp->weight_A           ip = intermediate result\n * r5 = dpp                     sp =\n * r6 = dpp->delta              lr =\n * r7 = eptr                    pc =\n *******************************************************************************\n */\n\nterm_minus_3:\n        ldr     r3, [r1, #-4]           @ load previous samples\n        ldr     r8, [r1, #-8]\n\nterm_minus_3_loop:\n        ldr     ip, [r1]\n        mla     r2, r3, r4, r11\n        add     r2, ip, r2, asr #10\n        str     r2, [r1], #4\n        cmp     r3, #0\n        cmpne   ip, #0\n        beq     .L399\n        teq     ip, r3                  @ update weight based on signs\n        submi   r4, r4, r6\n        addpl   r4, r4, r6\n        cmp     r4, #1024               @ then clip weight to +/-1024\n        movgt   r4, #1024\n        cmp     r4, r10\n        movlt   r4, r10\n\n.L399:  movs    ip, r8                  @ ip = previous left we use now\n        mov     r8, r2                  @ r8 = current left we use next time\n        ldr     r2, [r1], #4\n        mla     r3, ip, r0, r11\n        add     r3, r2, r3, asr #10\n        strne   r3, [r1, #-4]\n        cmpne   r2, #0\n        beq     .L407\n        teq     ip, r2\n        submi   r0, r0, r6\n        addpl   r0, r0, r6\n        cmp     r0, #1024\n        movgt   r0, #1024\n        cmp     r0, r10\n        movlt   r0, r10\n\n.L407:  cmp     r7, r1                  @ loop back if more samples to do\n        bhi     term_minus_3_loop\n\n        str     r3, [r5, #8]            @ else store previous samples & exit\n        str     r8, [r5, #40]\n\n/*\n * Before finally exiting we must store weights back for next time\n */\n\ncommon_exit:\n        strh    r4, [r5, #4]\n        strh    r0, [r5, #6]\n        ldmfd   sp!, {r4 - r8, r10, r11, pc}\n\n"
  },
  {
    "path": "src/engine/external/wavpack/arml.S",
    "content": "////////////////////////////////////////////////////////////////////////////\n//                           **** WAVPACK ****                            //\n//                  Hybrid Lossless Wavefile Compressor                   //\n//              Copyright (c) 1998 - 2006 Conifer Software.               //\n//                          All Rights Reserved.                          //\n//      Distributed under the BSD Software License (see license.txt)      //\n////////////////////////////////////////////////////////////////////////////\n\n/* This is an assembly optimized version of the following WavPack function:\n *\n * void decorr_stereo_pass_cont (struct decorr_pass *dpp,\n *                               long *buffer, long sample_count);\n *\n * It performs a single pass of stereo decorrelation on the provided buffer.\n * Note that this version of the function requires that the 8 previous stereo\n * samples are visible and correct. In other words, it ignores the \"samples_*\"\n * fields in the decorr_pass structure and gets the history data directly\n * from the buffer. It does, however, return the appropriate history samples\n * to the decorr_pass structure before returning.\n *\n * This is written to work on a ARM7TDMI processor. This version uses the\n * 64-bit multiply-accumulate instruction and so can be used with all\n * WavPack files. However, for optimum performance with 16-bit WavPack\n * files, there is a faster version that only uses the 32-bit MLA\n * instruction.\n */\n\n        .text\n        .align\n        .global         decorr_stereo_pass_cont_arml\n\n/*\n * on entry:\n *\n * r0 = struct decorr_pass *dpp\n * r1 = long *buffer\n * r2 = long sample_count\n */\n\ndecorr_stereo_pass_cont_arml:\n\n        stmfd   sp!, {r4 - r8, r10, r11, lr}\n        mov     r5, r0                  @ r5 = dpp\n        mov     r11, #512               @ r11 = 512 for rounding\n        ldrsh   r6, [r0, #2]            @ r6 = dpp->delta\n        ldrsh   r4, [r0, #4]            @ r4 = dpp->weight_A\n        ldrsh   r0, [r0, #6]            @ r0 = dpp->weight_B\n        cmp     r2, #0                  @ exit if no samples to process\n        beq     common_exit\n\n        mov     r0, r0, asl #18         @ for 64-bit math we use weights << 18\n        mov     r4, r4, asl #18\n        mov     r6, r6, asl #18\n        add     r7, r1, r2, asl #3      @ r7 = buffer ending position\n        ldrsh   r2, [r5, #0]            @ r2 = dpp->term\n        cmp     r2, #0\n        blt     minus_term\n\n        ldr     lr, [r1, #-16]          @ load 2 sample history from buffer\n        ldr     r10, [r1, #-12]         @  for terms 2, 17, and 18\n        ldr     r8, [r1, #-8]\n        ldr     r3, [r1, #-4]\n\n        cmp     r2, #18\n        beq     term_18_loop\n        mov     lr, lr, asl #4\n        mov     r10, r10, asl #4\n        cmp     r2, #2\n        beq     term_2_loop\n        cmp     r2, #17\n        beq     term_17_loop\n        b       term_default_loop\n\nminus_term:\n        mov     r10, #(1024 << 18)      @ r10 = -1024 << 18 for weight clipping\n        rsb     r10, r10, #0            @  (only used for negative terms)\n        cmn     r2, #1\n        beq     term_minus_1\n        cmn     r2, #2\n        beq     term_minus_2\n        cmn     r2, #3\n        beq     term_minus_3\n        b       common_exit\n\n/*\n ******************************************************************************\n * Loop to handle term = 17 condition\n *\n * r0 = dpp->weight_B           r8 = previous left sample\n * r1 = bptr                    r9 = \n * r2 = current sample          r10 = second previous left sample << 4\n * r3 = previous right sample   r11 = lo accumulator (for rounding)\n * r4 = dpp->weight_A           ip = current decorrelation value\n * r5 = dpp                     sp =\n * r6 = dpp->delta              lr = second previous right sample << 4\n * r7 = eptr                    pc =\n *******************************************************************************\n */\n\nterm_17_loop:\n        rsbs    ip, lr, r8, asl #5      @ decorr value = (2 * prev) - 2nd prev\n        mov     lr, r8, asl #4          @ previous becomes 2nd previous\n        ldr     r2, [r1], #4            @ get sample & update pointer\n        mov     r11, #0x80000000\n        mov     r8, r2\n        smlalne r11, r8, r4, ip\n        strne   r8, [r1, #-4]           @ if change possible, store sample back\n        cmpne   r2, #0\n        beq     .L325\n        teq     ip, r2                  @ update weight based on signs\n        submi   r4, r4, r6\n        addpl   r4, r4, r6\n\n.L325:  rsbs    ip, r10, r3, asl #5     @ do same thing for right channel\n        mov     r10, r3, asl #4\n        ldr     r2, [r1], #4\n        mov     r11, #0x80000000\n        mov     r3, r2\n        smlalne r11, r3, r0, ip\n        strne   r3, [r1, #-4]\n        cmpne   r2, #0\n        beq     .L329\n        teq     ip, r2\n        submi   r0, r0, r6\n        addpl   r0, r0, r6\n\n.L329:  cmp     r7, r1                  @ loop back if more samples to do\n        bhi     term_17_loop\n        mov     lr, lr, asr #4\n        mov     r10, r10, asr #4\n        b       store_1718              @ common exit for terms 17 & 18\n\n/*\n ******************************************************************************\n * Loop to handle term = 18 condition\n *\n * r0 = dpp->weight_B           r8 = previous left sample\n * r1 = bptr                    r9 = \n * r2 = current sample          r10 = second previous left sample\n * r3 = previous right sample   r11 = lo accumulator (for rounding)\n * r4 = dpp->weight_A           ip = decorrelation value\n * r5 = dpp                     sp =\n * r6 = dpp->delta              lr = second previous right sample\n * r7 = eptr                    pc =\n *******************************************************************************\n */\n\nterm_18_loop:\n        rsb     ip, lr, r8              @ decorr value =\n        mov     lr, r8                  @  ((3 * prev) - 2nd prev) >> 1\n        add     ip, lr, ip, asr #1\n        movs    ip, ip, asl #4\n        ldr     r2, [r1], #4            @ get sample & update pointer\n        mov     r11, #0x80000000\n        mov     r8, r2\n        smlalne r11, r8, r4, ip\n        strne   r8, [r1, #-4]           @ if change possible, store sample back\n        cmpne   r2, #0\n        beq     .L337\n        teq     ip, r2                  @ update weight based on signs\n        submi   r4, r4, r6\n        addpl   r4, r4, r6\n\n.L337:  rsb     ip, r10, r3             @ do same thing for right channel\n        mov     r10, r3\n        add     ip, r10, ip, asr #1\n        movs    ip, ip, asl #4\n        ldr     r2, [r1], #4\n        mov     r11, #0x80000000\n        mov     r3, r2\n        smlalne r11, r3, r0, ip\n        strne   r3, [r1, #-4]\n        cmpne   r2, #0\n        beq     .L341\n        teq     ip, r2\n        submi   r0, r0, r6\n        addpl   r0, r0, r6\n\n.L341:  cmp     r7, r1                  @ loop back if more samples to do\n        bhi     term_18_loop\n\n/* common exit for terms 17 & 18 */\n\nstore_1718:\n        str     r3, [r5, #40]           @ store sample history into struct\n        str     r8, [r5, #8]\n        str     r10, [r5, #44]\n        str     lr, [r5, #12]\n        b       common_exit             @ and return\n\n/*\n ******************************************************************************\n * Loop to handle term = 2 condition\n * (note that this case can be handled by the default term handler (1-8), but\n * this special case is faster because it doesn't have to read memory twice)\n *\n * r0 = dpp->weight_B           r8 = previous left sample\n * r1 = bptr                    r9 = \n * r2 = current sample          r10 = second previous left sample << 4\n * r3 = previous right sample   r11 = lo accumulator (for rounding)\n * r4 = dpp->weight_A           ip = decorrelation value\n * r5 = dpp                     sp =\n * r6 = dpp->delta              lr = second previous right sample << 4\n * r7 = eptr                    pc =\n *******************************************************************************\n */\n\nterm_2_loop:\n        movs    ip, lr                  @ get decorrelation value & test\n        ldr     r2, [r1], #4            @ get sample & update pointer\n        mov     lr, r8, asl #4          @ previous becomes 2nd previous\n        mov     r11, #0x80000000\n        mov     r8, r2\n        smlalne r11, r8, r4, ip\n        strne   r8, [r1, #-4]           @ if change possible, store sample back\n        cmpne   r2, #0\n        beq     .L225\n        teq     ip, r2                  @ update weight based on signs\n        submi   r4, r4, r6\n        addpl   r4, r4, r6\n\n.L225:  movs    ip, r10                 @ do same thing for right channel\n        ldr     r2, [r1], #4\n        mov     r10, r3, asl #4\n        mov     r11, #0x80000000\n        mov     r3, r2\n        smlalne r11, r3, r0, ip\n        strne   r3, [r1, #-4]\n        cmpne   r2, #0\n        beq     .L229\n        teq     ip, r2\n        submi   r0, r0, r6\n        addpl   r0, r0, r6\n\n.L229:  cmp     r7, r1                  @ loop back if more samples to do\n        bhi     term_2_loop\n\n        b       default_term_exit       @ this exit updates all dpp->samples\n\n/*\n ******************************************************************************\n * Loop to handle default term condition\n *\n * r0 = dpp->weight_B           r8 = result accumulator\n * r1 = bptr                    r9 = \n * r2 = dpp->term               r10 =\n * r3 = decorrelation value     r11 = lo accumulator (for rounding)\n * r4 = dpp->weight_A           ip = current sample\n * r5 = dpp                     sp =\n * r6 = dpp->delta              lr =\n * r7 = eptr                    pc =\n *******************************************************************************\n */\n\nterm_default_loop:\n        ldr     r3, [r1, -r2, asl #3]   @ get decorrelation value based on term\n        ldr     ip, [r1], #4            @ get original sample and bump ptr\n        movs    r3, r3, asl #4\n        mov     r11, #0x80000000\n        mov     r8, ip\n        smlalne r11, r8, r4, r3\n        strne   r8, [r1, #-4]           @ if possibly changed, store updated sample\n        cmpne   ip, #0\n        beq     .L350\n        teq     ip, r3                  @ update weight based on signs\n        submi   r4, r4, r6\n        addpl   r4, r4, r6\n\n.L350:  ldr     r3, [r1, -r2, asl #3]   @ do the same thing for right channel\n        ldr     ip, [r1], #4\n        movs    r3, r3, asl #4\n        mov     r11, #0x80000000\n        mov     r8, ip\n        smlalne r11, r8, r0, r3\n        strne   r8, [r1, #-4]\n        cmpne   ip, #0\n        beq     .L354\n        teq     ip, r3\n        submi   r0, r0, r6\n        addpl   r0, r0, r6\n\n.L354:  cmp     r7, r1                  @ loop back if more samples to do\n        bhi     term_default_loop\n\n/*\n * This exit is used by terms 1-8 to store the previous 8 samples into the decorr\n * structure (even if they are not all used for the given term)\n */\n\ndefault_term_exit:\n        ldrsh   r3, [r5, #0]\n        sub     ip, r3, #1\n        mov     lr, #7\n\n.L358:  and     r3, ip, #7\n        add     r3, r5, r3, asl #2\n        ldr     r2, [r1, #-4]\n        str     r2, [r3, #40]\n        ldr     r2, [r1, #-8]!\n        str     r2, [r3, #8]\n        sub     ip, ip, #1\n        sub     lr, lr, #1\n        cmn     lr, #1\n        bne     .L358\n        b       common_exit\n\n/*\n ******************************************************************************\n * Loop to handle term = -1 condition\n *\n * r0 = dpp->weight_B           r8 =\n * r1 = bptr                    r9 = \n * r2 = intermediate result     r10 = -1024 (for clipping)\n * r3 = previous right sample   r11 = lo accumulator (for rounding)\n * r4 = dpp->weight_A           ip = current sample\n * r5 = dpp                     sp =\n * r6 = dpp->delta              lr = updated left sample\n * r7 = eptr                    pc =\n *******************************************************************************\n */\n\nterm_minus_1:\n        ldr     r3, [r1, #-4]\n\nterm_minus_1_loop:\n        ldr     ip, [r1], #8            @ for left channel the decorrelation value\n        movs    r3, r3, asl #4          @  is the previous right sample (in r3)\n        mov     r11, #0x80000000\n        mov     lr, ip\n        smlalne r11, lr, r4, r3\n        strne   lr, [r1, #-8]\n        cmpne   ip, #0\n        beq     .L361\n        teq     ip, r3                  @ update weight based on signs\n        submi   r4, r4, r6\n        addpl   r4, r4, r6\n        cmp     r4, #(1024 << 18)\n        movgt   r4, #(1024 << 18)\n        cmp     r4, r10\n        movlt   r4, r10\n\n.L361:  ldr     r2, [r1, #-4]           @ for right channel the decorrelation value\n        movs    lr, lr, asl #4\n        mov     r11, #0x80000000\n        mov     r3, r2\n        smlalne r11, r3, r0, lr\n        strne   r3, [r1, #-4]\n        cmpne   r2, #0\n        beq     .L369\n        teq     r2, lr\n        submi   r0, r0, r6\n        addpl   r0, r0, r6\n        cmp     r0, #(1024 << 18)               @ then clip weight to +/-1024\n        movgt   r0, #(1024 << 18)\n        cmp     r0, r10\n        movlt   r0, r10\n\n.L369:  cmp     r7, r1                  @ loop back if more samples to do\n        bhi     term_minus_1_loop\n\n        str     r3, [r5, #8]            @ else store right sample and exit\n        b       common_exit\n\n/*\n ******************************************************************************\n * Loop to handle term = -2 condition\n * (note that the channels are processed in the reverse order here)\n *\n * r0 = dpp->weight_B           r8 =\n * r1 = bptr                    r9 = \n * r2 = intermediate result     r10 = -1024 (for clipping)\n * r3 = previous left sample    r11 = lo accumulator (for rounding)\n * r4 = dpp->weight_A           ip = current sample\n * r5 = dpp                     sp =\n * r6 = dpp->delta              lr = updated right sample\n * r7 = eptr                    pc =\n *******************************************************************************\n */\n\nterm_minus_2:\n        ldr     r3, [r1, #-8]\n\nterm_minus_2_loop:\n        ldr     ip, [r1, #4]            @ for right channel the decorrelation value\n        movs    r3, r3, asl #4          @  is the previous left sample (in r3)\n        mov     r11, #0x80000000\n        mov     lr, ip\n        smlalne r11, lr, r0, r3\n        strne   lr, [r1, #4]\n        cmpne   ip, #0\n        beq     .L380\n        teq     ip, r3                  @ update weight based on signs\n        submi   r0, r0, r6\n        addpl   r0, r0, r6\n        cmp     r0, #(1024 << 18)               @ then clip weight to +/-1024\n        movgt   r0, #(1024 << 18)\n        cmp     r0, r10\n        movlt   r0, r10\n\n.L380:  ldr     r2, [r1], #8            @ for left channel the decorrelation value\n        movs    lr, lr, asl #4\n        mov     r11, #0x80000000\n        mov     r3, r2\n        smlalne r11, r3, r4, lr\n        strne   r3, [r1, #-8]\n        cmpne   r2, #0\n        beq     .L388\n        teq     r2, lr\n        submi   r4, r4, r6\n        addpl   r4, r4, r6\n        cmp     r4, #(1024 << 18)\n        movgt   r4, #(1024 << 18)\n        cmp     r4, r10\n        movlt   r4, r10\n\n.L388:  cmp     r7, r1                  @ loop back if more samples to do\n        bhi     term_minus_2_loop\n\n        str     r3, [r5, #40]           @ else store left channel and exit\n        b       common_exit\n\n/*\n ******************************************************************************\n * Loop to handle term = -3 condition\n *\n * r0 = dpp->weight_B           r8 = previous left sample\n * r1 = bptr                    r9 = \n * r2 = current left sample     r10 = -1024 (for clipping)\n * r3 = previous right sample   r11 = lo accumulator (for rounding)\n * r4 = dpp->weight_A           ip = intermediate result\n * r5 = dpp                     sp =\n * r6 = dpp->delta              lr =\n * r7 = eptr                    pc =\n *******************************************************************************\n */\n\nterm_minus_3:\n        ldr     r3, [r1, #-4]           @ load previous samples\n        ldr     r8, [r1, #-8]\n\nterm_minus_3_loop:\n        ldr     ip, [r1], #4\n        movs    r3, r3, asl #4\n        mov     r11, #0x80000000\n        mov     r2, ip\n        smlalne r11, r2, r4, r3\n        strne   r2, [r1, #-4]\n        cmpne   ip, #0\n        beq     .L399\n        teq     ip, r3                  @ update weight based on signs\n        submi   r4, r4, r6\n        addpl   r4, r4, r6\n        cmp     r4, #(1024 << 18)       @ then clip weight to +/-1024\n        movgt   r4, #(1024 << 18)\n        cmp     r4, r10\n        movlt   r4, r10\n\n.L399:  movs    ip, r8, asl #4          @ ip = previous left we use now\n        mov     r8, r2                  @ r8 = current left we use next time\n        ldr     r2, [r1], #4\n        mov     r11, #0x80000000\n        mov     r3, r2\n        smlalne r11, r3, r0, ip\n        strne   r3, [r1, #-4]\n        cmpne   r2, #0\n        beq     .L407\n        teq     ip, r2\n        submi   r0, r0, r6\n        addpl   r0, r0, r6\n        cmp     r0, #(1024 << 18)\n        movgt   r0, #(1024 << 18)\n        cmp     r0, r10\n        movlt   r0, r10\n\n.L407:  cmp     r7, r1                  @ loop back if more samples to do\n        bhi     term_minus_3_loop\n\n        str     r3, [r5, #8]            @ else store previous samples & exit\n        str     r8, [r5, #40]\n\n/*\n * Before finally exiting we must store weights back for next time\n */\n\ncommon_exit:\n        mov     r0, r0, asr #18         @ restore weights to real magnitude\n        mov     r4, r4, asr #18\n        strh    r4, [r5, #4]\n        strh    r0, [r5, #6]\n        ldmfd   sp!, {r4 - r8, r10, r11, pc}\n\n"
  },
  {
    "path": "src/engine/external/wavpack/bits.c",
    "content": "////////////////////////////////////////////////////////////////////////////\n//                           **** WAVPACK ****                            //\n//                  Hybrid Lossless Wavefile Compressor                   //\n//              Copyright (c) 1998 - 2006 Conifer Software.               //\n//                          All Rights Reserved.                          //\n//      Distributed under the BSD Software License (see license.txt)      //\n////////////////////////////////////////////////////////////////////////////\n\n// bits.c\n\n// This module provides utilities to support the BitStream structure which is\n// used to read and write all WavPack audio data streams. It also contains a\n// wrapper for the stream I/O functions and a set of functions dealing with\n// endian-ness, both for enhancing portability. Finally, a debug wrapper for\n// the malloc() system is provided.\n\n#include \"wavpack.h\"\n\n#include <string.h>\n#include <ctype.h>\n\n////////////////////////// Bitstream functions ////////////////////////////////\n\n// Open the specified BitStream and associate with the specified buffer.\n\nstatic void bs_read (Bitstream *bs);\n\nvoid bs_open_read (Bitstream *bs, uchar *buffer_start, uchar *buffer_end, read_stream file, uint32_t file_bytes)\n{\n    CLEAR (*bs);\n    bs->buf = buffer_start;\n    bs->end = buffer_end;\n\n    if (file) {\n        bs->ptr = bs->end - 1;\n        bs->file_bytes = file_bytes;\n        bs->file = file;\n    }\n    else\n        bs->ptr = bs->buf - 1;\n\n    bs->wrap = bs_read;\n}\n\n// This function is only called from the getbit() and getbits() macros when\n// the BitStream has been exhausted and more data is required. Sinve these\n// bistreams no longer access files, this function simple sets an error and\n// resets the buffer.\n\nstatic void bs_read (Bitstream *bs)\n{\n    if (bs->file && bs->file_bytes) {\n        uint32_t bytes_read, bytes_to_read = bs->end - bs->buf;\n\n        if (bytes_to_read > bs->file_bytes)\n            bytes_to_read = bs->file_bytes;\n\n        bytes_read = bs->file (bs->buf, bytes_to_read);\n\n        if (bytes_read) {\n            bs->end = bs->buf + bytes_read;\n            bs->file_bytes -= bytes_read;\n        }\n        else {\n            memset (bs->buf, -1, bs->end - bs->buf);\n            bs->error = 1;\n        }\n    }\n    else\n        bs->error = 1;\n\n    if (bs->error)\n        memset (bs->buf, -1, bs->end - bs->buf);\n\n    bs->ptr = bs->buf;\n}\n\n/////////////////////// Endian Correction Routines ////////////////////////////\n\nvoid little_endian_to_native (void *data, char *format)\n{\n    uchar *cp = (uchar *) data;\n    int32_t temp;\n\n    while (*format) {\n        switch (*format) {\n            case 'L':\n                temp = cp [0] + ((int32_t) cp [1] << 8) + ((int32_t) cp [2] << 16) + ((int32_t) cp [3] << 24);\n                * (int32_t *) cp = temp;\n                cp += 4;\n                break;\n\n            case 'S':\n                temp = cp [0] + (cp [1] << 8);\n                * (short *) cp = (short) temp;\n                cp += 2;\n                break;\n\n            default:\n                if (isdigit (*format))\n                    cp += *format - '0';\n\n                break;\n        }\n\n        format++;\n    }\n}\n\nvoid native_to_little_endian (void *data, char *format)\n{\n    uchar *cp = (uchar *) data;\n    int32_t temp;\n\n    while (*format) {\n        switch (*format) {\n            case 'L':\n                temp = * (int32_t *) cp;\n                *cp++ = (uchar) temp;\n                *cp++ = (uchar) (temp >> 8);\n                *cp++ = (uchar) (temp >> 16);\n                *cp++ = (uchar) (temp >> 24);\n                break;\n\n            case 'S':\n                temp = * (short *) cp;\n                *cp++ = (uchar) temp;\n                *cp++ = (uchar) (temp >> 8);\n                break;\n\n            default:\n                if (isdigit (*format))\n                    cp += *format - '0';\n\n                break;\n        }\n\n        format++;\n    }\n}\n"
  },
  {
    "path": "src/engine/external/wavpack/coldfire.S",
    "content": "////////////////////////////////////////////////////////////////////////////\n//                           **** WAVPACK ****                            //\n//                  Hybrid Lossless Wavefile Compressor                   //\n//              Copyright (c) 1998 - 2006 Conifer Software.               //\n//                          All Rights Reserved.                          //\n//      Distributed under the BSD Software License (see license.txt)      //\n////////////////////////////////////////////////////////////////////////////\n\n/* This is an assembly optimized version of the following WavPack function:\n *\n * void decorr_stereo_pass_cont (struct decorr_pass *dpp,\n *                               long *buffer, long sample_count);\n *\n * It performs a single pass of stereo decorrelation on the provided buffer.\n * Note that this version of the function requires that the 8 previous stereo\n * samples are visible and correct. In other words, it ignores the \"samples_*\"\n * fields in the decorr_pass structure and gets the history data directly\n * from the buffer. It does, however, return the appropriate history samples\n * to the decorr_pass structure before returning.\n *\n * This is written to work on a MCF5249 processor, or any processor based on\n * the ColdFire V2 core with an EMAC unit. The EMAC is perfectly suited for\n * the \"apply_weight\" function of WavPack decorrelation because it provides\n * the requires 40-bit product. The fractional rounding mode of the EMAC is not\n * configurable and uses \"round to even\" while WavPack uses \"round to larger\",\n * so the rounding has to be done manually.\n */\n\n        .text\n        .align  2\n        .global decorr_stereo_pass_cont_mcf5249\n\ndecorr_stereo_pass_cont_mcf5249:\n\n        lea     (-44, %sp), %sp\n        movem.l %d2-%d7/%a2-%a6, (%sp)\n        move.l  44+4(%sp), %a2          | a2 = dpp->\n        move.l  44+8(%sp), %a1          | a1 = bptr\n        move.w  2(%a2), %a3             | a3 = dpp->delta\n        move.w  4(%a2), %d3             | d3 = dpp->weight_A (sign extended)\n        ext.l   %d3\n        move.w  6(%a2), %d4             | d4 = dpp->weight_B (sign extended)\n        ext.l   %d4\n        move.l 44+12(%sp), %d0          | d0 = sample_count\n        jbeq    return_only             | if zero, nothing to do\n\n        lsl.l   #3, %d0                 | d5 = bptr + (sample_count * 8)\n        move.l  %d0, %d5\n        add.l   %a1, %d5\n\n        moveq.l #17, %d0                | left shift weights & delta 17 places\n        asl.l   %d0, %d3\n        asl.l   %d0, %d4\n        move.l  %a3, %d1\n        asl.l   %d0, %d1\n        move.l  %d1, %a3\n\n        moveq.l #0x20, %d6\n        move.l  %d6, %macsr             | set fractional mode for MAC\n        move.l  #0, %acc1               | acc1 = 0x00 0000 80 (for rounding)\n        move.l  #0x800000, %accext01\n        \n        move.l  #1024<<17, %d6          | d6 & d7 are weight clipping limits\n        move.l  #-1024<<17, %d7         | (only used by negative terms)\n\n        move.w  (%a2), %d0              | d0 = term\n        ext.l   %d0\n        cmp.l   #17, %d0\n        jbeq    term_17                 | term = 17\n        cmp.l   #18, %d0\n        jbeq    term_18                 | term = 18\n        addq.l  #1, %d0\n        jbeq    term_minus_1            | term = -1\n        addq.l  #1, %d0\n        jbeq    term_minus_2            | term = -2\n        addq.l  #1, %d0\n        jbeq    term_minus_3            | term = -3\n        jbra    term_default            | default term = 1 - 8\n\n|------------------------------------------------------------------------------\n| Loop to handle term = 17 condition\n|\n| a0 =                          d0 = (2 * bptr [-1]) - bptr [-2]\n| a1 = bptr                     d1 = initial bptr [0]\n| a2 = dpp->                    d2 = updated bptr [0]\n| a3 = dpp->delta << 17         d3 = dpp->weight_A << 17\n| a4 =                          d4 = dpp->weight_B << 17\n| a5 =                          d5 = eptr\n| macsr = 0x20                  acc1 = 0x00 0000 80\n|------------------------------------------------------------------------------\n\nterm_17:\n        move.l  -8(%a1), %d0            | d0 = 2 * bptr [-1] - bptr [-2]\n        add.l   %d0, %d0\n        sub.l   -16(%a1), %d0\n        beq     .L251                   | if zero, skip calculation\n        move.l  %acc1, %acc0\n        asl.l   #4, %d0                 | acc0 = acc1 + (d0 << 4) * weight_A\n        mac.l   %d0, %d3, %acc0\n        move.l  (%a1), %d1\n        beq     .L255\n        eor.l   %d1, %d0                | else compare signs\n        bge     .L256                   | if same, add delta to weight\n        sub.l   %a3, %d3                | else subtract delta from weight\n        sub.l   %a3, %d3                | subtract again instead of branch\n.L256:  add.l   %a3, %d3                | add delta to weight\n\n.L255:  move.l  %acc0, %d2              | d2 = rounded product\n        add.l   %d1, %d2                | update bptr [0] and store\n        move.l  %d2, (%a1)+\n\n.L253:  move.l  -8(%a1), %d0            | d0 = 2 * bptr [-1] - bptr [-2]\n        add.l   %d0, %d0\n        sub.l   -16(%a1), %d0\n        beq     .L257                   | if zero, skip calculations\n        move.l  %acc1, %acc0\n        asl.l   #4, %d0                 | acc0 = acc1 + (d0 << 4) * weight_B\n        mac.l   %d0, %d4, %acc0\n        move.l  (%a1), %d1\n        beq     .L254\n        eor.l   %d1, %d0                | else compare signs\n        bge     .L259                   | if same, add delta to weight\n        sub.l   %a3, %d4                | else subtract delta from weight\n        sub.l   %a3, %d4                | subtract again instead of branch\n.L259:  add.l   %a3, %d4                | add delta to weight\n\n.L254:  move.l  %acc0, %d2              | d2 = rounded product\n        add.l   %d1, %d2                | update bptr [0] and store\n        move.l  %d2, (%a1)+\n\n.L252:  cmp.l   %a1, %d5                | loop if bptr < eptr\n        jbhi    term_17\n        bra     term_17_18_finish       | exit through common path\n\n.L251:  addq.l  #4, %a1                 | update point and jump back into loop\n        bra     .L253\n\n.L257:  addq.l  #4, %a1                 | update point and jump back into loop\n        bra     .L252\n\n|------------------------------------------------------------------------------\n| Loop to handle term = 18 condition\n|\n| a0 =                          d0 = ((3 * bptr [-1]) - bptr [-2]) >> 1\n| a1 = bptr                     d1 = initial bptr [0]\n| a2 = dpp->                    d2 = updated bptr [0]\n| a3 = dpp->delta << 17         d3 = dpp->weight_A << 17\n| a4 =                          d4 = dpp->weight_B << 17\n| a5 =                          d5 = eptr\n| macsr = 0x20                  acc1 = 0x00 0000 80\n|------------------------------------------------------------------------------\n\nterm_18:\n        move.l  -8(%a1), %a0            | d0 = (3 * bptr [-1] - bptr [-2]) >> 1\n        lea     (%a0,%a0.l*2), %a0\n        move.l  %a0, %d0\n        sub.l   -16(%a1), %d0\n        asr.l   #1, %d0\n        beq     .L260\n        move.l  %acc1, %acc0\n        asl.l   #4, %d0                 | acc0 = acc1 + (d0 << 4) * weight_A\n        mac.l   %d0, %d3, %acc0\n        move.l  (%a1), %d1\n        beq     .L266\n        eor.l   %d1, %d0                | else compare signs\n        bge     .L267                   | if same, add delta to weight\n        sub.l   %a3, %d3                | else subtract delta from weight\n        sub.l   %a3, %d3                | subtract again instead of branch\n.L267:  add.l   %a3, %d3                | add delta to weight\n\n.L266:  move.l  %acc0, %d2              | d2 = rounded product\n        add.l   %d1, %d2                | add applied weight to bptr [0], store\n        move.l  %d2, (%a1)+\n\n.L268:  move.l  -8(%a1), %a0            | d0 = (3 * bptr [-1] - bptr [-2]) >> 1\n        lea     (%a0,%a0.l*2), %a0\n        move.l  %a0, %d0\n        sub.l   -16(%a1), %d0\n        asr.l   #1, %d0\n        beq     .L261\n        move.l  %acc1, %acc0\n        asl.l   #4, %d0                 | acc0 = acc1 + (d0 << 4) * weight_B\n        mac.l   %d0, %d4, %acc0\n        move.l  (%a1), %d1\n        beq     .L265\n        eor.l   %d1, %d0                | else compare signs\n        bge     .L270                   | if same, add delta to weight\n        sub.l   %a3, %d4                | else subtract delta from weight\n        sub.l   %a3, %d4                | subtract again instead of branch\n.L270:  add.l   %a3, %d4                | add delta to weight\n\n.L265:  move.l  %acc0, %d2              | d2 = rounded product\n        add.l   %d1, %d2                | add applied weight to bptr [0], store\n        move.l  %d2, (%a1)+\n\n.L269:  cmp.l   %a1, %d5                | loop if bptr < eptr\n        jbhi    term_18\n        bra     term_17_18_finish       | exit through common path\n\n.L260:  addq.l  #4, %a1                 | bump pointer and jump back into loop\n        bra     .L268\n\n.L261:  addq.l  #4, %a1                 | bump pointer and jump back into loop\n        bra     .L269\n\nterm_17_18_finish:\n        move.l  -4(%a1), 40(%a2)        | restore dpp->samples_A [0-1], B [0-1]\n        move.l  -8(%a1), 8(%a2)\n        move.l  -12(%a1), 44(%a2)\n        move.l  -16(%a1), 12(%a2)\n        jbra    finish_up\n\n|------------------------------------------------------------------------------\n| Loop to handle default terms (i.e. 1 - 8)\n|\n| a0 = tptr                     d0 = tptr [0]\n| a1 = bptr                     d1 = initial bptr [0]\n| a2 = dpp->                    d2 = updated bptr [0]\n| a3 = dpp->delta << 17         d3 = dpp->weight_A << 17\n| a4 =                          d4 = dpp->weight_B << 17\n| a5 =                          d5 = eptr\n| macsr = 0x20                  acc1 = 0x00 0000 80\n|------------------------------------------------------------------------------\n\nterm_default:\n        move.w  (%a2), %d0              | a0 = a1 - (dpp->term * 8)\n        ext.l   %d0\n        lsl.l   #3, %d0\n        move.l  %a1, %a0\n        sub.l   %d0, %a0\n\nterm_default_loop:\n        move.l  (%a0)+, %d0             | d0 = tptr [0], skip ahead if zero\n        beq     .L271\n        move.l  %acc1, %acc0\n        asl.l   #4, %d0                 | acc0 = acc1 + (d0 << 4) * weight_A\n        mac.l   %d0, %d3, %acc0\n        move.l  (%a1), %d1\n        beq     .L277\n        eor.l   %d1, %d0                | else compare signs\n        bge     .L278                   | if same, add delta to weight\n        sub.l   %a3, %d3                | else subtract delta from weight\n        sub.l   %a3, %d3                | subtract again instead of branch\n.L278:  add.l   %a3, %d3                | add delta to weight\n\n.L277:  move.l  %acc0, %d2              | d2 = rounded product\n        add.l   %d1, %d2                | add applied weight to bptr [0], store\n        move.l  %d2, (%a1)+\n\n.L275:  move.l  (%a0)+, %d0             | d0 = tptr [0], skip ahead if zero\n        beq     .L272\n        move.l  %acc1, %acc0\n        asl.l   #4, %d0                 | acc0 = acc1 + (d0 << 4) * weight_B\n        mac.l   %d0, %d4, %acc0\n        move.l  (%a1), %d1\n        beq     .L276\n        eor.l   %d1, %d0                | else compare signs\n        bge     .L281                   | if same, add delta to weight\n        sub.l   %a3, %d4                | else subtract delta from weight\n        sub.l   %a3, %d4                | subtract again instead of branch\n.L281:  add.l   %a3, %d4                | add delta to weight\n\n.L276:  move.l  %acc0, %d2              | d2 = rounded product\n        add.l   %d1, %d2                | add applied weight to bptr [0], store\n        move.l  %d2, (%a1)+\n\n.L274:  cmp.l   %a1, %d5                | loop back if bptr < eptr\n        jbhi    term_default_loop\n        move.w  (%a2), %d0              | d0 = term - 1\n        moveq.l #8, %d1                 | d1 = loop counter\n\n.L323:  subq.l  #1, %d0                 | back up & mask index\n        and.l   #7, %d0\n        move.l  -(%a1), 40(%a2,%d0.l*4) | store dpp->samples_B [d0]\n        move.l  -(%a1), 8(%a2,%d0.l*4)  | store dpp->samples_A [d0]\n        subq.l  #1, %d1                 | loop on count\n        jbne    .L323\n        jbra    finish_up\n\n.L271:  addq.l  #4, %a1                 | bump pointer and jump back into loop\n        bra     .L275\n\n.L272:  addq.l  #4, %a1                 | bump pointer and jump back into loop\n        bra     .L274\n\n\n|------------------------------------------------------------------------------\n| Loop to handle term = -1 condition\n|\n| a0 =                          d0 = decorrelation sample\n| a1 = bptr                     d1 = initial bptr [0]\n| a2 = dpp->                    d2 = updated bptr [0]\n| a3 = dpp->delta << 17         d3 = dpp->weight_A << 17\n| a4 =                          d4 = dpp->weight_B << 17\n| a5 =                          d5 = eptr\n| a6 =                          d6 = 1024 << 17\n| a7 =                          d7 = -1024 << 17\n| macsr = 0x20                  acc1 = 0x00 0000 80\n|------------------------------------------------------------------------------\n\nterm_minus_1:\n        move.l  -4(%a1), %d0            | d0 = bptr [-1]\n        beq     .L402\n        move.l  %acc1, %acc0\n        asl.l   #4, %d0                 | acc0 = acc1 + ((d0 << 4) * weight_A)\n        mac.l   %d0, %d3, %acc0\n        move.l  (%a1), %d1\n        beq     .L405\n        eor.l   %d1, %d0                | else compare signs\n        bge     .L404                   | if same, add delta to weight\n        sub.l   %a3, %d3                | else subtract delta from weight\n        cmp.l   %d7, %d3                | check for negative clip limit\n        bge     .L405\n        move.l  %d7, %d3\n        bra     .L405\n\n.L404:  add.l   %a3, %d3                | add delta to weight\n        cmp.l   %d6, %d3                | check for positive clip limit\n        ble     .L405\n        move.l  %d6, %d3\n\n.L405:  move.l  %acc0, %d0              | d2 = rounded product\n        add.l   %d1, %d0                | add applied weight to bptr [0], store\n        move.l  %d0, (%a1)+\n        beq     .L401\n\n.L410:  move.l  %acc1, %acc0\n        asl.l   #4, %d0                 | acc0 = acc1 + ((d0 << 4) * weight_B)\n        mac.l   %d0, %d4, %acc0\n        move.l  (%a1), %d1\n        beq     .L403\n        eor.l   %d1, %d0                | else compare signs\n        bge     .L407                   | if same, add delta to weight\n        sub.l   %a3, %d4                | else subtract delta from weight\n        cmp.l   %d7, %d4                | check for negative clip limit\n        bge     .L403\n        move.l  %d7, %d4\n        bra     .L403\n\n.L407:  add.l   %a3, %d4                | add delta to weight\n        cmp.l   %d6, %d4                | check for positive clip limit\n        ble     .L403\n        move.l  %d6, %d4\n\n.L403:  move.l  %acc0, %d2              | d2 = rounded product\n        add.l   %d1, %d2                | add applied weight to bptr [1], store\n        move.l  %d2, (%a1)+\n\n.L411:  cmp.l   %a1, %d5                | loop back if bptr < eptr\n        jbhi    term_minus_1\n        move.l  -4(%a1), 8(%a2)         | dpp->samples_A [0] = bptr [-1]\n        jbra    finish_up\n\n.L402:  move.l  (%a1)+, %d0\n        bne     .L410\n\n.L401:  addq.l  #4, %a1\n        bra     .L411\n\n\n|------------------------------------------------------------------------------\n| Loop to handle term = -2 condition\n|\n| a0 =                          d0 = decorrelation sample\n| a1 = bptr                     d1 = initial bptr [0]\n| a2 = dpp->                    d2 = updated bptr [0]\n| a3 = dpp->delta << 17         d3 = dpp->weight_A << 17\n| a4 =                          d4 = dpp->weight_B << 17\n| a5 =                          d5 = eptr\n| a6 =                          d6 = 1024 << 17\n| a7 =                          d7 = -1024 << 17\n| macsr = 0x20                  acc1 = 0x00 0000 80\n|------------------------------------------------------------------------------\n\nterm_minus_2:\n        move.l  -8(%a1), %d0            | d0 = bptr [-2]\n        beq     .L511\n        move.l  %acc1, %acc0\n        asl.l   #4, %d0                 | acc0 = acc1 + ((d0 << 4) * weight_B)\n        mac.l   %d0, %d4, %acc0\n        move.l  4(%a1), %d1\n        beq     .L505\n        eor.l   %d1, %d0                | else compare signs\n        bge     .L504                   | if same, add delta to weight\n        sub.l   %a3, %d4                | else subtract delta from weight\n        cmp.l   %d7, %d4                | ckeck for negative clip limit\n        bge     .L505\n        move.l  %d7, %d4\n        bra     .L505\n\n.L504:  add.l   %a3, %d4                | add delta to weight\n        cmp.l   %d6, %d4                | check for positive clip limit\n        ble     .L505\n        move.l  %d6, %d4\n\n.L505:  move.l  %acc0, %d0              | d2 = rounded product\n        add.l   %d1, %d0                | add applied weight to bptr [0], store\n        move.l  %d0, 4(%a1)\n        beq     .L512\n\n.L510:  move.l  %acc1, %acc0\n        asl.l   #4, %d0                 | acc0 = acc1 + ((d0 << 4) * weight_A)\n        mac.l   %d0, %d3, %acc0\n        move.l  (%a1), %d1\n        beq     .L503\n        eor.l   %d1, %d0                | else compare signs\n        bge     .L507                   | if same, add delta to weight\n        sub.l   %a3, %d3                | else subtract delta from weight\n        cmp.l   %d7, %d3                | check for negative clip limit\n        bge     .L503\n        move.l  %d7, %d3\n        bra     .L503\n\n.L507:  add.l   %a3, %d3                | add delta to weight\n        cmp.l   %d6, %d3                | check for negative clip limit\n        ble     .L503\n        move.l  %d6, %d3\n\n.L503:  move.l  %acc0, %d2              | d2 = rounded product\n        add.l   %d1, %d2                | add applied weight to bptr [1], store\n        move.l  %d2, (%a1)\n\n.L512:  addq.l  #8, %a1\n        cmp.l   %a1, %d5                | loop if bptr < eptr\n        jbhi    term_minus_2\n        move.l  -8(%a1), 40(%a2)        | dpp->samples_B [0] = bptr [-4]\n        jbra    finish_up\n\n.L511:  move.l  4(%a1), %d0\n        beq     .L512\n        bra     .L510\n\n\n|------------------------------------------------------------------------------\n| Loop to handle term = -3 condition\n|\n| a0 =                          d0 = decorrelation sample\n| a1 = bptr                     d1 = initial bptr [0]\n| a2 = dpp->                    d2 = updated bptr [0]\n| a3 = dpp->delta << 17         d3 = dpp->weight_A << 17\n| a4 =                          d4 = dpp->weight_B << 17\n| a5 =                          d5 = eptr\n| a6 =                          d6 = 1024 << 17\n| a7 =                          d7 = -1024 << 17\n| macsr = 0x20                  acc1 = 0x00 0000 80\n|------------------------------------------------------------------------------\n\nterm_minus_3:\n        move.l  -4(%a1), %d0            | d0 = bptr [-1]\n        beq     .L301\n        move.l  %acc1, %acc0\n        asl.l   #4, %d0                 | acc0 = acc1 + ((d0 << 4) * weight_A)\n        mac.l   %d0, %d3, %acc0\n        move.l  (%a1), %d1\n        beq     .L320\n        eor.l   %d1, %d0                | else compare signs\n        bge     .L319                   | if same, add delta to weight\n        sub.l   %a3, %d3                | else subtract delta from weight\n        cmp.l   %d7, %d3                | check for negative clip limit\n        bge     .L320\n        move.l  %d7, %d3\n        bra     .L320\n\n.L319:  add.l   %a3, %d3                | add delta to weight\n        cmp.l   %d6, %d3                | check for positive clip limit\n        ble     .L320\n        move.l  %d6, %d3\n\n.L320:  move.l  %acc0, %d2              | d2 = rounded product\n        add.l   %d1, %d2                | add applied weight to bptr [0], store\n        move.l  %d2, (%a1)+\n\n.L330:  move.l  -12(%a1), %d0           | d0 = bptr [-2]\n        beq     .L302\n        move.l  %acc1, %acc0\n        asl.l   #4, %d0                 | acc0 = acc1 + ((d0 << 4) * weight_B)\n        mac.l   %d0, %d4, %acc0\n        move.l  (%a1), %d1\n        beq     .L318\n        eor.l   %d1, %d0                | else compare signs\n        bge     .L322                   | if same, add delta to weight\n        sub.l   %a3, %d4                | else subtract delta from weight\n        cmp.l   %d7, %d4                | check for negative clip limit\n        bge     .L318\n        move.l  %d7, %d4\n        bra     .L318\n\n.L322:  add.l   %a3, %d4                | add delta to weight\n        cmp.l   %d6, %d4                | check for positive clip limit\n        ble     .L318\n        move.l  %d6, %d4\n\n.L318:  move.l  %acc0, %d2              | d2 = rounded product\n        add.l   %d1, %d2                | add applied weight to bptr [1], store\n        move.l  %d2, (%a1)+\n\n.L331:  cmp.l   %a1, %d5                | bptr, eptr\n        jbhi    term_minus_3\n        move.l  -4(%a1), 8(%a2)         | dpp->samples_A [0] = bptr [-1]\n        move.l  -8(%a1), 40(%a2)        | dpp->samples_B [0] = bptr [-2]\n        jbra    finish_up\n\n.L301:  addq.l  #4, %a1\n        bra     .L330\n\n.L302:  addq.l  #4, %a1\n        bra     .L331\n\n| finish and return\n\nfinish_up:\n        moveq.l #17, %d0\n        asr.l   %d0, %d3\n        asr.l   %d0, %d4\n        move.w  %d3, 4(%a2)     | weight_A, dpp->weight_A\n        move.w  %d4, 6(%a2)     | weight_B, dpp->weight_B\n\n        clr.l   %d0             | clear up EMAC\n        move.l  %d0, %acc0\n        move.l  %d0, %acc1\n\nreturn_only:\n        movem.l (%sp), %d2-%d7/%a2-%a6\n        lea     (44,%sp), %sp\n        rts\n"
  },
  {
    "path": "src/engine/external/wavpack/float.c",
    "content": "////////////////////////////////////////////////////////////////////////////\n//                           **** WAVPACK ****                            //\n//                  Hybrid Lossless Wavefile Compressor                   //\n//              Copyright (c) 1998 - 2006 Conifer Software.               //\n//                          All Rights Reserved.                          //\n//      Distributed under the BSD Software License (see license.txt)      //\n////////////////////////////////////////////////////////////////////////////\n\n// float.c\n\n#include \"wavpack.h\"\n\nint read_float_info (WavpackStream *wps, WavpackMetadata *wpmd)\n{\n    int bytecnt = wpmd->byte_length;\n    char *byteptr = wpmd->data;\n\n    if (bytecnt != 4)\n        return FALSE;\n\n    wps->float_flags = *byteptr++;\n    wps->float_shift = *byteptr++;\n    wps->float_max_exp = *byteptr++;\n    wps->float_norm_exp = *byteptr;\n    return TRUE;\n}\n\nvoid float_values (WavpackStream *wps, int32_t *values, int32_t num_values)\n{\n    int shift = wps->float_max_exp - wps->float_norm_exp + wps->float_shift;\n\n    if (shift > 32)\n        shift = 32;\n    else if (shift < -32)\n        shift = -32;\n\n    while (num_values--) {\n        if (shift > 0)\n            *values <<= shift;\n        else if (shift < 0)\n            *values >>= -shift;\n\n        if (*values > 8388607L)\n            *values = 8388607L;\n        else if (*values < -8388608L)\n            *values = -8388608L;\n\n        values++;\n    }\n}\n"
  },
  {
    "path": "src/engine/external/wavpack/license.txt",
    "content": "               Copyright (c) 1998 - 2006 Conifer Software\n                          All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n    * Redistributions of source code must retain the above copyright notice,\n      this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright notice,\n      this list of conditions and the following disclaimer in the\n      documentation and/or other materials provided with the distribution.\n    * Neither the name of Conifer Software nor the names of its contributors\n      may be used to endorse or promote products derived from this software\n      without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
  },
  {
    "path": "src/engine/external/wavpack/metadata.c",
    "content": "////////////////////////////////////////////////////////////////////////////\n//                           **** WAVPACK ****                            //\n//                  Hybrid Lossless Wavefile Compressor                   //\n//              Copyright (c) 1998 - 2006 Conifer Software.               //\n//                          All Rights Reserved.                          //\n//      Distributed under the BSD Software License (see license.txt)      //\n////////////////////////////////////////////////////////////////////////////\n\n// metadata.c\n\n// This module handles the metadata structure introduced in WavPack 4.0\n\n#include \"wavpack.h\"\n\nint read_metadata_buff (WavpackContext *wpc, WavpackMetadata *wpmd)\n{\n    uchar tchar;\n\n    if (!wpc->infile (&wpmd->id, 1) || !wpc->infile (&tchar, 1))\n        return FALSE;\n\n    wpmd->byte_length = tchar << 1;\n\n    if (wpmd->id & ID_LARGE) {\n        wpmd->id &= ~ID_LARGE;\n\n        if (!wpc->infile (&tchar, 1))\n            return FALSE;\n\n        wpmd->byte_length += (int32_t) tchar << 9; \n\n        if (!wpc->infile (&tchar, 1))\n            return FALSE;\n\n        wpmd->byte_length += (int32_t) tchar << 17;\n    }\n\n    if (wpmd->id & ID_ODD_SIZE) {\n        wpmd->id &= ~ID_ODD_SIZE;\n        wpmd->byte_length--;\n    }\n\n    if (wpmd->byte_length && wpmd->byte_length <= sizeof (wpc->read_buffer)) {\n        uint32_t bytes_to_read = wpmd->byte_length + (wpmd->byte_length & 1);\n\n        if (wpc->infile (wpc->read_buffer, bytes_to_read) != (int32_t) bytes_to_read) {\n            wpmd->data = NULL;\n            return FALSE;\n        }\n\n        wpmd->data = wpc->read_buffer;\n    }\n    else\n        wpmd->data = NULL;\n\n    return TRUE;\n}\n\nint process_metadata (WavpackContext *wpc, WavpackMetadata *wpmd)\n{\n    WavpackStream *wps = &wpc->stream;\n\n    switch (wpmd->id) {\n        case ID_DUMMY:\n            return TRUE;\n\n        case ID_DECORR_TERMS:\n            return read_decorr_terms (wps, wpmd);\n\n        case ID_DECORR_WEIGHTS:\n            return read_decorr_weights (wps, wpmd);\n\n        case ID_DECORR_SAMPLES:\n            return read_decorr_samples (wps, wpmd);\n\n        case ID_ENTROPY_VARS:\n            return read_entropy_vars (wps, wpmd);\n\n        case ID_HYBRID_PROFILE:\n            return read_hybrid_profile (wps, wpmd);\n\n        case ID_FLOAT_INFO:\n            return read_float_info (wps, wpmd);\n\n        case ID_INT32_INFO:\n            return read_int32_info (wps, wpmd);\n\n        case ID_CHANNEL_INFO:\n            return read_channel_info (wpc, wpmd);\n\n        case ID_CONFIG_BLOCK:\n            return read_config_info (wpc, wpmd);\n\n        case ID_WV_BITSTREAM:\n            return init_wv_bitstream (wpc, wpmd);\n\n        case ID_SHAPING_WEIGHTS:\n        case ID_WVC_BITSTREAM:\n        case ID_WVX_BITSTREAM:\n            return TRUE;\n\n        default:\n            return (wpmd->id & ID_OPTIONAL_DATA) ? TRUE : FALSE;\n    }\n}\n"
  },
  {
    "path": "src/engine/external/wavpack/readme.txt",
    "content": "////////////////////////////////////////////////////////////////////////////\n//                           **** WAVPACK ****                            //\n//                  Hybrid Lossless Wavefile Compressor                   //\n//              Copyright (c) 1998 - 2006 Conifer Software.               //\n//                          All Rights Reserved.                          //\n//      Distributed under the BSD Software License (see license.txt)      //\n////////////////////////////////////////////////////////////////////////////\n\nThis package contains a tiny version of the WavPack 4.40 decoder that might\nbe used in a \"resource limited\" CPU environment or form the basis for a\nhardware decoding implementation. It is packaged with a demo command-line\nprogram that accepts a WavPack audio file on stdin and outputs a RIFF wav\nfile to stdout. The program is standard C, and a win32 executable is\nincluded which was compiled under MS Visual C++ 6.0 using this command:\n\ncl /O1 /DWIN32 wvfilter.c wputils.c unpack.c float.c metadata.c words.c bits.c\n\nWavPack data is read with a stream reading callback. No direct seeking is\nprovided for, but it is possible to start decoding anywhere in a WavPack\nstream. In this case, WavPack will be able to provide the sample-accurate\nposition when it synchs with the data and begins decoding. The WIN32 macro\nis used for Windows to force the stdin and stdout streams to be binary mode.\n\nCompared to the previous version, this library has been optimized somewhat\nfor improved performance in exchange for slightly larger code size. The\nlibrary also now includes hand-optimized assembly language versions of the\ndecorrelation functions for both the ColdFire (w/EMAC) and ARM processors.\n\nFor demonstration purposes this uses a single static copy of the\nWavpackContext structure, so obviously it cannot be used for more than one\nfile at a time. Also, this decoder will not handle \"correction\" files, plays\nonly the first two channels of multi-channel files, and is limited in\nresolution in some large integer or floating point files (but always\nprovides at least 24 bits of resolution). It also will not accept WavPack\nfiles from before version 4.0.\n\nThe previous version of this library would handle float files by returning\n32-bit floating-point data (even though no floating point math was used).\nBecause this library would normally be used for simply playing WavPack\nfiles where lossless performance (beyond 24-bits) is not relevant, I have\nchanged this behavior. Now, these files will generate clipped 24-bit data.\nThe MODE_FLOAT flag will still be returned by WavpackGetMode(), but the\nBitsPerSample and BytesPerSample queries will be 24 and 3, respectfully.\nWhat this means is that an application that can handle 24-bit data will\nnow be able to handle floating point data (assuming that the MODE_FLOAT\nflag is ignored).\n\nTo make this code viable on the greatest number of hardware platforms, the\nfollowing are true:\n\n   speed is about 5x realtime on an AMD K6 300 MHz\n      (\"high\" mode 16/44 stereo; normal mode is about twice that fast)\n\n   no floating-point math required; just 32b * 32b = 32b int multiply\n\n   large data areas are static and less than 4K total\n   executable code and tables are less than 40K\n   no malloc / free usage\n\nTo maintain compatibility on various platforms, the following conventions\nare used:\n\n   a \"char\" must be exactly 8-bits\n   a \"short\" must be exactly 16-bits\n   an \"int\" must be at least 16-bits, but may be larger\n   the \"long\" type is not used to avoid problems with 64-bit compilers\n\nQuestions or comments should be directed to david@wavpack.com\n"
  },
  {
    "path": "src/engine/external/wavpack/unpack.c",
    "content": "////////////////////////////////////////////////////////////////////////////\n//                           **** WAVPACK ****                            //\n//                  Hybrid Lossless Wavefile Compressor                   //\n//              Copyright (c) 1998 - 2006 Conifer Software.               //\n//                          All Rights Reserved.                          //\n//      Distributed under the BSD Software License (see license.txt)      //\n////////////////////////////////////////////////////////////////////////////\n\n// unpack.c\n\n// This module actually handles the decompression of the audio data, except\n// for the entropy decoding which is handled by the words.c module. For\n// maximum efficiency, the conversion is isolated to tight loops that handle\n// an entire buffer.\n\n#include \"wavpack.h\"\n\n#include <stdlib.h>\n#include <string.h>\n\n#define LOSSY_MUTE\n\n///////////////////////////// executable code ////////////////////////////////\n\n// This function initializes everything required to unpack a WavPack block\n// and must be called before unpack_samples() is called to obtain audio data.\n// It is assumed that the WavpackHeader has been read into the wps->wphdr\n// (in the current WavpackStream). This is where all the metadata blocks are\n// scanned up to the one containing the audio bitstream.\n\nint unpack_init (WavpackContext *wpc)\n{\n    WavpackStream *wps = &wpc->stream;\n    WavpackMetadata wpmd;\n\n    if (wps->wphdr.block_samples && wps->wphdr.block_index != (uint32_t) -1)\n        wps->sample_index = wps->wphdr.block_index;\n\n    wps->mute_error = FALSE;\n    wps->crc = 0xffffffff;\n    CLEAR (wps->wvbits);\n    CLEAR (wps->decorr_passes);\n    CLEAR (wps->w);\n\n    while (read_metadata_buff (wpc, &wpmd)) {\n        if (!process_metadata (wpc, &wpmd)) {\n            strcpy (wpc->error_message, \"invalid metadata!\");\n            return FALSE;\n        }\n\n        if (wpmd.id == ID_WV_BITSTREAM)\n            break;\n    }\n\n    if (wps->wphdr.block_samples && !bs_is_open (&wps->wvbits)) {\n        strcpy (wpc->error_message, \"invalid WavPack file!\");\n        return FALSE;\n    }\n\n    if (wps->wphdr.block_samples) {\n        if ((wps->wphdr.flags & INT32_DATA) && wps->int32_sent_bits)\n            wpc->lossy_blocks = TRUE;\n\n        if ((wps->wphdr.flags & FLOAT_DATA) &&\n            wps->float_flags & (FLOAT_EXCEPTIONS | FLOAT_ZEROS_SENT | FLOAT_SHIFT_SENT | FLOAT_SHIFT_SAME))\n                wpc->lossy_blocks = TRUE;\n    }\n\n    return TRUE;\n}\n\n// This function initialzes the main bitstream for audio samples, which must\n// be in the \"wv\" file.\n\nint init_wv_bitstream (WavpackContext *wpc, WavpackMetadata *wpmd)\n{\n    WavpackStream *wps = &wpc->stream;\n\n    if (wpmd->data)\n        bs_open_read (&wps->wvbits, wpmd->data, (unsigned char *) wpmd->data + wpmd->byte_length, NULL, 0);\n    else if (wpmd->byte_length)\n        bs_open_read (&wps->wvbits, wpc->read_buffer, wpc->read_buffer + sizeof (wpc->read_buffer),\n            wpc->infile, wpmd->byte_length + (wpmd->byte_length & 1));\n\n    return TRUE;\n}\n\n// Read decorrelation terms from specified metadata block into the\n// decorr_passes array. The terms range from -3 to 8, plus 17 & 18;\n// other values are reserved and generate errors for now. The delta\n// ranges from 0 to 7 with all values valid. Note that the terms are\n// stored in the opposite order in the decorr_passes array compared\n// to packing.\n\nint read_decorr_terms (WavpackStream *wps, WavpackMetadata *wpmd)\n{\n    int termcnt = wpmd->byte_length;\n    uchar *byteptr = wpmd->data;\n    struct decorr_pass *dpp;\n\n    if (termcnt > MAX_NTERMS)\n        return FALSE;\n\n    wps->num_terms = termcnt;\n\n    for (dpp = wps->decorr_passes + termcnt - 1; termcnt--; dpp--) {\n        dpp->term = (int)(*byteptr & 0x1f) - 5;\n        dpp->delta = (*byteptr++ >> 5) & 0x7;\n\n        if (!dpp->term || dpp->term < -3 || (dpp->term > MAX_TERM && dpp->term < 17) || dpp->term > 18)\n            return FALSE;\n    }\n\n    return TRUE;\n}\n\n// Read decorrelation weights from specified metadata block into the\n// decorr_passes array. The weights range +/-1024, but are rounded and\n// truncated to fit in signed chars for metadata storage. Weights are\n// separate for the two channels and are specified from the \"last\" term\n// (first during encode). Unspecified weights are set to zero.\n\nint read_decorr_weights (WavpackStream *wps, WavpackMetadata *wpmd)\n{\n    int termcnt = wpmd->byte_length, tcount;\n    signed char *byteptr = wpmd->data;\n    struct decorr_pass *dpp;\n\n    if (!(wps->wphdr.flags & MONO_DATA))\n        termcnt /= 2;\n\n    if (termcnt > wps->num_terms)\n        return FALSE;\n\n    for (tcount = wps->num_terms, dpp = wps->decorr_passes; tcount--; dpp++)\n        dpp->weight_A = dpp->weight_B = 0;\n\n    while (--dpp >= wps->decorr_passes && termcnt--) {\n        dpp->weight_A = restore_weight (*byteptr++);\n\n        if (!(wps->wphdr.flags & MONO_DATA))\n            dpp->weight_B = restore_weight (*byteptr++);\n    }\n\n    return TRUE;\n}\n\n// Read decorrelation samples from specified metadata block into the\n// decorr_passes array. The samples are signed 32-bit values, but are\n// converted to signed log2 values for storage in metadata. Values are\n// stored for both channels and are specified from the \"last\" term\n// (first during encode) with unspecified samples set to zero. The\n// number of samples stored varies with the actual term value, so\n// those must obviously come first in the metadata.\n\nint read_decorr_samples (WavpackStream *wps, WavpackMetadata *wpmd)\n{\n    uchar *byteptr = wpmd->data;\n    uchar *endptr = byteptr + wpmd->byte_length;\n    struct decorr_pass *dpp;\n    int tcount;\n\n    for (tcount = wps->num_terms, dpp = wps->decorr_passes; tcount--; dpp++) {\n        CLEAR (dpp->samples_A);\n        CLEAR (dpp->samples_B);\n    }\n\n    if (wps->wphdr.version == 0x402 && (wps->wphdr.flags & HYBRID_FLAG)) {\n        byteptr += 2;\n\n        if (!(wps->wphdr.flags & MONO_DATA))\n            byteptr += 2;\n    }\n\n    while (dpp-- > wps->decorr_passes && byteptr < endptr)\n        if (dpp->term > MAX_TERM) {\n            dpp->samples_A [0] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8)));\n            dpp->samples_A [1] = exp2s ((short)(byteptr [2] + (byteptr [3] << 8)));\n            byteptr += 4;\n\n            if (!(wps->wphdr.flags & MONO_DATA)) {\n                dpp->samples_B [0] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8)));\n                dpp->samples_B [1] = exp2s ((short)(byteptr [2] + (byteptr [3] << 8)));\n                byteptr += 4;\n            }\n        }\n        else if (dpp->term < 0) {\n            dpp->samples_A [0] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8)));\n            dpp->samples_B [0] = exp2s ((short)(byteptr [2] + (byteptr [3] << 8)));\n            byteptr += 4;\n        }\n        else {\n            int m = 0, cnt = dpp->term;\n\n            while (cnt--) {\n                dpp->samples_A [m] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8)));\n                byteptr += 2;\n\n                if (!(wps->wphdr.flags & MONO_DATA)) {\n                    dpp->samples_B [m] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8)));\n                    byteptr += 2;\n                }\n\n                m++;\n            }\n        }\n\n    return byteptr == endptr;\n}\n\n// Read the int32 data from the specified metadata into the specified stream.\n// This data is used for integer data that has more than 24 bits of magnitude\n// or, in some cases, used to eliminate redundant bits from any audio stream.\n\nint read_int32_info (WavpackStream *wps, WavpackMetadata *wpmd)\n{\n    int bytecnt = wpmd->byte_length;\n    char *byteptr = wpmd->data;\n\n    if (bytecnt != 4)\n        return FALSE;\n\n    wps->int32_sent_bits = *byteptr++;\n    wps->int32_zeros = *byteptr++;\n    wps->int32_ones = *byteptr++;\n    wps->int32_dups = *byteptr;\n    return TRUE;\n}\n\n// Read multichannel information from metadata. The first byte is the total\n// number of channels and the following bytes represent the channel_mask\n// as described for Microsoft WAVEFORMATEX.\n\nint read_channel_info (WavpackContext *wpc, WavpackMetadata *wpmd)\n{\n    int bytecnt = wpmd->byte_length, shift = 0;\n    char *byteptr = wpmd->data;\n    uint32_t mask = 0;\n\n    if (!bytecnt || bytecnt > 5)\n        return FALSE;\n\n    wpc->config.num_channels = *byteptr++;\n\n    while (--bytecnt) {\n        mask |= (uint32_t) *byteptr++ << shift;\n        shift += 8;\n    }\n\n    wpc->config.channel_mask = mask;\n    return TRUE;\n}\n\n// Read configuration information from metadata.\n\nint read_config_info (WavpackContext *wpc, WavpackMetadata *wpmd)\n{\n    int bytecnt = wpmd->byte_length;\n    uchar *byteptr = wpmd->data;\n\n    if (bytecnt >= 3) {\n        wpc->config.flags &= 0xff;\n        wpc->config.flags |= (int32_t) *byteptr++ << 8;\n        wpc->config.flags |= (int32_t) *byteptr++ << 16;\n        wpc->config.flags |= (int32_t) *byteptr << 24;\n    }\n\n    return TRUE;\n}\n\n// This monster actually unpacks the WavPack bitstream(s) into the specified\n// buffer as 32-bit integers or floats (depending on orignal data). Lossy\n// samples will be clipped to their original limits (i.e. 8-bit samples are\n// clipped to -128/+127) but are still returned in int32_ts. It is up to the\n// caller to potentially reformat this for the final output including any\n// multichannel distribution, block alignment or endian compensation. The\n// function unpack_init() must have been called and the entire WavPack block\n// must still be visible (although wps->blockbuff will not be accessed again).\n// For maximum clarity, the function is broken up into segments that handle\n// various modes. This makes for a few extra infrequent flag checks, but\n// makes the code easier to follow because the nesting does not become so\n// deep. For maximum efficiency, the conversion is isolated to tight loops\n// that handle an entire buffer. The function returns the total number of\n// samples unpacked, which can be less than the number requested if an error\n// occurs or the end of the block is reached.\n\n#if defined(CPU_COLDFIRE) && !defined(SIMULATOR)\nextern void decorr_stereo_pass_cont_mcf5249 (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count);\n#elif defined(CPU_ARM) && !defined(SIMULATOR)\nextern void decorr_stereo_pass_cont_arm (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count);\nextern void decorr_stereo_pass_cont_arml (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count);\n#else\nstatic void decorr_stereo_pass_cont (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count);\n#endif\n\nstatic void decorr_mono_pass (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count);\nstatic void decorr_stereo_pass (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count);\nstatic void fixup_samples (WavpackStream *wps, int32_t *buffer, uint32_t sample_count);\n\nint32_t unpack_samples (WavpackContext *wpc, int32_t *buffer, uint32_t sample_count)\n{\n    WavpackStream *wps = &wpc->stream;\n    uint32_t flags = wps->wphdr.flags, crc = wps->crc, i;\n    int32_t mute_limit = (1L << ((flags & MAG_MASK) >> MAG_LSB)) + 2;\n    struct decorr_pass *dpp;\n    int32_t *bptr, *eptr;\n    int tcount;\n\n    if (wps->sample_index + sample_count > wps->wphdr.block_index + wps->wphdr.block_samples)\n        sample_count = wps->wphdr.block_index + wps->wphdr.block_samples - wps->sample_index;\n\n    if (wps->mute_error) {\n        memset (buffer, 0, sample_count * (flags & MONO_FLAG ? 4 : 8));\n        wps->sample_index += sample_count;\n        return sample_count;\n    }\n\n    if (flags & HYBRID_FLAG)\n        mute_limit *= 2;\n\n    ///////////////////// handle version 4 mono data /////////////////////////\n\n    if (flags & MONO_DATA) {\n        eptr = buffer + sample_count;\n        i = get_words (buffer, sample_count, flags, &wps->w, &wps->wvbits);\n\n        for (tcount = wps->num_terms, dpp = wps->decorr_passes; tcount--; dpp++)\n            decorr_mono_pass (dpp, buffer, sample_count);\n\n        for (bptr = buffer; bptr < eptr; ++bptr) {\n            if (labs (bptr [0]) > mute_limit) {\n                i = bptr - buffer;\n                break;\n            }\n\n            crc = crc * 3 + bptr [0];\n        }\n    }\n\n    //////////////////// handle version 4 stereo data ////////////////////////\n\n    else {\n        eptr = buffer + (sample_count * 2);\n        i = get_words (buffer, sample_count, flags, &wps->w, &wps->wvbits);\n\n        if (sample_count < 16)\n            for (tcount = wps->num_terms, dpp = wps->decorr_passes; tcount--; dpp++)\n                decorr_stereo_pass (dpp, buffer, sample_count);\n        else\n            for (tcount = wps->num_terms, dpp = wps->decorr_passes; tcount--; dpp++) {\n                decorr_stereo_pass (dpp, buffer, 8);\n#if defined(CPU_COLDFIRE) && !defined(SIMULATOR)\n                decorr_stereo_pass_cont_mcf5249 (dpp, buffer + 16, sample_count - 8);\n#elif defined(CPU_ARM) && !defined(SIMULATOR)\n                if (((flags & MAG_MASK) >> MAG_LSB) > 15)\n                    decorr_stereo_pass_cont_arml (dpp, buffer + 16, sample_count - 8);\n                else\n                    decorr_stereo_pass_cont_arm (dpp, buffer + 16, sample_count - 8);\n#else\n                decorr_stereo_pass_cont (dpp, buffer + 16, sample_count - 8);\n#endif\n            }\n\n        if (flags & JOINT_STEREO)\n            for (bptr = buffer; bptr < eptr; bptr += 2) {\n                bptr [0] += (bptr [1] -= (bptr [0] >> 1));\n\n                if (labs (bptr [0]) > mute_limit || labs (bptr [1]) > mute_limit) {\n                    i = (bptr - buffer) / 2;\n                    break;\n                }\n\n                crc = (crc * 3 + bptr [0]) * 3 + bptr [1];\n            }\n        else\n            for (bptr = buffer; bptr < eptr; bptr += 2) {\n                if (labs (bptr [0]) > mute_limit || labs (bptr [1]) > mute_limit) {\n                    i = (bptr - buffer) / 2;\n                    break;\n                }\n\n                crc = (crc * 3 + bptr [0]) * 3 + bptr [1];\n            }\n    }\n\n    if (i != sample_count) {\n        memset (buffer, 0, sample_count * (flags & MONO_FLAG ? 4 : 8));\n        wps->mute_error = TRUE;\n        i = sample_count;\n    }\n\n    fixup_samples (wps, buffer, i);\n\n    if (flags & FALSE_STEREO) {\n        int32_t *dptr = buffer + i * 2;\n        int32_t *sptr = buffer + i;\n        int32_t c = i;\n\n        while (c--) {\n            *--dptr = *--sptr;\n            *--dptr = *sptr;\n        }\n    }\n\n    wps->sample_index += i;\n    wps->crc = crc;\n\n    return i;\n}\n\nstatic void decorr_stereo_pass (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count)\n{\n    int32_t delta = dpp->delta, weight_A = dpp->weight_A, weight_B = dpp->weight_B;\n    int32_t *bptr, *eptr = buffer + (sample_count * 2), sam_A, sam_B;\n    int m, k;\n\n    switch (dpp->term) {\n\n        case 17:\n            for (bptr = buffer; bptr < eptr; bptr += 2) {\n                sam_A = 2 * dpp->samples_A [0] - dpp->samples_A [1];\n                dpp->samples_A [1] = dpp->samples_A [0];\n                dpp->samples_A [0] = apply_weight (weight_A, sam_A) + bptr [0];\n                update_weight (weight_A, delta, sam_A, bptr [0]);\n                bptr [0] = dpp->samples_A [0];\n\n                sam_A = 2 * dpp->samples_B [0] - dpp->samples_B [1];\n                dpp->samples_B [1] = dpp->samples_B [0];\n                dpp->samples_B [0] = apply_weight (weight_B, sam_A) + bptr [1];\n                update_weight (weight_B, delta, sam_A, bptr [1]);\n                bptr [1] = dpp->samples_B [0];\n            }\n\n            break;\n\n        case 18:\n            for (bptr = buffer; bptr < eptr; bptr += 2) {\n                sam_A = (3 * dpp->samples_A [0] - dpp->samples_A [1]) >> 1;\n                dpp->samples_A [1] = dpp->samples_A [0];\n                dpp->samples_A [0] = apply_weight (weight_A, sam_A) + bptr [0];\n                update_weight (weight_A, delta, sam_A, bptr [0]);\n                bptr [0] = dpp->samples_A [0];\n\n                sam_A = (3 * dpp->samples_B [0] - dpp->samples_B [1]) >> 1;\n                dpp->samples_B [1] = dpp->samples_B [0];\n                dpp->samples_B [0] = apply_weight (weight_B, sam_A) + bptr [1];\n                update_weight (weight_B, delta, sam_A, bptr [1]);\n                bptr [1] = dpp->samples_B [0];\n            }\n\n            break;\n\n        default:\n            for (m = 0, k = dpp->term & (MAX_TERM - 1), bptr = buffer; bptr < eptr; bptr += 2) {\n                sam_A = dpp->samples_A [m];\n                dpp->samples_A [k] = apply_weight (weight_A, sam_A) + bptr [0];\n                update_weight (weight_A, delta, sam_A, bptr [0]);\n                bptr [0] = dpp->samples_A [k];\n\n                sam_A = dpp->samples_B [m];\n                dpp->samples_B [k] = apply_weight (weight_B, sam_A) + bptr [1];\n                update_weight (weight_B, delta, sam_A, bptr [1]);\n                bptr [1] = dpp->samples_B [k];\n\n                m = (m + 1) & (MAX_TERM - 1);\n                k = (k + 1) & (MAX_TERM - 1);\n            }\n\n            if (m) {\n                int32_t temp_samples [MAX_TERM];\n\n                memcpy (temp_samples, dpp->samples_A, sizeof (dpp->samples_A));\n\n                for (k = 0; k < MAX_TERM; k++, m++)\n                    dpp->samples_A [k] = temp_samples [m & (MAX_TERM - 1)];\n\n                memcpy (temp_samples, dpp->samples_B, sizeof (dpp->samples_B));\n\n                for (k = 0; k < MAX_TERM; k++, m++)\n                    dpp->samples_B [k] = temp_samples [m & (MAX_TERM - 1)];\n            }\n\n            break;\n\n        case -1:\n            for (bptr = buffer; bptr < eptr; bptr += 2) {\n                sam_A = bptr [0] + apply_weight (weight_A, dpp->samples_A [0]);\n                update_weight_clip (weight_A, delta, dpp->samples_A [0], bptr [0]);\n                bptr [0] = sam_A;\n                dpp->samples_A [0] = bptr [1] + apply_weight (weight_B, sam_A);\n                update_weight_clip (weight_B, delta, sam_A, bptr [1]);\n                bptr [1] = dpp->samples_A [0];\n            }\n\n            break;\n\n        case -2:\n            for (bptr = buffer; bptr < eptr; bptr += 2) {\n                sam_B = bptr [1] + apply_weight (weight_B, dpp->samples_B [0]);\n                update_weight_clip (weight_B, delta, dpp->samples_B [0], bptr [1]);\n                bptr [1] = sam_B;\n                dpp->samples_B [0] = bptr [0] + apply_weight (weight_A, sam_B);\n                update_weight_clip (weight_A, delta, sam_B, bptr [0]);\n                bptr [0] = dpp->samples_B [0];\n            }\n\n            break;\n\n        case -3:\n            for (bptr = buffer; bptr < eptr; bptr += 2) {\n                sam_A = bptr [0] + apply_weight (weight_A, dpp->samples_A [0]);\n                update_weight_clip (weight_A, delta, dpp->samples_A [0], bptr [0]);\n                sam_B = bptr [1] + apply_weight (weight_B, dpp->samples_B [0]);\n                update_weight_clip (weight_B, delta, dpp->samples_B [0], bptr [1]);\n                bptr [0] = dpp->samples_B [0] = sam_A;\n                bptr [1] = dpp->samples_A [0] = sam_B;\n            }\n\n            break;\n    }\n\n    dpp->weight_A = weight_A;\n    dpp->weight_B = weight_B;\n}\n\n#if (!defined(CPU_COLDFIRE) && !defined(CPU_ARM)) || defined(SIMULATOR)\n\nstatic void decorr_stereo_pass_cont (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count)\n{\n    int32_t delta = dpp->delta, weight_A = dpp->weight_A, weight_B = dpp->weight_B;\n    int32_t *bptr, *tptr, *eptr = buffer + (sample_count * 2), sam_A, sam_B;\n    int k, i;\n\n    switch (dpp->term) {\n\n        case 17:\n            for (bptr = buffer; bptr < eptr; bptr += 2) {\n                sam_A = 2 * bptr [-2] - bptr [-4];\n                bptr [0] = apply_weight (weight_A, sam_A) + (sam_B = bptr [0]);\n                update_weight (weight_A, delta, sam_A, sam_B);\n\n                sam_A = 2 * bptr [-1] - bptr [-3];\n                bptr [1] = apply_weight (weight_B, sam_A) + (sam_B = bptr [1]);\n                update_weight (weight_B, delta, sam_A, sam_B);\n            }\n\n            dpp->samples_B [0] = bptr [-1];\n            dpp->samples_A [0] = bptr [-2];\n            dpp->samples_B [1] = bptr [-3];\n            dpp->samples_A [1] = bptr [-4];\n            break;\n\n        case 18:\n            for (bptr = buffer; bptr < eptr; bptr += 2) {\n                sam_A = (3 * bptr [-2] - bptr [-4]) >> 1;\n                bptr [0] = apply_weight (weight_A, sam_A) + (sam_B = bptr [0]);\n                update_weight (weight_A, delta, sam_A, sam_B);\n\n                sam_A = (3 * bptr [-1] - bptr [-3]) >> 1;\n                bptr [1] = apply_weight (weight_B, sam_A) + (sam_B = bptr [1]);\n                update_weight (weight_B, delta, sam_A, sam_B);\n            }\n\n            dpp->samples_B [0] = bptr [-1];\n            dpp->samples_A [0] = bptr [-2];\n            dpp->samples_B [1] = bptr [-3];\n            dpp->samples_A [1] = bptr [-4];\n            break;\n\n        default:\n            for (bptr = buffer, tptr = buffer - (dpp->term * 2); bptr < eptr; bptr += 2, tptr += 2) {\n                bptr [0] = apply_weight (weight_A, tptr [0]) + (sam_A = bptr [0]);\n                update_weight (weight_A, delta, tptr [0], sam_A);\n\n                bptr [1] = apply_weight (weight_B, tptr [1]) + (sam_A = bptr [1]);\n                update_weight (weight_B, delta, tptr [1], sam_A);\n            }\n\n            for (k = dpp->term - 1, i = 8; i--; k--) {\n                dpp->samples_B [k & (MAX_TERM - 1)] = *--bptr;\n                dpp->samples_A [k & (MAX_TERM - 1)] = *--bptr;\n            }\n\n            break;\n\n        case -1:\n            for (bptr = buffer; bptr < eptr; bptr += 2) {\n                bptr [0] = apply_weight (weight_A, bptr [-1]) + (sam_A = bptr [0]);\n                update_weight_clip (weight_A, delta, bptr [-1], sam_A);\n                bptr [1] = apply_weight (weight_B, bptr [0]) + (sam_A = bptr [1]);\n                update_weight_clip (weight_B, delta, bptr [0], sam_A);\n            }\n\n            dpp->samples_A [0] = bptr [-1];\n            break;\n\n        case -2:\n            for (bptr = buffer; bptr < eptr; bptr += 2) {\n                bptr [1] = apply_weight (weight_B, bptr [-2]) + (sam_A = bptr [1]);\n                update_weight_clip (weight_B, delta, bptr [-2], sam_A);\n                bptr [0] = apply_weight (weight_A, bptr [1]) + (sam_A = bptr [0]);\n                update_weight_clip (weight_A, delta, bptr [1], sam_A);\n            }\n\n            dpp->samples_B [0] = bptr [-2];\n            break;\n\n        case -3:\n            for (bptr = buffer; bptr < eptr; bptr += 2) {\n                bptr [0] = apply_weight (weight_A, bptr [-1]) + (sam_A = bptr [0]);\n                update_weight_clip (weight_A, delta, bptr [-1], sam_A);\n                bptr [1] = apply_weight (weight_B, bptr [-2]) + (sam_A = bptr [1]);\n                update_weight_clip (weight_B, delta, bptr [-2], sam_A);\n            }\n\n            dpp->samples_A [0] = bptr [-1];\n            dpp->samples_B [0] = bptr [-2];\n            break;\n    }\n\n    dpp->weight_A = weight_A;\n    dpp->weight_B = weight_B;\n}\n\n#endif\n\nstatic void decorr_mono_pass (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count)\n{\n    int32_t delta = dpp->delta, weight_A = dpp->weight_A;\n    int32_t *bptr, *eptr = buffer + sample_count, sam_A;\n    int m, k;\n\n    switch (dpp->term) {\n\n        case 17:\n            for (bptr = buffer; bptr < eptr; bptr++) {\n                sam_A = 2 * dpp->samples_A [0] - dpp->samples_A [1];\n                dpp->samples_A [1] = dpp->samples_A [0];\n                dpp->samples_A [0] = apply_weight (weight_A, sam_A) + bptr [0];\n                update_weight (weight_A, delta, sam_A, bptr [0]);\n                bptr [0] = dpp->samples_A [0];\n            }\n\n            break;\n\n        case 18:\n            for (bptr = buffer; bptr < eptr; bptr++) {\n                sam_A = (3 * dpp->samples_A [0] - dpp->samples_A [1]) >> 1;\n                dpp->samples_A [1] = dpp->samples_A [0];\n                dpp->samples_A [0] = apply_weight (weight_A, sam_A) + bptr [0];\n                update_weight (weight_A, delta, sam_A, bptr [0]);\n                bptr [0] = dpp->samples_A [0];\n            }\n\n            break;\n\n        default:\n            for (m = 0, k = dpp->term & (MAX_TERM - 1), bptr = buffer; bptr < eptr; bptr++) {\n                sam_A = dpp->samples_A [m];\n                dpp->samples_A [k] = apply_weight (weight_A, sam_A) + bptr [0];\n                update_weight (weight_A, delta, sam_A, bptr [0]);\n                bptr [0] = dpp->samples_A [k];\n                m = (m + 1) & (MAX_TERM - 1);\n                k = (k + 1) & (MAX_TERM - 1);\n            }\n\n            if (m) {\n                int32_t temp_samples [MAX_TERM];\n\n                memcpy (temp_samples, dpp->samples_A, sizeof (dpp->samples_A));\n\n                for (k = 0; k < MAX_TERM; k++, m++)\n                    dpp->samples_A [k] = temp_samples [m & (MAX_TERM - 1)];\n            }\n\n            break;\n    }\n\n    dpp->weight_A = weight_A;\n}\n\n\n// This is a helper function for unpack_samples() that applies several final\n// operations. First, if the data is 32-bit float data, then that conversion\n// is done in the float.c module (whether lossy or lossless) and we return.\n// Otherwise, if the extended integer data applies, then that operation is\n// executed first. If the unpacked data is lossy (and not corrected) then\n// it is clipped and shifted in a single operation. Otherwise, if it's\n// lossless then the last step is to apply the final shift (if any).\n\nstatic void fixup_samples (WavpackStream *wps, int32_t *buffer, uint32_t sample_count)\n{\n    uint32_t flags = wps->wphdr.flags;\n    int shift = (flags & SHIFT_MASK) >> SHIFT_LSB;\n\n    if (flags & FLOAT_DATA) {\n        float_values (wps, buffer, (flags & MONO_FLAG) ? sample_count : sample_count * 2);\n        return;\n    }\n\n    if (flags & INT32_DATA) {\n        uint32_t count = (flags & MONO_FLAG) ? sample_count : sample_count * 2;\n        int sent_bits = wps->int32_sent_bits, zeros = wps->int32_zeros;\n        int ones = wps->int32_ones, dups = wps->int32_dups;\n        int32_t *dptr = buffer;\n\n        if (!(flags & HYBRID_FLAG) && !sent_bits && (zeros + ones + dups))\n            while (count--) {\n                if (zeros)\n                    *dptr <<= zeros;\n                else if (ones)\n                    *dptr = ((*dptr + 1) << ones) - 1;\n                else if (dups)\n                    *dptr = ((*dptr + (*dptr & 1)) << dups) - (*dptr & 1);\n\n                dptr++;\n            }\n        else\n            shift += zeros + sent_bits + ones + dups;\n    }\n\n    if (flags & HYBRID_FLAG) {\n        int32_t min_value, max_value, min_shifted, max_shifted;\n\n        switch (flags & BYTES_STORED) {\n            case 0:\n                min_shifted = (min_value = -128 >> shift) << shift;\n                max_shifted = (max_value = 127 >> shift) << shift;\n                break;\n\n            case 1:\n                min_shifted = (min_value = -32768 >> shift) << shift;\n                max_shifted = (max_value = 32767 >> shift) << shift;\n                break;\n\n            case 2:\n                min_shifted = (min_value = -8388608 >> shift) << shift;\n                max_shifted = (max_value = 8388607 >> shift) << shift;\n                break;\n\n            case 3:\n            default:\n                min_shifted = (min_value = (int32_t) 0x80000000 >> shift) << shift;\n                max_shifted = (max_value = (int32_t) 0x7FFFFFFF >> shift) << shift;\n                break;\n        }\n\n        if (!(flags & MONO_FLAG))\n            sample_count *= 2;\n\n        while (sample_count--) {\n            if (*buffer < min_value)\n                *buffer++ = min_shifted;\n            else if (*buffer > max_value)\n                *buffer++ = max_shifted;\n            else\n                *buffer++ <<= shift;\n        }\n    }\n    else if (shift) {\n        if (!(flags & MONO_FLAG))\n            sample_count *= 2;\n\n        while (sample_count--)\n            *buffer++ <<= shift;\n    }\n}\n\n// This function checks the crc value(s) for an unpacked block, returning the\n// number of actual crc errors detected for the block. The block must be\n// completely unpacked before this test is valid. For losslessly unpacked\n// blocks of float or extended integer data the extended crc is also checked.\n// Note that WavPack's crc is not a CCITT approved polynomial algorithm, but\n// is a much simpler method that is virtually as robust for real world data.\n\nint check_crc_error (WavpackContext *wpc)\n{\n    WavpackStream *wps = &wpc->stream;\n    int result = 0;\n\n    if (wps->crc != wps->wphdr.crc)\n        ++result;\n\n    return result;\n}\n"
  },
  {
    "path": "src/engine/external/wavpack/wavpack.h",
    "content": "/*////////////////////////////////////////////////////////////////////////// */\n/*                           **** WAVPACK ****                            // */\n/*                  Hybrid Lossless Wavefile Compressor                   // */\n/*              Copyright (c) 1998 - 2004 Conifer Software.               // */\n/*                          All Rights Reserved.                          // */\n/*      Distributed under the BSD Software License (see license.txt)      // */\n/*////////////////////////////////////////////////////////////////////////// */\n\n/* wavpack.h */\n\n#include <sys/types.h>\n\n/* This header file contains all the definitions required by WavPack. */\n\n#ifdef __BORLANDC__\ntypedef unsigned long uint32_t;\ntypedef long int32_t;\n#elif defined(_WIN32) && !defined(__MINGW32__)\n#include <stdlib.h>\ntypedef unsigned __int64 uint64_t;\ntypedef unsigned __int32 uint32_t;\ntypedef __int64 int64_t;\ntypedef __int32 int32_t;\n#else\n#include <inttypes.h>\n#endif\n\ntypedef unsigned char   uchar;\n\n#if !defined(__GNUC__) || defined(WIN32)\ntypedef unsigned short  ushort;\ntypedef unsigned int    uint;\n#endif\n\n#include <stdio.h>\n\n#define FALSE 0\n#define TRUE 1\n\n/*//////////////////////////// WavPack Header ///////////////////////////////// */\n\n/* Note that this is the ONLY structure that is written to (or read from) */\n/* WavPack 4.0 files, and is the preamble to every block in both the .wv */\n/* and .wvc files. */\n\ntypedef struct {\n    char ckID [4];\n    uint32_t ckSize;\n    short version;\n    uchar track_no, index_no;\n    uint32_t total_samples, block_index, block_samples, flags, crc;\n} WavpackHeader;\n\n#define WavpackHeaderFormat \"4LS2LLLLL\"\n\n/* or-values for \"flags\" */\n\n#define BYTES_STORED    3       /* 1-4 bytes/sample */\n#define MONO_FLAG       4       /* not stereo */\n#define HYBRID_FLAG     8       /* hybrid mode */\n#define JOINT_STEREO    0x10    /* joint stereo */\n#define CROSS_DECORR    0x20    /* no-delay cross decorrelation */\n#define HYBRID_SHAPE    0x40    /* noise shape (hybrid mode only) */\n#define FLOAT_DATA      0x80    /* ieee 32-bit floating point data */\n\n#define INT32_DATA      0x100   /* special extended int handling */\n#define HYBRID_BITRATE  0x200   /* bitrate noise (hybrid mode only) */\n#define HYBRID_BALANCE  0x400   /* balance noise (hybrid stereo mode only) */\n\n#define INITIAL_BLOCK   0x800   /* initial block of multichannel segment */\n#define FINAL_BLOCK     0x1000  /* final block of multichannel segment */\n\n#define SHIFT_LSB       13\n#define SHIFT_MASK      (0x1fL << SHIFT_LSB)\n\n#define MAG_LSB         18\n#define MAG_MASK        (0x1fL << MAG_LSB)\n\n#define SRATE_LSB       23\n#define SRATE_MASK      (0xfL << SRATE_LSB)\n\n#define FALSE_STEREO    0x40000000      /* block is stereo, but data is mono */\n\n#define IGNORED_FLAGS   0x18000000      /* reserved, but ignore if encountered */\n#define NEW_SHAPING     0x20000000      /* use IIR filter for negative shaping */\n#define UNKNOWN_FLAGS   0x80000000      /* also reserved, but refuse decode if */\n                                        /*  encountered */\n\n#define MONO_DATA (MONO_FLAG | FALSE_STEREO)\n\n#define MIN_STREAM_VERS     0x402       /* lowest stream version we'll decode */\n#define MAX_STREAM_VERS     0x410       /* highest stream version we'll decode */\n\n/*////////////////////////// WavPack Metadata ///////////////////////////////// */\n\n/* This is an internal representation of metadata. */\n\ntypedef struct {\n    int32_t byte_length;\n    void *data;\n    uchar id;\n} WavpackMetadata;\n\n#define ID_OPTIONAL_DATA        0x20\n#define ID_ODD_SIZE             0x40\n#define ID_LARGE                0x80\n\n#define ID_DUMMY                0x0\n#define ID_ENCODER_INFO         0x1\n#define ID_DECORR_TERMS         0x2\n#define ID_DECORR_WEIGHTS       0x3\n#define ID_DECORR_SAMPLES       0x4\n#define ID_ENTROPY_VARS         0x5\n#define ID_HYBRID_PROFILE       0x6\n#define ID_SHAPING_WEIGHTS      0x7\n#define ID_FLOAT_INFO           0x8\n#define ID_INT32_INFO           0x9\n#define ID_WV_BITSTREAM         0xa\n#define ID_WVC_BITSTREAM        0xb\n#define ID_WVX_BITSTREAM        0xc\n#define ID_CHANNEL_INFO         0xd\n\n#define ID_RIFF_HEADER          (ID_OPTIONAL_DATA | 0x1)\n#define ID_RIFF_TRAILER         (ID_OPTIONAL_DATA | 0x2)\n#define ID_REPLAY_GAIN          (ID_OPTIONAL_DATA | 0x3)\n#define ID_CUESHEET             (ID_OPTIONAL_DATA | 0x4)\n#define ID_CONFIG_BLOCK         (ID_OPTIONAL_DATA | 0x5)\n#define ID_MD5_CHECKSUM         (ID_OPTIONAL_DATA | 0x6)\n\n/*/////////////////////// WavPack Configuration /////////////////////////////// */\n\n/* This internal structure is used during encode to provide configuration to */\n/* the encoding engine and during decoding to provide fle information back to */\n/* the higher level functions. Not all fields are used in both modes. */\n\ntypedef struct {\n    int bits_per_sample, bytes_per_sample;\n    int num_channels, float_norm_exp;\n    uint32_t flags, sample_rate, channel_mask;\n} WavpackConfig;\n\n#define CONFIG_BYTES_STORED     3       /* 1-4 bytes/sample */\n#define CONFIG_MONO_FLAG        4       /* not stereo */\n#define CONFIG_HYBRID_FLAG      8       /* hybrid mode */\n#define CONFIG_JOINT_STEREO     0x10    /* joint stereo */\n#define CONFIG_CROSS_DECORR     0x20    /* no-delay cross decorrelation */\n#define CONFIG_HYBRID_SHAPE     0x40    /* noise shape (hybrid mode only) */\n#define CONFIG_FLOAT_DATA       0x80    /* ieee 32-bit floating point data */\n\n#define CONFIG_FAST_FLAG        0x200   /* fast mode */\n#define CONFIG_HIGH_FLAG        0x800   /* high quality mode */\n#define CONFIG_VERY_HIGH_FLAG   0x1000  /* very high */\n#define CONFIG_BITRATE_KBPS     0x2000  /* bitrate is kbps, not bits / sample */\n#define CONFIG_AUTO_SHAPING     0x4000  /* automatic noise shaping */\n#define CONFIG_SHAPE_OVERRIDE   0x8000  /* shaping mode specified */\n#define CONFIG_JOINT_OVERRIDE   0x10000 /* joint-stereo mode specified */\n#define CONFIG_CREATE_EXE       0x40000 /* create executable */\n#define CONFIG_CREATE_WVC       0x80000 /* create correction file */\n#define CONFIG_OPTIMIZE_WVC     0x100000 /* maximize bybrid compression */\n#define CONFIG_CALC_NOISE       0x800000 /* calc noise in hybrid mode */\n#define CONFIG_LOSSY_MODE       0x1000000 /* obsolete (for information) */\n#define CONFIG_EXTRA_MODE       0x2000000 /* extra processing mode */\n#define CONFIG_SKIP_WVX         0x4000000 /* no wvx stream w/ floats & big ints */\n#define CONFIG_MD5_CHECKSUM     0x8000000 /* compute & store MD5 signature */\n#define CONFIG_OPTIMIZE_MONO    0x80000000 /* optimize for mono streams posing as stereo */\n\n/*////////////////////////////// WavPack Stream /////////////////////////////// */\n\n/* This internal structure contains everything required to handle a WavPack */\n/* \"stream\", which is defined as a stereo or mono stream of audio samples. For */\n/* multichannel audio several of these would be required. Each stream contains */\n/* pointers to hold a complete allocated block of WavPack data, although it's */\n/* possible to decode WavPack blocks without buffering an entire block. */\n\ntypedef int32_t (*read_stream)(void *, int32_t);\n\ntypedef struct bs {\n    uchar *buf, *end, *ptr;\n    void (*wrap)(struct bs *bs);\n    uint32_t file_bytes, sr;\n    int error, bc;\n    read_stream file;\n} Bitstream;\n\n#define MAX_NTERMS 16\n#define MAX_TERM 8\n\nstruct decorr_pass {\n    short term, delta, weight_A, weight_B;\n    int32_t samples_A [MAX_TERM], samples_B [MAX_TERM];\n};\n\nstruct entropy_data {\n    uint32_t median [3], slow_level, error_limit;\n};\n\nstruct words_data {\n    uint32_t bitrate_delta [2], bitrate_acc [2];\n    uint32_t pend_data, holding_one, zeros_acc;\n    int holding_zero, pend_count;\n    struct entropy_data c [2];\n};\n\ntypedef struct {\n    WavpackHeader wphdr;\n    Bitstream wvbits;\n\n    struct words_data w;\n\n    int num_terms, mute_error;\n    uint32_t sample_index, crc;\n\n    uchar int32_sent_bits, int32_zeros, int32_ones, int32_dups;\n    uchar float_flags, float_shift, float_max_exp, float_norm_exp;\n \n    struct decorr_pass decorr_passes [MAX_NTERMS];\n\n} WavpackStream;\n\n/* flags for float_flags: */\n\n#define FLOAT_SHIFT_ONES 1      /* bits left-shifted into float = '1' */\n#define FLOAT_SHIFT_SAME 2      /* bits left-shifted into float are the same */\n#define FLOAT_SHIFT_SENT 4      /* bits shifted into float are sent literally */\n#define FLOAT_ZEROS_SENT 8      /* \"zeros\" are not all real zeros */\n#define FLOAT_NEG_ZEROS  0x10   /* contains negative zeros */\n#define FLOAT_EXCEPTIONS 0x20   /* contains exceptions (inf, nan, etc.) */\n\n/*///////////////////////////// WavPack Context /////////////////////////////// */\n\n/* This internal structure holds everything required to encode or decode WavPack */\n/* files. It is recommended that direct access to this structure be minimized */\n/* and the provided utilities used instead. */\n\ntypedef struct {\n    WavpackConfig config;\n    WavpackStream stream;\n\n    uchar read_buffer [1024];\n    char error_message [80];\n\n    read_stream infile;\n    uint32_t total_samples, crc_errors, first_flags;\n    int open_flags, norm_offset, reduced_channels, lossy_blocks;\n\n} WavpackContext;\n\n/*////////////////////// function prototypes and macros ////////////////////// */\n\n#define CLEAR(destin) memset (&destin, 0, sizeof (destin));\n\n/* bits.c */\n\nvoid bs_open_read (Bitstream *bs, uchar *buffer_start, uchar *buffer_end, read_stream file, uint32_t file_bytes);\n\n#define bs_is_open(bs) ((bs)->ptr != NULL)\n\n#define getbit(bs) ( \\\n    (((bs)->bc) ? \\\n        ((bs)->bc--, (bs)->sr & 1) : \\\n            (((++((bs)->ptr) != (bs)->end) ? (void) 0 : (bs)->wrap (bs)), (bs)->bc = 7, ((bs)->sr = *((bs)->ptr)) & 1) \\\n    ) ? \\\n        ((bs)->sr >>= 1, 1) : \\\n        ((bs)->sr >>= 1, 0) \\\n)\n\n#define getbits(value, nbits, bs) { \\\n    while ((nbits) > (bs)->bc) { \\\n        if (++((bs)->ptr) == (bs)->end) (bs)->wrap (bs); \\\n        (bs)->sr |= (int32_t)*((bs)->ptr) << (bs)->bc; \\\n        (bs)->bc += 8; \\\n    } \\\n    *(value) = (bs)->sr; \\\n    if ((bs)->bc > 32) { \\\n        (bs)->bc -= (nbits); \\\n        (bs)->sr = *((bs)->ptr) >> (8 - (bs)->bc); \\\n    } \\\n    else { \\\n        (bs)->bc -= (nbits); \\\n        (bs)->sr >>= (nbits); \\\n    } \\\n}\n\nvoid little_endian_to_native (void *data, char *format);\nvoid native_to_little_endian (void *data, char *format);\n\n/* These macros implement the weight application and update operations */\n/* that are at the heart of the decorrelation loops. Note that when there */\n/* are several alternative versions of the same macro (marked with PERFCOND) */\n/* then the versions are functionally equivalent with respect to WavPack */\n/* decoding and the user should choose the one that provides the best */\n/* performance. This may be easier to check when NOT using the assembly */\n/* language optimizations. */\n\n#if 1   /* PERFCOND */\n#define apply_weight_i(weight, sample) ((weight * sample + 512) >> 10)\n#else\n#define apply_weight_i(weight, sample) ((((weight * sample) >> 8) + 2) >> 2)\n#endif\n\n#define apply_weight_f(weight, sample) (((((sample & 0xffffL) * weight) >> 9) + \\\n    (((sample & ~0xffffL) >> 9) * weight) + 1) >> 1)\n\n#if 1   /* PERFCOND */\n#define apply_weight(weight, sample) (sample != (short) sample ? \\\n    apply_weight_f (weight, sample) : apply_weight_i (weight, sample))\n#else\n#define apply_weight(weight, sample) ((int32_t)((weight * (int64_t) sample + 512) >> 10))\n#endif\n\n#if 0   /* PERFCOND */\n#define update_weight(weight, delta, source, result) \\\n    if (source && result) { int32_t s = (int32_t) (source ^ result) >> 31; weight = (delta ^ s) + (weight - s); }\n#elif 1\n#define update_weight(weight, delta, source, result) \\\n    if (source && result) weight += (((source ^ result) >> 30) | 1) * delta\n#else\n#define update_weight(weight, delta, source, result) \\\n    if (source && result) (source ^ result) < 0 ? (weight -= delta) : (weight += delta)\n#endif\n\n#define update_weight_clip(weight, delta, source, result) \\\n    if (source && result && ((source ^ result) < 0 ? (weight -= delta) < -1024 : (weight += delta) > 1024)) \\\n        weight = weight < 0 ? -1024 : 1024\n\n/* unpack.c */\n\nint unpack_init (WavpackContext *wpc);\nint init_wv_bitstream (WavpackContext *wpc, WavpackMetadata *wpmd);\nint read_decorr_terms (WavpackStream *wps, WavpackMetadata *wpmd);\nint read_decorr_weights (WavpackStream *wps, WavpackMetadata *wpmd);\nint read_decorr_samples (WavpackStream *wps, WavpackMetadata *wpmd);\nint read_float_info (WavpackStream *wps, WavpackMetadata *wpmd);\nint read_int32_info (WavpackStream *wps, WavpackMetadata *wpmd);\nint read_channel_info (WavpackContext *wpc, WavpackMetadata *wpmd);\nint read_config_info (WavpackContext *wpc, WavpackMetadata *wpmd);\nint32_t unpack_samples (WavpackContext *wpc, int32_t *buffer, uint32_t sample_count);\nint check_crc_error (WavpackContext *wpc);\n\n/* metadata.c stuff */\n\nint read_metadata_buff (WavpackContext *wpc, WavpackMetadata *wpmd);\nint process_metadata (WavpackContext *wpc, WavpackMetadata *wpmd);\n\n/* words.c stuff */\n\nint read_entropy_vars (WavpackStream *wps, WavpackMetadata *wpmd);\nint read_hybrid_profile (WavpackStream *wps, WavpackMetadata *wpmd);\nint32_t get_words (int32_t *buffer, int nsamples, uint32_t flags,\n                struct words_data *w, Bitstream *bs);\nint32_t exp2s (int log);\nint restore_weight (signed char weight);\n\n#define WORD_EOF (1L << 31)\n\n/* float.c */\n\nint read_float_info (WavpackStream *wps, WavpackMetadata *wpmd);\nvoid float_values (WavpackStream *wps, int32_t *values, int32_t num_values);\n\n/* wputils.c */\n\nWavpackContext *WavpackOpenFileInput (read_stream infile, char *error);\n\nint WavpackGetMode (WavpackContext *wpc);\n\n#define MODE_WVC        0x1\n#define MODE_LOSSLESS   0x2\n#define MODE_HYBRID     0x4\n#define MODE_FLOAT      0x8\n#define MODE_VALID_TAG  0x10\n#define MODE_HIGH       0x20\n#define MODE_FAST       0x40\n\nuint32_t WavpackUnpackSamples (WavpackContext *wpc, int32_t *buffer, uint32_t samples);\nuint32_t WavpackGetNumSamples (WavpackContext *wpc);\nuint32_t WavpackGetSampleIndex (WavpackContext *wpc);\nint WavpackGetNumErrors (WavpackContext *wpc);\nint WavpackLossyBlocks (WavpackContext *wpc);\nuint32_t WavpackGetSampleRate (WavpackContext *wpc);\nint WavpackGetBitsPerSample (WavpackContext *wpc);\nint WavpackGetBytesPerSample (WavpackContext *wpc);\nint WavpackGetNumChannels (WavpackContext *wpc);\nint WavpackGetReducedChannels (WavpackContext *wpc);\n"
  },
  {
    "path": "src/engine/external/wavpack/words.c",
    "content": "////////////////////////////////////////////////////////////////////////////\n//                           **** WAVPACK ****                            //\n//                  Hybrid Lossless Wavefile Compressor                   //\n//              Copyright (c) 1998 - 2006 Conifer Software.               //\n//                          All Rights Reserved.                          //\n//      Distributed under the BSD Software License (see license.txt)      //\n////////////////////////////////////////////////////////////////////////////\n\n// words.c\n\n// This module provides entropy word encoding and decoding functions using\n// a variation on the Rice method.  This was introduced in version 3.93\n// because it allows splitting the data into a \"lossy\" stream and a\n// \"correction\" stream in a very efficient manner and is therefore ideal\n// for the \"hybrid\" mode.  For 4.0, the efficiency of this method was\n// significantly improved by moving away from the normal Rice restriction of\n// using powers of two for the modulus divisions and now the method can be\n// used for both hybrid and pure lossless encoding.\n\n// Samples are divided by median probabilities at 5/7 (71.43%), 10/49 (20.41%),\n// and 20/343 (5.83%). Each zone has 3.5 times fewer samples than the\n// previous. Using standard Rice coding on this data would result in 1.4\n// bits per sample average (not counting sign bit). However, there is a\n// very simple encoding that is over 99% efficient with this data and\n// results in about 1.22 bits per sample.\n\n#include \"wavpack.h\"\n\n#include <string.h>\n\n//////////////////////////////// local macros /////////////////////////////////\n\n#define LIMIT_ONES 16   // maximum consecutive 1s sent for \"div\" data\n\n// these control the time constant \"slow_level\" which is used for hybrid mode\n// that controls bitrate as a function of residual level (HYBRID_BITRATE).\n#define SLS 8\n#define SLO ((1 << (SLS - 1)))\n\n// these control the time constant of the 3 median level breakpoints\n#define DIV0 128        // 5/7 of samples\n#define DIV1 64         // 10/49 of samples\n#define DIV2 32         // 20/343 of samples\n\n// this macro retrieves the specified median breakpoint (without frac; min = 1)\n#define GET_MED(med) (((c->median [med]) >> 4) + 1)\n\n// These macros update the specified median breakpoints. Note that the median\n// is incremented when the sample is higher than the median, else decremented.\n// They are designed so that the median will never drop below 1 and the value\n// is essentially stationary if there are 2 increments for every 5 decrements.\n\n#define INC_MED0() (c->median [0] += ((c->median [0] + DIV0) / DIV0) * 5)\n#define DEC_MED0() (c->median [0] -= ((c->median [0] + (DIV0-2)) / DIV0) * 2)\n#define INC_MED1() (c->median [1] += ((c->median [1] + DIV1) / DIV1) * 5)\n#define DEC_MED1() (c->median [1] -= ((c->median [1] + (DIV1-2)) / DIV1) * 2)\n#define INC_MED2() (c->median [2] += ((c->median [2] + DIV2) / DIV2) * 5)\n#define DEC_MED2() (c->median [2] -= ((c->median [2] + (DIV2-2)) / DIV2) * 2)\n\n#define count_bits(av) ( \\\n (av) < (1 << 8) ? nbits_table [av] : \\\n  ( \\\n   (av) < (1L << 16) ? nbits_table [(av) >> 8] + 8 : \\\n   ((av) < (1L << 24) ? nbits_table [(av) >> 16] + 16 : nbits_table [(av) >> 24] + 24) \\\n  ) \\\n)\n\n///////////////////////////// local table storage ////////////////////////////\n\nconst char nbits_table [] = {\n    0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,     // 0 - 15\n    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,     // 16 - 31\n    6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,     // 32 - 47\n    6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,     // 48 - 63\n    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,     // 64 - 79\n    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,     // 80 - 95\n    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,     // 96 - 111\n    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,     // 112 - 127\n    8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,     // 128 - 143\n    8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,     // 144 - 159\n    8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,     // 160 - 175\n    8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,     // 176 - 191\n    8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,     // 192 - 207\n    8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,     // 208 - 223\n    8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,     // 224 - 239\n    8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8      // 240 - 255\n};\n\nstatic const uchar log2_table [] = {\n    0x00, 0x01, 0x03, 0x04, 0x06, 0x07, 0x09, 0x0a, 0x0b, 0x0d, 0x0e, 0x10, 0x11, 0x12, 0x14, 0x15,\n    0x16, 0x18, 0x19, 0x1a, 0x1c, 0x1d, 0x1e, 0x20, 0x21, 0x22, 0x24, 0x25, 0x26, 0x28, 0x29, 0x2a,\n    0x2c, 0x2d, 0x2e, 0x2f, 0x31, 0x32, 0x33, 0x34, 0x36, 0x37, 0x38, 0x39, 0x3b, 0x3c, 0x3d, 0x3e,\n    0x3f, 0x41, 0x42, 0x43, 0x44, 0x45, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4d, 0x4e, 0x4f, 0x50, 0x51,\n    0x52, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63,\n    0x64, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x74, 0x75,\n    0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85,\n    0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95,\n    0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4,\n    0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb2,\n    0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc0,\n    0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcb, 0xcc, 0xcd, 0xce,\n    0xcf, 0xd0, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd8, 0xd9, 0xda, 0xdb,\n    0xdc, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe4, 0xe5, 0xe6, 0xe7, 0xe7,\n    0xe8, 0xe9, 0xea, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xee, 0xef, 0xf0, 0xf1, 0xf1, 0xf2, 0xf3, 0xf4,\n    0xf4, 0xf5, 0xf6, 0xf7, 0xf7, 0xf8, 0xf9, 0xf9, 0xfa, 0xfb, 0xfc, 0xfc, 0xfd, 0xfe, 0xff, 0xff\n};\n\nstatic const uchar exp2_table [] = {\n    0x00, 0x01, 0x01, 0x02, 0x03, 0x03, 0x04, 0x05, 0x06, 0x06, 0x07, 0x08, 0x08, 0x09, 0x0a, 0x0b,\n    0x0b, 0x0c, 0x0d, 0x0e, 0x0e, 0x0f, 0x10, 0x10, 0x11, 0x12, 0x13, 0x13, 0x14, 0x15, 0x16, 0x16,\n    0x17, 0x18, 0x19, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1d, 0x1e, 0x1f, 0x20, 0x20, 0x21, 0x22, 0x23,\n    0x24, 0x24, 0x25, 0x26, 0x27, 0x28, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,\n    0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3a, 0x3b, 0x3c, 0x3d,\n    0x3e, 0x3f, 0x40, 0x41, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x48, 0x49, 0x4a, 0x4b,\n    0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a,\n    0x5b, 0x5c, 0x5d, 0x5e, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,\n    0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,\n    0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x87, 0x88, 0x89, 0x8a,\n    0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b,\n    0x9c, 0x9d, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad,\n    0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0,\n    0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc8, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf, 0xd0, 0xd2, 0xd3, 0xd4,\n    0xd6, 0xd7, 0xd8, 0xd9, 0xdb, 0xdc, 0xdd, 0xde, 0xe0, 0xe1, 0xe2, 0xe4, 0xe5, 0xe6, 0xe8, 0xe9,\n    0xea, 0xec, 0xed, 0xee, 0xf0, 0xf1, 0xf2, 0xf4, 0xf5, 0xf6, 0xf8, 0xf9, 0xfa, 0xfc, 0xfd, 0xff\n};\n\nstatic const char ones_count_table [] = {\n    0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,\n    0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,\n    0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,\n    0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,7,\n    0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,\n    0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,\n    0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,\n    0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,8\n};\n\n///////////////////////////// executable code ////////////////////////////////\n\nvoid init_words (WavpackStream *wps)\n{\n    CLEAR (wps->w);\n}\n\nstatic int mylog2 (uint32_t avalue);\n\n// Read the median log2 values from the specifed metadata structure, convert\n// them back to 32-bit unsigned values and store them. If length is not\n// exactly correct then we flag and return an error.\n\nint read_entropy_vars (WavpackStream *wps, WavpackMetadata *wpmd)\n{\n    uchar *byteptr = wpmd->data;\n\n    if (wpmd->byte_length != ((wps->wphdr.flags & MONO_DATA) ? 6 : 12))\n        return FALSE;\n\n    wps->w.c [0].median [0] = exp2s (byteptr [0] + (byteptr [1] << 8));\n    wps->w.c [0].median [1] = exp2s (byteptr [2] + (byteptr [3] << 8));\n    wps->w.c [0].median [2] = exp2s (byteptr [4] + (byteptr [5] << 8));\n\n    if (!(wps->wphdr.flags & MONO_DATA)) {\n        wps->w.c [1].median [0] = exp2s (byteptr [6] + (byteptr [7] << 8));\n        wps->w.c [1].median [1] = exp2s (byteptr [8] + (byteptr [9] << 8));\n        wps->w.c [1].median [2] = exp2s (byteptr [10] + (byteptr [11] << 8));\n    }\n\n    return TRUE;\n}\n\n// Read the hybrid related values from the specifed metadata structure, convert\n// them back to their internal formats and store them. The extended profile\n// stuff is not implemented yet, so return an error if we get more data than\n// we know what to do with.\n\nint read_hybrid_profile (WavpackStream *wps, WavpackMetadata *wpmd)\n{\n    uchar *byteptr = wpmd->data;\n    uchar *endptr = byteptr + wpmd->byte_length;\n\n    if (wps->wphdr.flags & HYBRID_BITRATE) {\n        wps->w.c [0].slow_level = exp2s (byteptr [0] + (byteptr [1] << 8));\n        byteptr += 2;\n\n        if (!(wps->wphdr.flags & MONO_DATA)) {\n            wps->w.c [1].slow_level = exp2s (byteptr [0] + (byteptr [1] << 8));\n            byteptr += 2;\n        }\n    }\n\n    wps->w.bitrate_acc [0] = (int32_t)(byteptr [0] + (byteptr [1] << 8)) << 16;\n    byteptr += 2;\n\n    if (!(wps->wphdr.flags & MONO_DATA)) {\n        wps->w.bitrate_acc [1] = (int32_t)(byteptr [0] + (byteptr [1] << 8)) << 16;\n        byteptr += 2;\n    }\n\n    if (byteptr < endptr) {\n        wps->w.bitrate_delta [0] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8)));\n        byteptr += 2;\n\n        if (!(wps->wphdr.flags & MONO_DATA)) {\n            wps->w.bitrate_delta [1] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8)));\n            byteptr += 2;\n        }\n\n        if (byteptr < endptr)\n            return FALSE;\n    }\n    else\n        wps->w.bitrate_delta [0] = wps->w.bitrate_delta [1] = 0;\n\n    return TRUE;\n}\n\n// This function is called during both encoding and decoding of hybrid data to\n// update the \"error_limit\" variable which determines the maximum sample error\n// allowed in the main bitstream. In the HYBRID_BITRATE mode (which is the only\n// currently implemented) this is calculated from the slow_level values and the\n// bitrate accumulators. Note that the bitrate accumulators can be changing.\n\nvoid update_error_limit (struct words_data *w, uint32_t flags)\n{\n    int bitrate_0 = (w->bitrate_acc [0] += w->bitrate_delta [0]) >> 16;\n\n    if (flags & MONO_DATA) {\n        if (flags & HYBRID_BITRATE) {\n            int slow_log_0 = (w->c [0].slow_level + SLO) >> SLS;\n\n            if (slow_log_0 - bitrate_0 > -0x100)\n                w->c [0].error_limit = exp2s (slow_log_0 - bitrate_0 + 0x100);\n            else\n                w->c [0].error_limit = 0;\n        }\n        else\n            w->c [0].error_limit = exp2s (bitrate_0);\n    }\n    else {\n        int bitrate_1 = (w->bitrate_acc [1] += w->bitrate_delta [1]) >> 16;\n\n        if (flags & HYBRID_BITRATE) {\n            int slow_log_0 = (w->c [0].slow_level + SLO) >> SLS;\n            int slow_log_1 = (w->c [1].slow_level + SLO) >> SLS;\n\n            if (flags & HYBRID_BALANCE) {\n                int balance = (slow_log_1 - slow_log_0 + bitrate_1 + 1) >> 1;\n\n                if (balance > bitrate_0) {\n                    bitrate_1 = bitrate_0 * 2;\n                    bitrate_0 = 0;\n                }\n                else if (-balance > bitrate_0) {\n                    bitrate_0 = bitrate_0 * 2;\n                    bitrate_1 = 0;\n                }\n                else {\n                    bitrate_1 = bitrate_0 + balance;\n                    bitrate_0 = bitrate_0 - balance;\n                }\n            }\n\n            if (slow_log_0 - bitrate_0 > -0x100)\n                w->c [0].error_limit = exp2s (slow_log_0 - bitrate_0 + 0x100);\n            else\n                w->c [0].error_limit = 0;\n\n            if (slow_log_1 - bitrate_1 > -0x100)\n                w->c [1].error_limit = exp2s (slow_log_1 - bitrate_1 + 0x100);\n            else\n                w->c [1].error_limit = 0;\n        }\n        else {\n            w->c [0].error_limit = exp2s (bitrate_0);\n            w->c [1].error_limit = exp2s (bitrate_1);\n        }\n    }\n}\n\nstatic uint32_t read_code (Bitstream *bs, uint32_t maxcode);\n\n// Read the next word from the bitstream \"wvbits\" and return the value. This\n// function can be used for hybrid or lossless streams, but since an\n// optimized version is available for lossless this function would normally\n// be used for hybrid only. If a hybrid lossless stream is being read then\n// the \"correction\" offset is written at the specified pointer. A return value\n// of WORD_EOF indicates that the end of the bitstream was reached (all 1s) or\n// some other error occurred.\n\nint32_t get_words (int32_t *buffer, int nsamples, uint32_t flags,\n                struct words_data *w, Bitstream *bs)\n{\n    register struct entropy_data *c = w->c;\n    int csamples;\n\n    if (!(flags & MONO_DATA))\n        nsamples *= 2;\n\n    for (csamples = 0; csamples < nsamples; ++csamples) {\n        uint32_t ones_count, low, mid, high;\n\n        if (!(flags & MONO_DATA))\n            c = w->c + (csamples & 1);\n\n        if (!(w->c [0].median [0] & ~1) && !w->holding_zero && !w->holding_one && !(w->c [1].median [0] & ~1)) {\n            uint32_t mask;\n            int cbits;\n\n            if (w->zeros_acc) {\n                if (--w->zeros_acc) {\n                    c->slow_level -= (c->slow_level + SLO) >> SLS;\n                    *buffer++ = 0;\n                    continue;\n                }\n            }\n            else {\n                for (cbits = 0; cbits < 33 && getbit (bs); ++cbits);\n\n                if (cbits == 33)\n                    break;\n\n                if (cbits < 2)\n                    w->zeros_acc = cbits;\n                else {\n                    for (mask = 1, w->zeros_acc = 0; --cbits; mask <<= 1)\n                        if (getbit (bs))\n                            w->zeros_acc |= mask;\n\n                    w->zeros_acc |= mask;\n                }\n\n                if (w->zeros_acc) {\n                    c->slow_level -= (c->slow_level + SLO) >> SLS;\n                    CLEAR (w->c [0].median);\n                    CLEAR (w->c [1].median);\n                    *buffer++ = 0;\n                    continue;\n                }\n            }\n        }\n\n        if (w->holding_zero)\n            ones_count = w->holding_zero = 0;\n        else {\n            int next8;\n\n            if (bs->bc < 8) {\n                if (++(bs->ptr) == bs->end)\n                    bs->wrap (bs);\n\n                next8 = (bs->sr |= *(bs->ptr) << bs->bc) & 0xff;\n                bs->bc += 8;\n            }\n            else\n                next8 = bs->sr & 0xff;\n\n            if (next8 == 0xff) {\n                bs->bc -= 8;\n                bs->sr >>= 8;\n\n                for (ones_count = 8; ones_count < (LIMIT_ONES + 1) && getbit (bs); ++ones_count);\n\n                if (ones_count == (LIMIT_ONES + 1))\n                    break;\n\n                if (ones_count == LIMIT_ONES) {\n                    uint32_t mask;\n                    int cbits;\n\n                    for (cbits = 0; cbits < 33 && getbit (bs); ++cbits);\n\n                    if (cbits == 33)\n                        break;\n\n                    if (cbits < 2)\n                        ones_count = cbits;\n                    else {\n                        for (mask = 1, ones_count = 0; --cbits; mask <<= 1)\n                            if (getbit (bs))\n                                ones_count |= mask;\n\n                        ones_count |= mask;\n                    }\n\n                    ones_count += LIMIT_ONES;\n                }\n            }\n            else {\n                bs->bc -= (ones_count = ones_count_table [next8]) + 1;\n                bs->sr >>= ones_count + 1;\n            }\n\n            if (w->holding_one) {\n                w->holding_one = ones_count & 1;\n                ones_count = (ones_count >> 1) + 1;\n            }\n            else {\n                w->holding_one = ones_count & 1;\n                ones_count >>= 1;\n            }\n\n            w->holding_zero = ~w->holding_one & 1;\n        }\n\n        if ((flags & HYBRID_FLAG) && ((flags & MONO_DATA) || !(csamples & 1)))\n            update_error_limit (w, flags);\n\n        if (ones_count == 0) {\n            low = 0;\n            high = GET_MED (0) - 1;\n            DEC_MED0 ();\n        }\n        else {\n            low = GET_MED (0);\n            INC_MED0 ();\n\n            if (ones_count == 1) {\n                high = low + GET_MED (1) - 1;\n                DEC_MED1 ();\n            }\n            else {\n                low += GET_MED (1);\n                INC_MED1 ();\n\n                if (ones_count == 2) {\n                    high = low + GET_MED (2) - 1;\n                    DEC_MED2 ();\n                }\n                else {\n                    low += (ones_count - 2) * GET_MED (2);\n                    high = low + GET_MED (2) - 1;\n                    INC_MED2 ();\n                }\n            }\n        }\n\n        mid = (high + low + 1) >> 1;\n\n        if (!c->error_limit)\n            mid = read_code (bs, high - low) + low;\n        else while (high - low > c->error_limit) {\n            if (getbit (bs))\n                mid = (high + (low = mid) + 1) >> 1;\n            else\n                mid = ((high = mid - 1) + low + 1) >> 1;\n        }\n\n        *buffer++ = getbit (bs) ? ~mid : mid;\n\n        if (flags & HYBRID_BITRATE)\n            c->slow_level = c->slow_level - ((c->slow_level + SLO) >> SLS) + mylog2 (mid);\n    }\n\n    return (flags & MONO_DATA) ? csamples : (csamples / 2);\n}\n\n// Read a single unsigned value from the specified bitstream with a value\n// from 0 to maxcode. If there are exactly a power of two number of possible\n// codes then this will read a fixed number of bits; otherwise it reads the\n// minimum number of bits and then determines whether another bit is needed\n// to define the code.\n\nstatic uint32_t read_code (Bitstream *bs, uint32_t maxcode)\n{\n    int bitcount = count_bits (maxcode);\n    uint32_t extras = (1L << bitcount) - maxcode - 1, code;\n\n    if (!bitcount)\n        return 0;\n\n    getbits (&code, bitcount - 1, bs);\n    code &= (1L << (bitcount - 1)) - 1;\n\n    if (code >= extras) {\n        code = (code << 1) - extras;\n\n        if (getbit (bs))\n            ++code;\n    }\n\n    return code;\n}\n\n// The concept of a base 2 logarithm is used in many parts of WavPack. It is\n// a way of sufficiently accurately representing 32-bit signed and unsigned\n// values storing only 16 bits (actually fewer). It is also used in the hybrid\n// mode for quickly comparing the relative magnitude of large values (i.e.\n// division) and providing smooth exponentials using only addition.\n\n// These are not strict logarithms in that they become linear around zero and\n// can therefore represent both zero and negative values. They have 8 bits\n// of precision and in \"roundtrip\" conversions the total error never exceeds 1\n// part in 225 except for the cases of +/-115 and +/-195 (which error by 1).\n\n\n// This function returns the log2 for the specified 32-bit unsigned value.\n// The maximum value allowed is about 0xff800000 and returns 8447.\n\nstatic int mylog2 (uint32_t avalue)\n{\n    int dbits;\n\n    if ((avalue += avalue >> 9) < (1 << 8)) {\n        dbits = nbits_table [avalue];\n        return (dbits << 8) + log2_table [(avalue << (9 - dbits)) & 0xff];\n    }\n    else {\n        if (avalue < (1L << 16))\n            dbits = nbits_table [avalue >> 8] + 8;\n        else if (avalue < (1L << 24))\n            dbits = nbits_table [avalue >> 16] + 16;\n        else\n            dbits = nbits_table [avalue >> 24] + 24;\n\n        return (dbits << 8) + log2_table [(avalue >> (dbits - 9)) & 0xff];\n    }\n}\n\n// This function returns the log2 for the specified 32-bit signed value.\n// All input values are valid and the return values are in the range of\n// +/- 8192.\n\nint log2s (int32_t value)\n{\n    return (value < 0) ? -mylog2 (-value) : mylog2 (value);\n}\n\n// This function returns the original integer represented by the supplied\n// logarithm (at least within the provided accuracy). The log is signed,\n// but since a full 32-bit value is returned this can be used for unsigned\n// conversions as well (i.e. the input range is -8192 to +8447).\n\nint32_t exp2s (int log)\n{\n    uint32_t value;\n\n    if (log < 0)\n        return -exp2s (-log);\n\n    value = exp2_table [log & 0xff] | 0x100;\n\n    if ((log >>= 8) <= 9)\n        return value >> (9 - log);\n    else\n        return value << (log - 9);\n}\n\n// These two functions convert internal weights (which are normally +/-1024)\n// to and from an 8-bit signed character version for storage in metadata. The\n// weights are clipped here in the case that they are outside that range.\n\nint restore_weight (signed char weight)\n{\n    int result;\n\n    if ((result = (int) weight << 3) > 0)\n        result += (result + 64) >> 7;\n\n    return result;\n}\n"
  },
  {
    "path": "src/engine/external/wavpack/wputils.c",
    "content": "////////////////////////////////////////////////////////////////////////////\n//                           **** WAVPACK ****                            //\n//                  Hybrid Lossless Wavefile Compressor                   //\n//              Copyright (c) 1998 - 2006 Conifer Software.               //\n//                          All Rights Reserved.                          //\n//      Distributed under the BSD Software License (see license.txt)      //\n////////////////////////////////////////////////////////////////////////////\n\n// wputils.c\n\n// This module provides a high-level interface for decoding WavPack 4.0 audio\n// streams and files. WavPack data is read with a stream reading callback. No\n// direct seeking is provided for, but it is possible to start decoding\n// anywhere in a WavPack stream. In this case, WavPack will be able to provide\n// the sample-accurate position when it synchs with the data and begins\n// decoding.\n\n#include \"wavpack.h\"\n\n#include <string.h>\n\n///////////////////////////// local table storage ////////////////////////////\n\nconst uint32_t sample_rates [] = { 6000, 8000, 9600, 11025, 12000, 16000, 22050,\n    24000, 32000, 44100, 48000, 64000, 88200, 96000, 192000 };\n\n///////////////////////////// executable code ////////////////////////////////\n\nstatic uint32_t read_next_header (read_stream infile, WavpackHeader *wphdr);\n        \n// This function reads data from the specified stream in search of a valid\n// WavPack 4.0 audio block. If this fails in 1 megabyte (or an invalid or\n// unsupported WavPack block is encountered) then an appropriate message is\n// copied to \"error\" and NULL is returned, otherwise a pointer to a\n// WavpackContext structure is returned (which is used to call all other\n// functions in this module). This can be initiated at the beginning of a\n// WavPack file, or anywhere inside a WavPack file. To determine the exact\n// position within the file use WavpackGetSampleIndex(). For demonstration\n// purposes this uses a single static copy of the WavpackContext structure,\n// so obviously it cannot be used for more than one file at a time. Also,\n// this function will not handle \"correction\" files, plays only the first\n// two channels of multi-channel files, and is limited in resolution in some\n// large integer or floating point files (but always provides at least 24 bits\n// of resolution).\n\nstatic WavpackContext wpc;\n\nWavpackContext *WavpackOpenFileInput (read_stream infile, char *error)\n{\n    WavpackStream *wps = &wpc.stream;\n    uint32_t bcount;\n\n    CLEAR (wpc);\n    wpc.infile = infile;\n    wpc.total_samples = (uint32_t) -1;\n    wpc.norm_offset = 0;\n    wpc.open_flags = 0;\n\n    // open the source file for reading and store the size\n\n    while (!wps->wphdr.block_samples) {\n\n        bcount = read_next_header (wpc.infile, &wps->wphdr);\n\n        if (bcount == (uint32_t) -1) {\n            strcpy (error, \"not compatible with this version of WavPack file!\");\n            return NULL;\n        }\n\n        if (wps->wphdr.block_samples && wps->wphdr.total_samples != (uint32_t) -1)\n            wpc.total_samples = wps->wphdr.total_samples;\n\n        if (!unpack_init (&wpc)) {\n            strcpy (error, wpc.error_message [0] ? wpc.error_message :\n                \"not compatible with this version of WavPack file!\");\n\n            return NULL;\n        }\n    }\n\n    wpc.config.flags &= ~0xff;\n    wpc.config.flags |= wps->wphdr.flags & 0xff;\n    wpc.config.bytes_per_sample = (wps->wphdr.flags & BYTES_STORED) + 1;\n    wpc.config.float_norm_exp = wps->float_norm_exp;\n\n    wpc.config.bits_per_sample = (wpc.config.bytes_per_sample * 8) - \n        ((wps->wphdr.flags & SHIFT_MASK) >> SHIFT_LSB);\n\n    if (wpc.config.flags & FLOAT_DATA) {\n        wpc.config.bytes_per_sample = 3;\n        wpc.config.bits_per_sample = 24;\n    }\n\n    if (!wpc.config.sample_rate) {\n        if (!wps || !wps->wphdr.block_samples || (wps->wphdr.flags & SRATE_MASK) == SRATE_MASK)\n            wpc.config.sample_rate = 44100;\n        else\n            wpc.config.sample_rate = sample_rates [(wps->wphdr.flags & SRATE_MASK) >> SRATE_LSB];\n    }\n\n    if (!wpc.config.num_channels) {\n        wpc.config.num_channels = (wps->wphdr.flags & MONO_FLAG) ? 1 : 2;\n        wpc.config.channel_mask = 0x5 - wpc.config.num_channels;\n    }\n\n    if (!(wps->wphdr.flags & FINAL_BLOCK))\n        wpc.reduced_channels = (wps->wphdr.flags & MONO_FLAG) ? 1 : 2;\n\n    return &wpc;\n}\n\n// This function obtains general information about an open file and returns\n// a mask with the following bit values:\n\n// MODE_LOSSLESS:  file is lossless (pure lossless only)\n// MODE_HYBRID:  file is hybrid mode (lossy part only)\n// MODE_FLOAT:  audio data is 32-bit ieee floating point (but will provided\n//               in 24-bit integers for convenience)\n// MODE_HIGH:  file was created in \"high\" mode (information only)\n// MODE_FAST:  file was created in \"fast\" mode (information only)\n\nint WavpackGetMode (WavpackContext *wpc)\n{\n    int mode = 0;\n\n    if (wpc) {\n        if (wpc->config.flags & CONFIG_HYBRID_FLAG)\n            mode |= MODE_HYBRID;\n        else if (!(wpc->config.flags & CONFIG_LOSSY_MODE))\n            mode |= MODE_LOSSLESS;\n\n        if (wpc->lossy_blocks)\n            mode &= ~MODE_LOSSLESS;\n\n        if (wpc->config.flags & CONFIG_FLOAT_DATA)\n            mode |= MODE_FLOAT;\n\n        if (wpc->config.flags & CONFIG_HIGH_FLAG)\n            mode |= MODE_HIGH;\n\n        if (wpc->config.flags & CONFIG_FAST_FLAG)\n            mode |= MODE_FAST;\n    }\n\n    return mode;\n}\n\n// Unpack the specified number of samples from the current file position.\n// Note that \"samples\" here refers to \"complete\" samples, which would be\n// 2 longs for stereo files. The audio data is returned right-justified in\n// 32-bit longs in the endian mode native to the executing processor. So,\n// if the original data was 16-bit, then the values returned would be\n// +/-32k. Floating point data will be returned as 24-bit integers (and may\n// also be clipped). The actual number of samples unpacked is returned,\n// which should be equal to the number requested unless the end of fle is\n// encountered or an error occurs.\n\nuint32_t WavpackUnpackSamples (WavpackContext *wpc, int32_t *buffer, uint32_t samples)\n{\n    WavpackStream *wps = &wpc->stream;\n    uint32_t bcount, samples_unpacked = 0, samples_to_unpack;\n    int num_channels = wpc->config.num_channels;\n\n    while (samples) {\n        if (!wps->wphdr.block_samples || !(wps->wphdr.flags & INITIAL_BLOCK) ||\n            wps->sample_index >= wps->wphdr.block_index + wps->wphdr.block_samples) {\n                bcount = read_next_header (wpc->infile, &wps->wphdr);\n\n                if (bcount == (uint32_t) -1)\n                    break;\n\n                if (!wps->wphdr.block_samples || wps->sample_index == wps->wphdr.block_index)\n                    if (!unpack_init (wpc))\n                        break;\n        }\n\n        if (!wps->wphdr.block_samples || !(wps->wphdr.flags & INITIAL_BLOCK) ||\n            wps->sample_index >= wps->wphdr.block_index + wps->wphdr.block_samples)\n                continue;\n\n        if (wps->sample_index < wps->wphdr.block_index) {\n            samples_to_unpack = wps->wphdr.block_index - wps->sample_index;\n\n            if (samples_to_unpack > samples)\n                samples_to_unpack = samples;\n\n            wps->sample_index += samples_to_unpack;\n            samples_unpacked += samples_to_unpack;\n            samples -= samples_to_unpack;\n\n            if (wpc->reduced_channels)\n                samples_to_unpack *= wpc->reduced_channels;\n            else\n                samples_to_unpack *= num_channels;\n\n            while (samples_to_unpack--)\n                *buffer++ = 0;\n\n            continue;\n        }\n\n        samples_to_unpack = wps->wphdr.block_index + wps->wphdr.block_samples - wps->sample_index;\n\n        if (samples_to_unpack > samples)\n            samples_to_unpack = samples;\n\n        unpack_samples (wpc, buffer, samples_to_unpack);\n\n        if (wpc->reduced_channels)\n            buffer += samples_to_unpack * wpc->reduced_channels;\n        else\n            buffer += samples_to_unpack * num_channels;\n\n        samples_unpacked += samples_to_unpack;\n        samples -= samples_to_unpack;\n\n        if (wps->sample_index == wps->wphdr.block_index + wps->wphdr.block_samples) {\n            if (check_crc_error (wpc))\n                wpc->crc_errors++;\n        }\n\n        if (wps->sample_index == wpc->total_samples)\n            break;\n    }\n\n    return samples_unpacked;\n}\n\n// Get total number of samples contained in the WavPack file, or -1 if unknown\n\nuint32_t WavpackGetNumSamples (WavpackContext *wpc)\n{\n    return wpc ? wpc->total_samples : (uint32_t) -1;\n}\n\n// Get the current sample index position, or -1 if unknown\n\nuint32_t WavpackGetSampleIndex (WavpackContext *wpc)\n{\n    if (wpc)\n        return wpc->stream.sample_index;\n\n    return (uint32_t) -1;\n}\n\n// Get the number of errors encountered so far\n\nint WavpackGetNumErrors (WavpackContext *wpc)\n{\n    return wpc ? wpc->crc_errors : 0;\n}\n\n// return TRUE if any uncorrected lossy blocks were actually written or read\n\nint WavpackLossyBlocks (WavpackContext *wpc)\n{\n    return wpc ? wpc->lossy_blocks : 0;\n}\n\n// Returns the sample rate of the specified WavPack file\n\nuint32_t WavpackGetSampleRate (WavpackContext *wpc)\n{\n    return wpc ? wpc->config.sample_rate : 44100;\n}\n\n// Returns the number of channels of the specified WavPack file. Note that\n// this is the actual number of channels contained in the file, but this\n// version can only decode the first two.\n\nint WavpackGetNumChannels (WavpackContext *wpc)\n{\n    return wpc ? wpc->config.num_channels : 2;\n}\n\n// Returns the actual number of valid bits per sample contained in the\n// original file, which may or may not be a multiple of 8. Floating data\n// always has 32 bits, integers may be from 1 to 32 bits each. When this\n// value is not a multiple of 8, then the \"extra\" bits are located in the\n// LSBs of the results. That is, values are right justified when unpacked\n// into longs, but are left justified in the number of bytes used by the\n// original data.\n\nint WavpackGetBitsPerSample (WavpackContext *wpc)\n{\n    return wpc ? wpc->config.bits_per_sample : 16;\n}\n\n// Returns the number of bytes used for each sample (1 to 4) in the original\n// file. This is required information for the user of this module because the\n// audio data is returned in the LOWER bytes of the long buffer and must be\n// left-shifted 8, 16, or 24 bits if normalized longs are required.\n\nint WavpackGetBytesPerSample (WavpackContext *wpc)\n{\n    return wpc ? wpc->config.bytes_per_sample : 2;\n}\n\n// This function will return the actual number of channels decoded from the\n// file (which may or may not be less than the actual number of channels, but\n// will always be 1 or 2). Normally, this will be the front left and right\n// channels of a multi-channel file.\n\nint WavpackGetReducedChannels (WavpackContext *wpc)\n{\n    if (wpc)\n        return wpc->reduced_channels ? wpc->reduced_channels : wpc->config.num_channels;\n    else\n        return 2;\n}\n\n// Read from current file position until a valid 32-byte WavPack 4.0 header is\n// found and read into the specified pointer. The number of bytes skipped is\n// returned. If no WavPack header is found within 1 meg, then a -1 is returned\n// to indicate the error. No additional bytes are read past the header and it\n// is returned in the processor's native endian mode. Seeking is not required.\n\nstatic uint32_t read_next_header (read_stream infile, WavpackHeader *wphdr)\n{\n    char buffer [sizeof (*wphdr)], *sp = buffer + sizeof (*wphdr), *ep = sp;\n    uint32_t bytes_skipped = 0;\n    int bleft;\n\n    while (1) {\n        if (sp < ep) {\n            bleft = ep - sp;\n            memcpy (buffer, sp, bleft);\n        }\n        else\n            bleft = 0;\n\n        if (infile (buffer + bleft, sizeof (*wphdr) - bleft) != (int32_t) sizeof (*wphdr) - bleft)\n            return -1;\n\n        sp = buffer;\n\n        if (*sp++ == 'w' && *sp == 'v' && *++sp == 'p' && *++sp == 'k' &&\n            !(*++sp & 1) && sp [2] < 16 && !sp [3] && sp [5] == 4 &&\n            sp [4] >= (MIN_STREAM_VERS & 0xff) && sp [4] <= (MAX_STREAM_VERS & 0xff)) {\n                memcpy (wphdr, buffer, sizeof (*wphdr));\n                little_endian_to_native (wphdr, WavpackHeaderFormat);\n                return bytes_skipped;\n            }\n\n        while (sp < ep && *sp != 'w')\n            sp++;\n\n        if ((bytes_skipped += sp - buffer) > 1048576L)\n            return -1;\n    }\n}\n"
  },
  {
    "path": "src/engine/external/wavpack/wvfilter.c.no_compile",
    "content": "////////////////////////////////////////////////////////////////////////////\r\n//                           **** WAVPACK ****                            //\r\n//                  Hybrid Lossless Wavefile Compressor                   //\r\n//              Copyright (c) 1998 - 2006 Conifer Software.               //\r\n//                          All Rights Reserved.                          //\r\n//      Distributed under the BSD Software License (see license.txt)      //\r\n////////////////////////////////////////////////////////////////////////////\r\n\r\n// wv_filter.c\r\n\r\n// This is the main module for the demonstration WavPack command-line\r\n// decoder filter. It uses the tiny \"hardware\" version of the decoder and\r\n// accepts WavPack files on stdin and outputs a standard MS wav file to\r\n// stdout. Note that this involves converting the data to little-endian\r\n// (if the executing processor is not), possibly packing the data into\r\n// fewer bytes per sample, and generating an appropriate riff wav header.\r\n// Note that this is NOT the copy of the RIFF header that might be stored\r\n// in the file, and any additional RIFF information and tags are lost.\r\n// See wputils.c for further limitations.\r\n\r\n#include \"wavpack.h\"\r\n\r\n#if defined(WIN32)\r\n#include <io.h>\r\n#include <fcntl.h>\r\n#endif\r\n\r\n#include <string.h>\r\n\r\n// These structures are used to place a wav riff header at the beginning of\r\n// the output.\r\n\r\ntypedef struct {\r\n    char ckID [4];\r\n    uint32_t ckSize;\r\n    char formType [4];\r\n} RiffChunkHeader;\r\n\r\ntypedef struct {\r\n    char ckID [4];\r\n    uint32_t ckSize;\r\n} ChunkHeader;\r\n\r\n#define ChunkHeaderFormat \"4L\"\r\n\r\ntypedef struct {\r\n    ushort FormatTag, NumChannels;\r\n    uint32_t SampleRate, BytesPerSecond;\r\n    ushort BlockAlign, BitsPerSample;\r\n} WaveHeader;\r\n\r\n#define WaveHeaderFormat \"SSLLSS\"\r\n\r\nstatic uchar *format_samples (int bps, uchar *dst, int32_t *src, uint32_t samcnt);\r\nstatic int32_t read_bytes (void *buff, int32_t bcount);\r\nstatic int32_t temp_buffer [256];\r\n\r\nint main ()\r\n{\r\n    ChunkHeader FormatChunkHeader, DataChunkHeader;\r\n    RiffChunkHeader RiffChunkHeader;\r\n    WaveHeader WaveHeader;\r\n\r\n    uint32_t total_unpacked_samples = 0, total_samples;\r\n    int num_channels, bps;\r\n    WavpackContext *wpc;\r\n    char error [80];\r\n\r\n#if defined(WIN32)\r\n    setmode (fileno (stdin), O_BINARY);\r\n    setmode (fileno (stdout), O_BINARY);\r\n#endif\r\n\r\n    wpc = WavpackOpenFileInput (read_bytes, error);\r\n\r\n    if (!wpc) {\r\n        fputs (error, stderr);\r\n        fputs (\"\\n\", stderr);\r\n        return 1;\r\n    }\r\n\r\n    num_channels = WavpackGetReducedChannels (wpc);\r\n    total_samples = WavpackGetNumSamples (wpc);\r\n    bps = WavpackGetBytesPerSample (wpc);\r\n\r\n    strncpy (RiffChunkHeader.ckID, \"RIFF\", sizeof (RiffChunkHeader.ckID));\r\n    RiffChunkHeader.ckSize = total_samples * num_channels * bps + sizeof (ChunkHeader) * 2 + sizeof (WaveHeader) + 4;\r\n    strncpy (RiffChunkHeader.formType, \"WAVE\", sizeof (RiffChunkHeader.formType));\r\n\r\n    strncpy (FormatChunkHeader.ckID, \"fmt \", sizeof (FormatChunkHeader.ckID));\r\n    FormatChunkHeader.ckSize = sizeof (WaveHeader);\r\n\r\n    WaveHeader.FormatTag = 1;\r\n    WaveHeader.NumChannels = num_channels;\r\n    WaveHeader.SampleRate = WavpackGetSampleRate (wpc);\r\n    WaveHeader.BlockAlign = num_channels * bps;\r\n    WaveHeader.BytesPerSecond = WaveHeader.SampleRate * WaveHeader.BlockAlign;\r\n    WaveHeader.BitsPerSample = WavpackGetBitsPerSample (wpc);\r\n\r\n    strncpy (DataChunkHeader.ckID, \"data\", sizeof (DataChunkHeader.ckID));\r\n    DataChunkHeader.ckSize = total_samples * num_channels * bps;\r\n\r\n    native_to_little_endian (&RiffChunkHeader, ChunkHeaderFormat);\r\n    native_to_little_endian (&FormatChunkHeader, ChunkHeaderFormat);\r\n    native_to_little_endian (&WaveHeader, WaveHeaderFormat);\r\n    native_to_little_endian (&DataChunkHeader, ChunkHeaderFormat);\r\n\r\n    if (!fwrite (&RiffChunkHeader, sizeof (RiffChunkHeader), 1, stdout) ||\r\n        !fwrite (&FormatChunkHeader, sizeof (FormatChunkHeader), 1, stdout) ||\r\n        !fwrite (&WaveHeader, sizeof (WaveHeader), 1, stdout) ||\r\n        !fwrite (&DataChunkHeader, sizeof (DataChunkHeader), 1, stdout)) {\r\n            fputs (\"can't write .WAV data, disk probably full!\\n\", stderr);\r\n            return 1;\r\n        }\r\n\r\n    while (1) {\r\n        uint32_t samples_unpacked;\r\n\r\n        samples_unpacked = WavpackUnpackSamples (wpc, temp_buffer, 256 / num_channels);\r\n        total_unpacked_samples += samples_unpacked;\r\n\r\n        if (samples_unpacked) {\r\n            format_samples (bps, (uchar *) temp_buffer, temp_buffer, samples_unpacked *= num_channels);\r\n\r\n            if (fwrite (temp_buffer, bps, samples_unpacked, stdout) != samples_unpacked) {\r\n                fputs (\"can't write .WAV data, disk probably full!\\n\", stderr);\r\n                return 1;\r\n            }\r\n        }\r\n\r\n        if (!samples_unpacked)\r\n            break;\r\n    }\r\n\r\n    fflush (stdout);\r\n\r\n    if (WavpackGetNumSamples (wpc) != (uint32_t) -1 &&\r\n        total_unpacked_samples != WavpackGetNumSamples (wpc)) {\r\n            fputs (\"incorrect number of samples!\\n\", stderr);\r\n            return 1;\r\n    }\r\n\r\n    if (WavpackGetNumErrors (wpc)) {\r\n        fputs (\"crc errors detected!\\n\", stderr);\r\n        return 1;\r\n    }\r\n\r\n    return 0;\r\n}\r\n\r\nstatic int32_t read_bytes (void *buff, int32_t bcount)\r\n{\r\n    return fread (buff, 1, bcount, stdin);\r\n}\r\n\r\n// Reformat samples from longs in processor's native endian mode to\r\n// little-endian data with (possibly) less than 4 bytes / sample.\r\n\r\nstatic uchar *format_samples (int bps, uchar *dst, int32_t *src, uint32_t samcnt)\r\n{\r\n    int32_t temp;\r\n\r\n    switch (bps) {\r\n\r\n        case 1:\r\n            while (samcnt--)\r\n                *dst++ = *src++ + 128;\r\n\r\n            break;\r\n\r\n        case 2:\r\n            while (samcnt--) {\r\n                *dst++ = (uchar)(temp = *src++);\r\n                *dst++ = (uchar)(temp >> 8);\r\n            }\r\n\r\n            break;\r\n\r\n        case 3:\r\n            while (samcnt--) {\r\n                *dst++ = (uchar)(temp = *src++);\r\n                *dst++ = (uchar)(temp >> 8);\r\n                *dst++ = (uchar)(temp >> 16);\r\n            }\r\n\r\n            break;\r\n\r\n        case 4:\r\n            while (samcnt--) {\r\n                *dst++ = (uchar)(temp = *src++);\r\n                *dst++ = (uchar)(temp >> 8);\r\n                *dst++ = (uchar)(temp >> 16);\r\n                *dst++ = (uchar)(temp >> 24);\r\n            }\r\n\r\n            break;\r\n    }\r\n\r\n    return dst;\r\n}\r\n"
  },
  {
    "path": "src/engine/external/zlib/VERSION",
    "content": "1.2.5\n"
  },
  {
    "path": "src/engine/external/zlib/adler32.c",
    "content": "/* adler32.c -- compute the Adler-32 checksum of a data stream\n * Copyright (C) 1995-2007 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* @(#) $Id$ */\n\n#include \"zutil.h\"\n\n#define local static\n\nlocal uLong adler32_combine_(uLong adler1, uLong adler2, z_off64_t len2);\n\n#define BASE 65521UL    /* largest prime smaller than 65536 */\n#define NMAX 5552\n/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */\n\n#define DO1(buf,i)  {adler += (buf)[i]; sum2 += adler;}\n#define DO2(buf,i)  DO1(buf,i); DO1(buf,i+1);\n#define DO4(buf,i)  DO2(buf,i); DO2(buf,i+2);\n#define DO8(buf,i)  DO4(buf,i); DO4(buf,i+4);\n#define DO16(buf)   DO8(buf,0); DO8(buf,8);\n\n/* use NO_DIVIDE if your processor does not do division in hardware */\n#ifdef NO_DIVIDE\n#  define MOD(a) \\\n    do { \\\n        if (a >= (BASE << 16)) a -= (BASE << 16); \\\n        if (a >= (BASE << 15)) a -= (BASE << 15); \\\n        if (a >= (BASE << 14)) a -= (BASE << 14); \\\n        if (a >= (BASE << 13)) a -= (BASE << 13); \\\n        if (a >= (BASE << 12)) a -= (BASE << 12); \\\n        if (a >= (BASE << 11)) a -= (BASE << 11); \\\n        if (a >= (BASE << 10)) a -= (BASE << 10); \\\n        if (a >= (BASE << 9)) a -= (BASE << 9); \\\n        if (a >= (BASE << 8)) a -= (BASE << 8); \\\n        if (a >= (BASE << 7)) a -= (BASE << 7); \\\n        if (a >= (BASE << 6)) a -= (BASE << 6); \\\n        if (a >= (BASE << 5)) a -= (BASE << 5); \\\n        if (a >= (BASE << 4)) a -= (BASE << 4); \\\n        if (a >= (BASE << 3)) a -= (BASE << 3); \\\n        if (a >= (BASE << 2)) a -= (BASE << 2); \\\n        if (a >= (BASE << 1)) a -= (BASE << 1); \\\n        if (a >= BASE) a -= BASE; \\\n    } while (0)\n#  define MOD4(a) \\\n    do { \\\n        if (a >= (BASE << 4)) a -= (BASE << 4); \\\n        if (a >= (BASE << 3)) a -= (BASE << 3); \\\n        if (a >= (BASE << 2)) a -= (BASE << 2); \\\n        if (a >= (BASE << 1)) a -= (BASE << 1); \\\n        if (a >= BASE) a -= BASE; \\\n    } while (0)\n#else\n#  define MOD(a) a %= BASE\n#  define MOD4(a) a %= BASE\n#endif\n\n/* ========================================================================= */\nuLong ZEXPORT adler32(adler, buf, len)\n    uLong adler;\n    const Bytef *buf;\n    uInt len;\n{\n    unsigned long sum2;\n    unsigned n;\n\n    /* split Adler-32 into component sums */\n    sum2 = (adler >> 16) & 0xffff;\n    adler &= 0xffff;\n\n    /* in case user likes doing a byte at a time, keep it fast */\n    if (len == 1) {\n        adler += buf[0];\n        if (adler >= BASE)\n            adler -= BASE;\n        sum2 += adler;\n        if (sum2 >= BASE)\n            sum2 -= BASE;\n        return adler | (sum2 << 16);\n    }\n\n    /* initial Adler-32 value (deferred check for len == 1 speed) */\n    if (buf == Z_NULL)\n        return 1L;\n\n    /* in case short lengths are provided, keep it somewhat fast */\n    if (len < 16) {\n        while (len--) {\n            adler += *buf++;\n            sum2 += adler;\n        }\n        if (adler >= BASE)\n            adler -= BASE;\n        MOD4(sum2);             /* only added so many BASE's */\n        return adler | (sum2 << 16);\n    }\n\n    /* do length NMAX blocks -- requires just one modulo operation */\n    while (len >= NMAX) {\n        len -= NMAX;\n        n = NMAX / 16;          /* NMAX is divisible by 16 */\n        do {\n            DO16(buf);          /* 16 sums unrolled */\n            buf += 16;\n        } while (--n);\n        MOD(adler);\n        MOD(sum2);\n    }\n\n    /* do remaining bytes (less than NMAX, still just one modulo) */\n    if (len) {                  /* avoid modulos if none remaining */\n        while (len >= 16) {\n            len -= 16;\n            DO16(buf);\n            buf += 16;\n        }\n        while (len--) {\n            adler += *buf++;\n            sum2 += adler;\n        }\n        MOD(adler);\n        MOD(sum2);\n    }\n\n    /* return recombined sums */\n    return adler | (sum2 << 16);\n}\n\n/* ========================================================================= */\nlocal uLong adler32_combine_(adler1, adler2, len2)\n    uLong adler1;\n    uLong adler2;\n    z_off64_t len2;\n{\n    unsigned long sum1;\n    unsigned long sum2;\n    unsigned rem;\n\n    /* the derivation of this formula is left as an exercise for the reader */\n    rem = (unsigned)(len2 % BASE);\n    sum1 = adler1 & 0xffff;\n    sum2 = rem * sum1;\n    MOD(sum2);\n    sum1 += (adler2 & 0xffff) + BASE - 1;\n    sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;\n    if (sum1 >= BASE) sum1 -= BASE;\n    if (sum1 >= BASE) sum1 -= BASE;\n    if (sum2 >= (BASE << 1)) sum2 -= (BASE << 1);\n    if (sum2 >= BASE) sum2 -= BASE;\n    return sum1 | (sum2 << 16);\n}\n\n/* ========================================================================= */\nuLong ZEXPORT adler32_combine(adler1, adler2, len2)\n    uLong adler1;\n    uLong adler2;\n    z_off_t len2;\n{\n    return adler32_combine_(adler1, adler2, len2);\n}\n\nuLong ZEXPORT adler32_combine64(adler1, adler2, len2)\n    uLong adler1;\n    uLong adler2;\n    z_off64_t len2;\n{\n    return adler32_combine_(adler1, adler2, len2);\n}\n"
  },
  {
    "path": "src/engine/external/zlib/compress.c",
    "content": "/* compress.c -- compress a memory buffer\n * Copyright (C) 1995-2005 Jean-loup Gailly.\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* @(#) $Id$ */\n\n#define ZLIB_INTERNAL\n#include \"zlib.h\"\n\n/* ===========================================================================\n     Compresses the source buffer into the destination buffer. The level\n   parameter has the same meaning as in deflateInit.  sourceLen is the byte\n   length of the source buffer. Upon entry, destLen is the total size of the\n   destination buffer, which must be at least 0.1% larger than sourceLen plus\n   12 bytes. Upon exit, destLen is the actual size of the compressed buffer.\n\n     compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough\n   memory, Z_BUF_ERROR if there was not enough room in the output buffer,\n   Z_STREAM_ERROR if the level parameter is invalid.\n*/\nint ZEXPORT compress2 (dest, destLen, source, sourceLen, level)\n    Bytef *dest;\n    uLongf *destLen;\n    const Bytef *source;\n    uLong sourceLen;\n    int level;\n{\n    z_stream stream;\n    int err;\n\n    stream.next_in = (Bytef*)source;\n    stream.avail_in = (uInt)sourceLen;\n#ifdef MAXSEG_64K\n    /* Check for source > 64K on 16-bit machine: */\n    if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;\n#endif\n    stream.next_out = dest;\n    stream.avail_out = (uInt)*destLen;\n    if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;\n\n    stream.zalloc = (alloc_func)0;\n    stream.zfree = (free_func)0;\n    stream.opaque = (voidpf)0;\n\n    err = deflateInit(&stream, level);\n    if (err != Z_OK) return err;\n\n    err = deflate(&stream, Z_FINISH);\n    if (err != Z_STREAM_END) {\n        deflateEnd(&stream);\n        return err == Z_OK ? Z_BUF_ERROR : err;\n    }\n    *destLen = stream.total_out;\n\n    err = deflateEnd(&stream);\n    return err;\n}\n\n/* ===========================================================================\n */\nint ZEXPORT compress (dest, destLen, source, sourceLen)\n    Bytef *dest;\n    uLongf *destLen;\n    const Bytef *source;\n    uLong sourceLen;\n{\n    return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);\n}\n\n/* ===========================================================================\n     If the default memLevel or windowBits for deflateInit() is changed, then\n   this function needs to be updated.\n */\nuLong ZEXPORT compressBound (sourceLen)\n    uLong sourceLen;\n{\n    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +\n           (sourceLen >> 25) + 13;\n}\n"
  },
  {
    "path": "src/engine/external/zlib/crc32.c",
    "content": "/* crc32.c -- compute the CRC-32 of a data stream\n * Copyright (C) 1995-2006, 2010 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n *\n * Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster\n * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing\n * tables for updating the shift register in one step with three exclusive-ors\n * instead of four steps with four exclusive-ors.  This results in about a\n * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3.\n */\n\n/* @(#) $Id$ */\n\n/*\n  Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore\n  protection on the static variables used to control the first-use generation\n  of the crc tables.  Therefore, if you #define DYNAMIC_CRC_TABLE, you should\n  first call get_crc_table() to initialize the tables before allowing more than\n  one thread to use crc32().\n */\n\n#ifdef MAKECRCH\n#  include <stdio.h>\n#  ifndef DYNAMIC_CRC_TABLE\n#    define DYNAMIC_CRC_TABLE\n#  endif /* !DYNAMIC_CRC_TABLE */\n#endif /* MAKECRCH */\n\n#include \"zutil.h\"      /* for STDC and FAR definitions */\n\n#define local static\n\n/* Find a four-byte integer type for crc32_little() and crc32_big(). */\n#ifndef NOBYFOUR\n#  ifdef STDC           /* need ANSI C limits.h to determine sizes */\n#    include <limits.h>\n#    define BYFOUR\n#    if (UINT_MAX == 0xffffffffUL)\n       typedef unsigned int u4;\n#    else\n#      if (ULONG_MAX == 0xffffffffUL)\n         typedef unsigned long u4;\n#      else\n#        if (USHRT_MAX == 0xffffffffUL)\n           typedef unsigned short u4;\n#        else\n#          undef BYFOUR     /* can't find a four-byte integer type! */\n#        endif\n#      endif\n#    endif\n#  endif /* STDC */\n#endif /* !NOBYFOUR */\n\n/* Definitions for doing the crc four data bytes at a time. */\n#ifdef BYFOUR\n#  define REV(w) ((((w)>>24)&0xff)+(((w)>>8)&0xff00)+ \\\n                (((w)&0xff00)<<8)+(((w)&0xff)<<24))\n   local unsigned long crc32_little OF((unsigned long,\n                        const unsigned char FAR *, unsigned));\n   local unsigned long crc32_big OF((unsigned long,\n                        const unsigned char FAR *, unsigned));\n#  define TBLS 8\n#else\n#  define TBLS 1\n#endif /* BYFOUR */\n\n/* Local functions for crc concatenation */\nlocal unsigned long gf2_matrix_times OF((unsigned long *mat,\n                                         unsigned long vec));\nlocal void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));\nlocal uLong crc32_combine_(uLong crc1, uLong crc2, z_off64_t len2);\n\n\n#ifdef DYNAMIC_CRC_TABLE\n\nlocal volatile int crc_table_empty = 1;\nlocal unsigned long FAR crc_table[TBLS][256];\nlocal void make_crc_table OF((void));\n#ifdef MAKECRCH\n   local void write_table OF((FILE *, const unsigned long FAR *));\n#endif /* MAKECRCH */\n/*\n  Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:\n  x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.\n\n  Polynomials over GF(2) are represented in binary, one bit per coefficient,\n  with the lowest powers in the most significant bit.  Then adding polynomials\n  is just exclusive-or, and multiplying a polynomial by x is a right shift by\n  one.  If we call the above polynomial p, and represent a byte as the\n  polynomial q, also with the lowest power in the most significant bit (so the\n  byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,\n  where a mod b means the remainder after dividing a by b.\n\n  This calculation is done using the shift-register method of multiplying and\n  taking the remainder.  The register is initialized to zero, and for each\n  incoming bit, x^32 is added mod p to the register if the bit is a one (where\n  x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by\n  x (which is shifting right by one and adding x^32 mod p if the bit shifted\n  out is a one).  We start with the highest power (least significant bit) of\n  q and repeat for all eight bits of q.\n\n  The first table is simply the CRC of all possible eight bit values.  This is\n  all the information needed to generate CRCs on data a byte at a time for all\n  combinations of CRC register values and incoming bytes.  The remaining tables\n  allow for word-at-a-time CRC calculation for both big-endian and little-\n  endian machines, where a word is four bytes.\n*/\nlocal void make_crc_table()\n{\n    unsigned long c;\n    int n, k;\n    unsigned long poly;                 /* polynomial exclusive-or pattern */\n    /* terms of polynomial defining this crc (except x^32): */\n    static volatile int first = 1;      /* flag to limit concurrent making */\n    static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};\n\n    /* See if another task is already doing this (not thread-safe, but better\n       than nothing -- significantly reduces duration of vulnerability in\n       case the advice about DYNAMIC_CRC_TABLE is ignored) */\n    if (first) {\n        first = 0;\n\n        /* make exclusive-or pattern from polynomial (0xedb88320UL) */\n        poly = 0UL;\n        for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)\n            poly |= 1UL << (31 - p[n]);\n\n        /* generate a crc for every 8-bit value */\n        for (n = 0; n < 256; n++) {\n            c = (unsigned long)n;\n            for (k = 0; k < 8; k++)\n                c = c & 1 ? poly ^ (c >> 1) : c >> 1;\n            crc_table[0][n] = c;\n        }\n\n#ifdef BYFOUR\n        /* generate crc for each value followed by one, two, and three zeros,\n           and then the byte reversal of those as well as the first table */\n        for (n = 0; n < 256; n++) {\n            c = crc_table[0][n];\n            crc_table[4][n] = REV(c);\n            for (k = 1; k < 4; k++) {\n                c = crc_table[0][c & 0xff] ^ (c >> 8);\n                crc_table[k][n] = c;\n                crc_table[k + 4][n] = REV(c);\n            }\n        }\n#endif /* BYFOUR */\n\n        crc_table_empty = 0;\n    }\n    else {      /* not first */\n        /* wait for the other guy to finish (not efficient, but rare) */\n        while (crc_table_empty)\n            ;\n    }\n\n#ifdef MAKECRCH\n    /* write out CRC tables to crc32.h */\n    {\n        FILE *out;\n\n        out = fopen(\"crc32.h\", \"w\");\n        if (out == NULL) return;\n        fprintf(out, \"/* crc32.h -- tables for rapid CRC calculation\\n\");\n        fprintf(out, \" * Generated automatically by crc32.c\\n */\\n\\n\");\n        fprintf(out, \"local const unsigned long FAR \");\n        fprintf(out, \"crc_table[TBLS][256] =\\n{\\n  {\\n\");\n        write_table(out, crc_table[0]);\n#  ifdef BYFOUR\n        fprintf(out, \"#ifdef BYFOUR\\n\");\n        for (k = 1; k < 8; k++) {\n            fprintf(out, \"  },\\n  {\\n\");\n            write_table(out, crc_table[k]);\n        }\n        fprintf(out, \"#endif\\n\");\n#  endif /* BYFOUR */\n        fprintf(out, \"  }\\n};\\n\");\n        fclose(out);\n    }\n#endif /* MAKECRCH */\n}\n\n#ifdef MAKECRCH\nlocal void write_table(out, table)\n    FILE *out;\n    const unsigned long FAR *table;\n{\n    int n;\n\n    for (n = 0; n < 256; n++)\n        fprintf(out, \"%s0x%08lxUL%s\", n % 5 ? \"\" : \"    \", table[n],\n                n == 255 ? \"\\n\" : (n % 5 == 4 ? \",\\n\" : \", \"));\n}\n#endif /* MAKECRCH */\n\n#else /* !DYNAMIC_CRC_TABLE */\n/* ========================================================================\n * Tables of CRC-32s of all single-byte values, made by make_crc_table().\n */\n#include \"crc32.h\"\n#endif /* DYNAMIC_CRC_TABLE */\n\n/* =========================================================================\n * This function can be used by asm versions of crc32()\n */\nconst unsigned long FAR * ZEXPORT get_crc_table()\n{\n#ifdef DYNAMIC_CRC_TABLE\n    if (crc_table_empty)\n        make_crc_table();\n#endif /* DYNAMIC_CRC_TABLE */\n    return (const unsigned long FAR *)crc_table;\n}\n\n/* ========================================================================= */\n#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)\n#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1\n\n/* ========================================================================= */\nunsigned long ZEXPORT crc32(crc, buf, len)\n    unsigned long crc;\n    const unsigned char FAR *buf;\n    uInt len;\n{\n    if (buf == Z_NULL) return 0UL;\n\n#ifdef DYNAMIC_CRC_TABLE\n    if (crc_table_empty)\n        make_crc_table();\n#endif /* DYNAMIC_CRC_TABLE */\n\n#ifdef BYFOUR\n    if (sizeof(void *) == sizeof(ptrdiff_t)) {\n        u4 endian;\n\n        endian = 1;\n        if (*((unsigned char *)(&endian)))\n            return crc32_little(crc, buf, len);\n        else\n            return crc32_big(crc, buf, len);\n    }\n#endif /* BYFOUR */\n    crc = crc ^ 0xffffffffUL;\n    while (len >= 8) {\n        DO8;\n        len -= 8;\n    }\n    if (len) do {\n        DO1;\n    } while (--len);\n    return crc ^ 0xffffffffUL;\n}\n\n#ifdef BYFOUR\n\n/* ========================================================================= */\n#define DOLIT4 c ^= *buf4++; \\\n        c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \\\n            crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]\n#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4\n\n/* ========================================================================= */\nlocal unsigned long crc32_little(crc, buf, len)\n    unsigned long crc;\n    const unsigned char FAR *buf;\n    unsigned len;\n{\n    register u4 c;\n    register const u4 FAR *buf4;\n\n    c = (u4)crc;\n    c = ~c;\n    while (len && ((ptrdiff_t)buf & 3)) {\n        c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);\n        len--;\n    }\n\n    buf4 = (const u4 FAR *)(const void FAR *)buf;\n    while (len >= 32) {\n        DOLIT32;\n        len -= 32;\n    }\n    while (len >= 4) {\n        DOLIT4;\n        len -= 4;\n    }\n    buf = (const unsigned char FAR *)buf4;\n\n    if (len) do {\n        c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);\n    } while (--len);\n    c = ~c;\n    return (unsigned long)c;\n}\n\n/* ========================================================================= */\n#define DOBIG4 c ^= *++buf4; \\\n        c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \\\n            crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]\n#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4\n\n/* ========================================================================= */\nlocal unsigned long crc32_big(crc, buf, len)\n    unsigned long crc;\n    const unsigned char FAR *buf;\n    unsigned len;\n{\n    register u4 c;\n    register const u4 FAR *buf4;\n\n    c = REV((u4)crc);\n    c = ~c;\n    while (len && ((ptrdiff_t)buf & 3)) {\n        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);\n        len--;\n    }\n\n    buf4 = (const u4 FAR *)(const void FAR *)buf;\n    buf4--;\n    while (len >= 32) {\n        DOBIG32;\n        len -= 32;\n    }\n    while (len >= 4) {\n        DOBIG4;\n        len -= 4;\n    }\n    buf4++;\n    buf = (const unsigned char FAR *)buf4;\n\n    if (len) do {\n        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);\n    } while (--len);\n    c = ~c;\n    return (unsigned long)(REV(c));\n}\n\n#endif /* BYFOUR */\n\n#define GF2_DIM 32      /* dimension of GF(2) vectors (length of CRC) */\n\n/* ========================================================================= */\nlocal unsigned long gf2_matrix_times(mat, vec)\n    unsigned long *mat;\n    unsigned long vec;\n{\n    unsigned long sum;\n\n    sum = 0;\n    while (vec) {\n        if (vec & 1)\n            sum ^= *mat;\n        vec >>= 1;\n        mat++;\n    }\n    return sum;\n}\n\n/* ========================================================================= */\nlocal void gf2_matrix_square(square, mat)\n    unsigned long *square;\n    unsigned long *mat;\n{\n    int n;\n\n    for (n = 0; n < GF2_DIM; n++)\n        square[n] = gf2_matrix_times(mat, mat[n]);\n}\n\n/* ========================================================================= */\nlocal uLong crc32_combine_(crc1, crc2, len2)\n    uLong crc1;\n    uLong crc2;\n    z_off64_t len2;\n{\n    int n;\n    unsigned long row;\n    unsigned long even[GF2_DIM];    /* even-power-of-two zeros operator */\n    unsigned long odd[GF2_DIM];     /* odd-power-of-two zeros operator */\n\n    /* degenerate case (also disallow negative lengths) */\n    if (len2 <= 0)\n        return crc1;\n\n    /* put operator for one zero bit in odd */\n    odd[0] = 0xedb88320UL;          /* CRC-32 polynomial */\n    row = 1;\n    for (n = 1; n < GF2_DIM; n++) {\n        odd[n] = row;\n        row <<= 1;\n    }\n\n    /* put operator for two zero bits in even */\n    gf2_matrix_square(even, odd);\n\n    /* put operator for four zero bits in odd */\n    gf2_matrix_square(odd, even);\n\n    /* apply len2 zeros to crc1 (first square will put the operator for one\n       zero byte, eight zero bits, in even) */\n    do {\n        /* apply zeros operator for this bit of len2 */\n        gf2_matrix_square(even, odd);\n        if (len2 & 1)\n            crc1 = gf2_matrix_times(even, crc1);\n        len2 >>= 1;\n\n        /* if no more bits set, then done */\n        if (len2 == 0)\n            break;\n\n        /* another iteration of the loop with odd and even swapped */\n        gf2_matrix_square(odd, even);\n        if (len2 & 1)\n            crc1 = gf2_matrix_times(odd, crc1);\n        len2 >>= 1;\n\n        /* if no more bits set, then done */\n    } while (len2 != 0);\n\n    /* return combined crc */\n    crc1 ^= crc2;\n    return crc1;\n}\n\n/* ========================================================================= */\nuLong ZEXPORT crc32_combine(crc1, crc2, len2)\n    uLong crc1;\n    uLong crc2;\n    z_off_t len2;\n{\n    return crc32_combine_(crc1, crc2, len2);\n}\n\nuLong ZEXPORT crc32_combine64(crc1, crc2, len2)\n    uLong crc1;\n    uLong crc2;\n    z_off64_t len2;\n{\n    return crc32_combine_(crc1, crc2, len2);\n}\n"
  },
  {
    "path": "src/engine/external/zlib/crc32.h",
    "content": "/* crc32.h -- tables for rapid CRC calculation\n * Generated automatically by crc32.c\n */\n\nlocal const unsigned long FAR crc_table[TBLS][256] =\n{\n  {\n    0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,\n    0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,\n    0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,\n    0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,\n    0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,\n    0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,\n    0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,\n    0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,\n    0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,\n    0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,\n    0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,\n    0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,\n    0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,\n    0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,\n    0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,\n    0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,\n    0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,\n    0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,\n    0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,\n    0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,\n    0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,\n    0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,\n    0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,\n    0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,\n    0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,\n    0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,\n    0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,\n    0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,\n    0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,\n    0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,\n    0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,\n    0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,\n    0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,\n    0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,\n    0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,\n    0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,\n    0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,\n    0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,\n    0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,\n    0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,\n    0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,\n    0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,\n    0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,\n    0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,\n    0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,\n    0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,\n    0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,\n    0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,\n    0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,\n    0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,\n    0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,\n    0x2d02ef8dUL\n#ifdef BYFOUR\n  },\n  {\n    0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,\n    0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,\n    0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,\n    0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,\n    0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,\n    0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,\n    0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,\n    0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,\n    0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,\n    0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,\n    0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,\n    0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,\n    0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,\n    0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,\n    0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,\n    0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,\n    0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,\n    0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,\n    0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,\n    0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,\n    0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,\n    0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,\n    0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,\n    0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,\n    0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,\n    0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,\n    0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,\n    0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,\n    0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,\n    0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,\n    0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,\n    0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,\n    0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,\n    0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,\n    0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,\n    0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,\n    0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,\n    0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,\n    0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,\n    0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,\n    0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,\n    0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,\n    0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,\n    0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,\n    0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,\n    0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,\n    0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,\n    0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,\n    0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,\n    0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,\n    0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,\n    0x9324fd72UL\n  },\n  {\n    0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,\n    0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,\n    0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,\n    0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,\n    0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,\n    0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,\n    0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,\n    0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,\n    0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,\n    0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,\n    0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,\n    0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,\n    0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,\n    0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,\n    0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,\n    0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,\n    0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,\n    0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,\n    0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,\n    0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,\n    0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,\n    0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,\n    0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,\n    0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,\n    0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,\n    0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,\n    0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,\n    0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,\n    0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,\n    0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,\n    0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,\n    0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,\n    0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,\n    0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,\n    0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,\n    0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,\n    0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,\n    0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,\n    0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,\n    0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,\n    0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,\n    0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,\n    0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,\n    0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,\n    0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,\n    0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,\n    0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,\n    0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,\n    0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,\n    0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,\n    0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,\n    0xbe9834edUL\n  },\n  {\n    0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,\n    0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,\n    0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,\n    0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,\n    0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,\n    0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,\n    0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,\n    0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,\n    0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,\n    0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,\n    0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,\n    0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,\n    0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,\n    0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,\n    0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,\n    0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,\n    0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,\n    0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,\n    0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,\n    0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,\n    0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,\n    0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,\n    0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,\n    0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,\n    0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,\n    0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,\n    0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,\n    0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,\n    0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,\n    0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,\n    0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,\n    0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,\n    0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,\n    0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,\n    0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,\n    0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,\n    0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,\n    0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,\n    0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,\n    0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,\n    0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,\n    0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,\n    0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,\n    0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,\n    0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,\n    0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,\n    0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,\n    0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,\n    0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,\n    0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,\n    0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,\n    0xde0506f1UL\n  },\n  {\n    0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,\n    0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,\n    0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,\n    0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,\n    0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,\n    0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,\n    0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,\n    0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,\n    0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,\n    0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,\n    0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,\n    0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,\n    0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,\n    0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,\n    0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,\n    0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,\n    0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,\n    0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,\n    0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,\n    0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,\n    0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,\n    0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,\n    0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,\n    0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,\n    0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,\n    0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,\n    0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,\n    0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,\n    0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,\n    0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,\n    0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,\n    0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,\n    0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,\n    0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,\n    0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,\n    0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,\n    0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,\n    0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,\n    0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,\n    0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,\n    0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,\n    0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,\n    0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,\n    0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,\n    0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,\n    0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,\n    0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,\n    0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,\n    0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,\n    0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,\n    0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,\n    0x8def022dUL\n  },\n  {\n    0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,\n    0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,\n    0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,\n    0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,\n    0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,\n    0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,\n    0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,\n    0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,\n    0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,\n    0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,\n    0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,\n    0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,\n    0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,\n    0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,\n    0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,\n    0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,\n    0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,\n    0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,\n    0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,\n    0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,\n    0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,\n    0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,\n    0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,\n    0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,\n    0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,\n    0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,\n    0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,\n    0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,\n    0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,\n    0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,\n    0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,\n    0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,\n    0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,\n    0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,\n    0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,\n    0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,\n    0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,\n    0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,\n    0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,\n    0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,\n    0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,\n    0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,\n    0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,\n    0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,\n    0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,\n    0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,\n    0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,\n    0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,\n    0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,\n    0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,\n    0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,\n    0x72fd2493UL\n  },\n  {\n    0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,\n    0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,\n    0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,\n    0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,\n    0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,\n    0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,\n    0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,\n    0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,\n    0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,\n    0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,\n    0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,\n    0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,\n    0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,\n    0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,\n    0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,\n    0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,\n    0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,\n    0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,\n    0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,\n    0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,\n    0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,\n    0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,\n    0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,\n    0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,\n    0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,\n    0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,\n    0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,\n    0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,\n    0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,\n    0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,\n    0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,\n    0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,\n    0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,\n    0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,\n    0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,\n    0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,\n    0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,\n    0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,\n    0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,\n    0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,\n    0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,\n    0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,\n    0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,\n    0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,\n    0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,\n    0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,\n    0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,\n    0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,\n    0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,\n    0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,\n    0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,\n    0xed3498beUL\n  },\n  {\n    0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,\n    0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,\n    0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,\n    0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,\n    0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,\n    0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,\n    0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,\n    0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,\n    0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,\n    0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,\n    0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,\n    0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,\n    0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,\n    0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,\n    0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,\n    0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,\n    0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,\n    0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,\n    0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,\n    0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,\n    0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,\n    0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,\n    0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,\n    0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,\n    0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,\n    0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,\n    0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,\n    0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,\n    0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,\n    0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,\n    0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,\n    0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,\n    0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,\n    0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,\n    0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,\n    0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,\n    0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,\n    0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,\n    0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,\n    0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,\n    0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,\n    0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,\n    0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,\n    0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,\n    0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,\n    0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,\n    0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,\n    0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,\n    0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,\n    0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,\n    0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,\n    0xf10605deUL\n#endif\n  }\n};\n"
  },
  {
    "path": "src/engine/external/zlib/deflate.c",
    "content": "/* deflate.c -- compress data using the deflation algorithm\n * Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/*\n *  ALGORITHM\n *\n *      The \"deflation\" process depends on being able to identify portions\n *      of the input text which are identical to earlier input (within a\n *      sliding window trailing behind the input currently being processed).\n *\n *      The most straightforward technique turns out to be the fastest for\n *      most input files: try all possible matches and select the longest.\n *      The key feature of this algorithm is that insertions into the string\n *      dictionary are very simple and thus fast, and deletions are avoided\n *      completely. Insertions are performed at each input character, whereas\n *      string matches are performed only when the previous match ends. So it\n *      is preferable to spend more time in matches to allow very fast string\n *      insertions and avoid deletions. The matching algorithm for small\n *      strings is inspired from that of Rabin & Karp. A brute force approach\n *      is used to find longer strings when a small match has been found.\n *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze\n *      (by Leonid Broukhis).\n *         A previous version of this file used a more sophisticated algorithm\n *      (by Fiala and Greene) which is guaranteed to run in linear amortized\n *      time, but has a larger average cost, uses more memory and is patented.\n *      However the F&G algorithm may be faster for some highly redundant\n *      files if the parameter max_chain_length (described below) is too large.\n *\n *  ACKNOWLEDGEMENTS\n *\n *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and\n *      I found it in 'freeze' written by Leonid Broukhis.\n *      Thanks to many people for bug reports and testing.\n *\n *  REFERENCES\n *\n *      Deutsch, L.P.,\"DEFLATE Compressed Data Format Specification\".\n *      Available in http://www.ietf.org/rfc/rfc1951.txt\n *\n *      A description of the Rabin and Karp algorithm is given in the book\n *         \"Algorithms\" by R. Sedgewick, Addison-Wesley, p252.\n *\n *      Fiala,E.R., and Greene,D.H.\n *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595\n *\n */\n\n/* @(#) $Id$ */\n\n#include \"deflate.h\"\n\nconst char deflate_copyright[] =\n   \" deflate 1.2.5 Copyright 1995-2010 Jean-loup Gailly and Mark Adler \";\n/*\n  If you use the zlib library in a product, an acknowledgment is welcome\n  in the documentation of your product. If for some reason you cannot\n  include such an acknowledgment, I would appreciate that you keep this\n  copyright string in the executable of your product.\n */\n\n/* ===========================================================================\n *  Function prototypes.\n */\ntypedef enum {\n    need_more,      /* block not completed, need more input or more output */\n    block_done,     /* block flush performed */\n    finish_started, /* finish started, need only more output at next deflate */\n    finish_done     /* finish done, accept no more input or output */\n} block_state;\n\ntypedef block_state (*compress_func) OF((deflate_state *s, int flush));\n/* Compression function. Returns the block state after the call. */\n\nlocal void fill_window    OF((deflate_state *s));\nlocal block_state deflate_stored OF((deflate_state *s, int flush));\nlocal block_state deflate_fast   OF((deflate_state *s, int flush));\n#ifndef FASTEST\nlocal block_state deflate_slow   OF((deflate_state *s, int flush));\n#endif\nlocal block_state deflate_rle    OF((deflate_state *s, int flush));\nlocal block_state deflate_huff   OF((deflate_state *s, int flush));\nlocal void lm_init        OF((deflate_state *s));\nlocal void putShortMSB    OF((deflate_state *s, uInt b));\nlocal void flush_pending  OF((z_streamp strm));\nlocal int read_buf        OF((z_streamp strm, Bytef *buf, unsigned size));\n#ifdef ASMV\n      void match_init OF((void)); /* asm code initialization */\n      uInt longest_match  OF((deflate_state *s, IPos cur_match));\n#else\nlocal uInt longest_match  OF((deflate_state *s, IPos cur_match));\n#endif\n\n#ifdef DEBUG\nlocal  void check_match OF((deflate_state *s, IPos start, IPos match,\n                            int length));\n#endif\n\n/* ===========================================================================\n * Local data\n */\n\n#define NIL 0\n/* Tail of hash chains */\n\n#ifndef TOO_FAR\n#  define TOO_FAR 4096\n#endif\n/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\ntypedef struct config_s {\n   ush good_length; /* reduce lazy search above this match length */\n   ush max_lazy;    /* do not perform lazy search above this match length */\n   ush nice_length; /* quit search above this match length */\n   ush max_chain;\n   compress_func func;\n} config;\n\n#ifdef FASTEST\nlocal const config configuration_table[2] = {\n/*      good lazy nice chain */\n/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */\n/* 1 */ {4,    4,  8,    4, deflate_fast}}; /* max speed, no lazy matches */\n#else\nlocal const config configuration_table[10] = {\n/*      good lazy nice chain */\n/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */\n/* 1 */ {4,    4,  8,    4, deflate_fast}, /* max speed, no lazy matches */\n/* 2 */ {4,    5, 16,    8, deflate_fast},\n/* 3 */ {4,    6, 32,   32, deflate_fast},\n\n/* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */\n/* 5 */ {8,   16, 32,   32, deflate_slow},\n/* 6 */ {8,   16, 128, 128, deflate_slow},\n/* 7 */ {8,   32, 128, 256, deflate_slow},\n/* 8 */ {32, 128, 258, 1024, deflate_slow},\n/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */\n#endif\n\n/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4\n * For deflate_fast() (levels <= 3) good is ignored and lazy has a different\n * meaning.\n */\n\n#define EQUAL 0\n/* result of memcmp for equal strings */\n\n#ifndef NO_DUMMY_DECL\nstruct static_tree_desc_s {int dummy;}; /* for buggy compilers */\n#endif\n\n/* ===========================================================================\n * Update a hash value with the given input byte\n * IN  assertion: all calls to to UPDATE_HASH are made with consecutive\n *    input characters, so that a running hash key can be computed from the\n *    previous key instead of complete recalculation each time.\n */\n#define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)\n\n\n/* ===========================================================================\n * Insert string str in the dictionary and set match_head to the previous head\n * of the hash chain (the most recent string with same hash key). Return\n * the previous length of the hash chain.\n * If this file is compiled with -DFASTEST, the compression level is forced\n * to 1, and no hash chains are maintained.\n * IN  assertion: all calls to to INSERT_STRING are made with consecutive\n *    input characters and the first MIN_MATCH bytes of str are valid\n *    (except for the last MIN_MATCH-1 bytes of the input file).\n */\n#ifdef FASTEST\n#define INSERT_STRING(s, str, match_head) \\\n   (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \\\n    match_head = s->head[s->ins_h], \\\n    s->head[s->ins_h] = (Pos)(str))\n#else\n#define INSERT_STRING(s, str, match_head) \\\n   (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \\\n    match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \\\n    s->head[s->ins_h] = (Pos)(str))\n#endif\n\n/* ===========================================================================\n * Initialize the hash table (avoiding 64K overflow for 16 bit systems).\n * prev[] will be initialized on the fly.\n */\n#define CLEAR_HASH(s) \\\n    s->head[s->hash_size-1] = NIL; \\\n    zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));\n\n/* ========================================================================= */\nint ZEXPORT deflateInit_(strm, level, version, stream_size)\n    z_streamp strm;\n    int level;\n    const char *version;\n    int stream_size;\n{\n    return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,\n                         Z_DEFAULT_STRATEGY, version, stream_size);\n    /* To do: ignore strm->next_in if we use it as window */\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,\n                  version, stream_size)\n    z_streamp strm;\n    int  level;\n    int  method;\n    int  windowBits;\n    int  memLevel;\n    int  strategy;\n    const char *version;\n    int stream_size;\n{\n    deflate_state *s;\n    int wrap = 1;\n    static const char my_version[] = ZLIB_VERSION;\n\n    ushf *overlay;\n    /* We overlay pending_buf and d_buf+l_buf. This works since the average\n     * output size for (length,distance) codes is <= 24 bits.\n     */\n\n    if (version == Z_NULL || version[0] != my_version[0] ||\n        stream_size != sizeof(z_stream)) {\n        return Z_VERSION_ERROR;\n    }\n    if (strm == Z_NULL) return Z_STREAM_ERROR;\n\n    strm->msg = Z_NULL;\n    if (strm->zalloc == (alloc_func)0) {\n        strm->zalloc = zcalloc;\n        strm->opaque = (voidpf)0;\n    }\n    if (strm->zfree == (free_func)0) strm->zfree = zcfree;\n\n#ifdef FASTEST\n    if (level != 0) level = 1;\n#else\n    if (level == Z_DEFAULT_COMPRESSION) level = 6;\n#endif\n\n    if (windowBits < 0) { /* suppress zlib wrapper */\n        wrap = 0;\n        windowBits = -windowBits;\n    }\n#ifdef GZIP\n    else if (windowBits > 15) {\n        wrap = 2;       /* write gzip wrapper instead */\n        windowBits -= 16;\n    }\n#endif\n    if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||\n        windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n        strategy < 0 || strategy > Z_FIXED) {\n        return Z_STREAM_ERROR;\n    }\n    if (windowBits == 8) windowBits = 9;  /* until 256-byte window bug fixed */\n    s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));\n    if (s == Z_NULL) return Z_MEM_ERROR;\n    strm->state = (struct internal_state FAR *)s;\n    s->strm = strm;\n\n    s->wrap = wrap;\n    s->gzhead = Z_NULL;\n    s->w_bits = windowBits;\n    s->w_size = 1 << s->w_bits;\n    s->w_mask = s->w_size - 1;\n\n    s->hash_bits = memLevel + 7;\n    s->hash_size = 1 << s->hash_bits;\n    s->hash_mask = s->hash_size - 1;\n    s->hash_shift =  ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);\n\n    s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));\n    s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));\n    s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));\n\n    s->high_water = 0;      /* nothing written to s->window yet */\n\n    s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n    overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);\n    s->pending_buf = (uchf *) overlay;\n    s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);\n\n    if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||\n        s->pending_buf == Z_NULL) {\n        s->status = FINISH_STATE;\n        strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);\n        deflateEnd (strm);\n        return Z_MEM_ERROR;\n    }\n    s->d_buf = overlay + s->lit_bufsize/sizeof(ush);\n    s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;\n\n    s->level = level;\n    s->strategy = strategy;\n    s->method = (Byte)method;\n\n    return deflateReset(strm);\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)\n    z_streamp strm;\n    const Bytef *dictionary;\n    uInt  dictLength;\n{\n    deflate_state *s;\n    uInt length = dictLength;\n    uInt n;\n    IPos hash_head = 0;\n\n    if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||\n        strm->state->wrap == 2 ||\n        (strm->state->wrap == 1 && strm->state->status != INIT_STATE))\n        return Z_STREAM_ERROR;\n\n    s = strm->state;\n    if (s->wrap)\n        strm->adler = adler32(strm->adler, dictionary, dictLength);\n\n    if (length < MIN_MATCH) return Z_OK;\n    if (length > s->w_size) {\n        length = s->w_size;\n        dictionary += dictLength - length; /* use the tail of the dictionary */\n    }\n    zmemcpy(s->window, dictionary, length);\n    s->strstart = length;\n    s->block_start = (long)length;\n\n    /* Insert all strings in the hash table (except for the last two bytes).\n     * s->lookahead stays null, so s->ins_h will be recomputed at the next\n     * call of fill_window.\n     */\n    s->ins_h = s->window[0];\n    UPDATE_HASH(s, s->ins_h, s->window[1]);\n    for (n = 0; n <= length - MIN_MATCH; n++) {\n        INSERT_STRING(s, n, hash_head);\n    }\n    if (hash_head) hash_head = 0;  /* to make compiler happy */\n    return Z_OK;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateReset (strm)\n    z_streamp strm;\n{\n    deflate_state *s;\n\n    if (strm == Z_NULL || strm->state == Z_NULL ||\n        strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {\n        return Z_STREAM_ERROR;\n    }\n\n    strm->total_in = strm->total_out = 0;\n    strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */\n    strm->data_type = Z_UNKNOWN;\n\n    s = (deflate_state *)strm->state;\n    s->pending = 0;\n    s->pending_out = s->pending_buf;\n\n    if (s->wrap < 0) {\n        s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */\n    }\n    s->status = s->wrap ? INIT_STATE : BUSY_STATE;\n    strm->adler =\n#ifdef GZIP\n        s->wrap == 2 ? crc32(0L, Z_NULL, 0) :\n#endif\n        adler32(0L, Z_NULL, 0);\n    s->last_flush = Z_NO_FLUSH;\n\n    _tr_init(s);\n    lm_init(s);\n\n    return Z_OK;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateSetHeader (strm, head)\n    z_streamp strm;\n    gz_headerp head;\n{\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    if (strm->state->wrap != 2) return Z_STREAM_ERROR;\n    strm->state->gzhead = head;\n    return Z_OK;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflatePrime (strm, bits, value)\n    z_streamp strm;\n    int bits;\n    int value;\n{\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    strm->state->bi_valid = bits;\n    strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));\n    return Z_OK;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateParams(strm, level, strategy)\n    z_streamp strm;\n    int level;\n    int strategy;\n{\n    deflate_state *s;\n    compress_func func;\n    int err = Z_OK;\n\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    s = strm->state;\n\n#ifdef FASTEST\n    if (level != 0) level = 1;\n#else\n    if (level == Z_DEFAULT_COMPRESSION) level = 6;\n#endif\n    if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {\n        return Z_STREAM_ERROR;\n    }\n    func = configuration_table[s->level].func;\n\n    if ((strategy != s->strategy || func != configuration_table[level].func) &&\n        strm->total_in != 0) {\n        /* Flush the last buffer: */\n        err = deflate(strm, Z_BLOCK);\n    }\n    if (s->level != level) {\n        s->level = level;\n        s->max_lazy_match   = configuration_table[level].max_lazy;\n        s->good_match       = configuration_table[level].good_length;\n        s->nice_match       = configuration_table[level].nice_length;\n        s->max_chain_length = configuration_table[level].max_chain;\n    }\n    s->strategy = strategy;\n    return err;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)\n    z_streamp strm;\n    int good_length;\n    int max_lazy;\n    int nice_length;\n    int max_chain;\n{\n    deflate_state *s;\n\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    s = strm->state;\n    s->good_match = good_length;\n    s->max_lazy_match = max_lazy;\n    s->nice_match = nice_length;\n    s->max_chain_length = max_chain;\n    return Z_OK;\n}\n\n/* =========================================================================\n * For the default windowBits of 15 and memLevel of 8, this function returns\n * a close to exact, as well as small, upper bound on the compressed size.\n * They are coded as constants here for a reason--if the #define's are\n * changed, then this function needs to be changed as well.  The return\n * value for 15 and 8 only works for those exact settings.\n *\n * For any setting other than those defaults for windowBits and memLevel,\n * the value returned is a conservative worst case for the maximum expansion\n * resulting from using fixed blocks instead of stored blocks, which deflate\n * can emit on compressed data for some combinations of the parameters.\n *\n * This function could be more sophisticated to provide closer upper bounds for\n * every combination of windowBits and memLevel.  But even the conservative\n * upper bound of about 14% expansion does not seem onerous for output buffer\n * allocation.\n */\nuLong ZEXPORT deflateBound(strm, sourceLen)\n    z_streamp strm;\n    uLong sourceLen;\n{\n    deflate_state *s;\n    uLong complen, wraplen;\n    Bytef *str;\n\n    /* conservative upper bound for compressed data */\n    complen = sourceLen +\n              ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;\n\n    /* if can't get parameters, return conservative bound plus zlib wrapper */\n    if (strm == Z_NULL || strm->state == Z_NULL)\n        return complen + 6;\n\n    /* compute wrapper length */\n    s = strm->state;\n    switch (s->wrap) {\n    case 0:                                 /* raw deflate */\n        wraplen = 0;\n        break;\n    case 1:                                 /* zlib wrapper */\n        wraplen = 6 + (s->strstart ? 4 : 0);\n        break;\n    case 2:                                 /* gzip wrapper */\n        wraplen = 18;\n        if (s->gzhead != Z_NULL) {          /* user-supplied gzip header */\n            if (s->gzhead->extra != Z_NULL)\n                wraplen += 2 + s->gzhead->extra_len;\n            str = s->gzhead->name;\n            if (str != Z_NULL)\n                do {\n                    wraplen++;\n                } while (*str++);\n            str = s->gzhead->comment;\n            if (str != Z_NULL)\n                do {\n                    wraplen++;\n                } while (*str++);\n            if (s->gzhead->hcrc)\n                wraplen += 2;\n        }\n        break;\n    default:                                /* for compiler happiness */\n        wraplen = 6;\n    }\n\n    /* if not default parameters, return conservative bound */\n    if (s->w_bits != 15 || s->hash_bits != 8 + 7)\n        return complen + wraplen;\n\n    /* default settings: return tight bound for that case */\n    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +\n           (sourceLen >> 25) + 13 - 6 + wraplen;\n}\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nlocal void putShortMSB (s, b)\n    deflate_state *s;\n    uInt b;\n{\n    put_byte(s, (Byte)(b >> 8));\n    put_byte(s, (Byte)(b & 0xff));\n}\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output goes\n * through this function so some applications may wish to modify it\n * to avoid allocating a large strm->next_out buffer and copying into it.\n * (See also read_buf()).\n */\nlocal void flush_pending(strm)\n    z_streamp strm;\n{\n    unsigned len = strm->state->pending;\n\n    if (len > strm->avail_out) len = strm->avail_out;\n    if (len == 0) return;\n\n    zmemcpy(strm->next_out, strm->state->pending_out, len);\n    strm->next_out  += len;\n    strm->state->pending_out  += len;\n    strm->total_out += len;\n    strm->avail_out  -= len;\n    strm->state->pending -= len;\n    if (strm->state->pending == 0) {\n        strm->state->pending_out = strm->state->pending_buf;\n    }\n}\n\n/* ========================================================================= */\nint ZEXPORT deflate (strm, flush)\n    z_streamp strm;\n    int flush;\n{\n    int old_flush; /* value of flush param for previous deflate call */\n    deflate_state *s;\n\n    if (strm == Z_NULL || strm->state == Z_NULL ||\n        flush > Z_BLOCK || flush < 0) {\n        return Z_STREAM_ERROR;\n    }\n    s = strm->state;\n\n    if (strm->next_out == Z_NULL ||\n        (strm->next_in == Z_NULL && strm->avail_in != 0) ||\n        (s->status == FINISH_STATE && flush != Z_FINISH)) {\n        ERR_RETURN(strm, Z_STREAM_ERROR);\n    }\n    if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);\n\n    s->strm = strm; /* just in case */\n    old_flush = s->last_flush;\n    s->last_flush = flush;\n\n    /* Write the header */\n    if (s->status == INIT_STATE) {\n#ifdef GZIP\n        if (s->wrap == 2) {\n            strm->adler = crc32(0L, Z_NULL, 0);\n            put_byte(s, 31);\n            put_byte(s, 139);\n            put_byte(s, 8);\n            if (s->gzhead == Z_NULL) {\n                put_byte(s, 0);\n                put_byte(s, 0);\n                put_byte(s, 0);\n                put_byte(s, 0);\n                put_byte(s, 0);\n                put_byte(s, s->level == 9 ? 2 :\n                            (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?\n                             4 : 0));\n                put_byte(s, OS_CODE);\n                s->status = BUSY_STATE;\n            }\n            else {\n                put_byte(s, (s->gzhead->text ? 1 : 0) +\n                            (s->gzhead->hcrc ? 2 : 0) +\n                            (s->gzhead->extra == Z_NULL ? 0 : 4) +\n                            (s->gzhead->name == Z_NULL ? 0 : 8) +\n                            (s->gzhead->comment == Z_NULL ? 0 : 16)\n                        );\n                put_byte(s, (Byte)(s->gzhead->time & 0xff));\n                put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));\n                put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));\n                put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));\n                put_byte(s, s->level == 9 ? 2 :\n                            (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?\n                             4 : 0));\n                put_byte(s, s->gzhead->os & 0xff);\n                if (s->gzhead->extra != Z_NULL) {\n                    put_byte(s, s->gzhead->extra_len & 0xff);\n                    put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);\n                }\n                if (s->gzhead->hcrc)\n                    strm->adler = crc32(strm->adler, s->pending_buf,\n                                        s->pending);\n                s->gzindex = 0;\n                s->status = EXTRA_STATE;\n            }\n        }\n        else\n#endif\n        {\n            uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;\n            uInt level_flags;\n\n            if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)\n                level_flags = 0;\n            else if (s->level < 6)\n                level_flags = 1;\n            else if (s->level == 6)\n                level_flags = 2;\n            else\n                level_flags = 3;\n            header |= (level_flags << 6);\n            if (s->strstart != 0) header |= PRESET_DICT;\n            header += 31 - (header % 31);\n\n            s->status = BUSY_STATE;\n            putShortMSB(s, header);\n\n            /* Save the adler32 of the preset dictionary: */\n            if (s->strstart != 0) {\n                putShortMSB(s, (uInt)(strm->adler >> 16));\n                putShortMSB(s, (uInt)(strm->adler & 0xffff));\n            }\n            strm->adler = adler32(0L, Z_NULL, 0);\n        }\n    }\n#ifdef GZIP\n    if (s->status == EXTRA_STATE) {\n        if (s->gzhead->extra != Z_NULL) {\n            uInt beg = s->pending;  /* start of bytes to update crc */\n\n            while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {\n                if (s->pending == s->pending_buf_size) {\n                    if (s->gzhead->hcrc && s->pending > beg)\n                        strm->adler = crc32(strm->adler, s->pending_buf + beg,\n                                            s->pending - beg);\n                    flush_pending(strm);\n                    beg = s->pending;\n                    if (s->pending == s->pending_buf_size)\n                        break;\n                }\n                put_byte(s, s->gzhead->extra[s->gzindex]);\n                s->gzindex++;\n            }\n            if (s->gzhead->hcrc && s->pending > beg)\n                strm->adler = crc32(strm->adler, s->pending_buf + beg,\n                                    s->pending - beg);\n            if (s->gzindex == s->gzhead->extra_len) {\n                s->gzindex = 0;\n                s->status = NAME_STATE;\n            }\n        }\n        else\n            s->status = NAME_STATE;\n    }\n    if (s->status == NAME_STATE) {\n        if (s->gzhead->name != Z_NULL) {\n            uInt beg = s->pending;  /* start of bytes to update crc */\n            int val;\n\n            do {\n                if (s->pending == s->pending_buf_size) {\n                    if (s->gzhead->hcrc && s->pending > beg)\n                        strm->adler = crc32(strm->adler, s->pending_buf + beg,\n                                            s->pending - beg);\n                    flush_pending(strm);\n                    beg = s->pending;\n                    if (s->pending == s->pending_buf_size) {\n                        val = 1;\n                        break;\n                    }\n                }\n                val = s->gzhead->name[s->gzindex++];\n                put_byte(s, val);\n            } while (val != 0);\n            if (s->gzhead->hcrc && s->pending > beg)\n                strm->adler = crc32(strm->adler, s->pending_buf + beg,\n                                    s->pending - beg);\n            if (val == 0) {\n                s->gzindex = 0;\n                s->status = COMMENT_STATE;\n            }\n        }\n        else\n            s->status = COMMENT_STATE;\n    }\n    if (s->status == COMMENT_STATE) {\n        if (s->gzhead->comment != Z_NULL) {\n            uInt beg = s->pending;  /* start of bytes to update crc */\n            int val;\n\n            do {\n                if (s->pending == s->pending_buf_size) {\n                    if (s->gzhead->hcrc && s->pending > beg)\n                        strm->adler = crc32(strm->adler, s->pending_buf + beg,\n                                            s->pending - beg);\n                    flush_pending(strm);\n                    beg = s->pending;\n                    if (s->pending == s->pending_buf_size) {\n                        val = 1;\n                        break;\n                    }\n                }\n                val = s->gzhead->comment[s->gzindex++];\n                put_byte(s, val);\n            } while (val != 0);\n            if (s->gzhead->hcrc && s->pending > beg)\n                strm->adler = crc32(strm->adler, s->pending_buf + beg,\n                                    s->pending - beg);\n            if (val == 0)\n                s->status = HCRC_STATE;\n        }\n        else\n            s->status = HCRC_STATE;\n    }\n    if (s->status == HCRC_STATE) {\n        if (s->gzhead->hcrc) {\n            if (s->pending + 2 > s->pending_buf_size)\n                flush_pending(strm);\n            if (s->pending + 2 <= s->pending_buf_size) {\n                put_byte(s, (Byte)(strm->adler & 0xff));\n                put_byte(s, (Byte)((strm->adler >> 8) & 0xff));\n                strm->adler = crc32(0L, Z_NULL, 0);\n                s->status = BUSY_STATE;\n            }\n        }\n        else\n            s->status = BUSY_STATE;\n    }\n#endif\n\n    /* Flush as much pending output as possible */\n    if (s->pending != 0) {\n        flush_pending(strm);\n        if (strm->avail_out == 0) {\n            /* Since avail_out is 0, deflate will be called again with\n             * more output space, but possibly with both pending and\n             * avail_in equal to zero. There won't be anything to do,\n             * but this is not an error situation so make sure we\n             * return OK instead of BUF_ERROR at next call of deflate:\n             */\n            s->last_flush = -1;\n            return Z_OK;\n        }\n\n    /* Make sure there is something to do and avoid duplicate consecutive\n     * flushes. For repeated and useless calls with Z_FINISH, we keep\n     * returning Z_STREAM_END instead of Z_BUF_ERROR.\n     */\n    } else if (strm->avail_in == 0 && flush <= old_flush &&\n               flush != Z_FINISH) {\n        ERR_RETURN(strm, Z_BUF_ERROR);\n    }\n\n    /* User must not provide more input after the first FINISH: */\n    if (s->status == FINISH_STATE && strm->avail_in != 0) {\n        ERR_RETURN(strm, Z_BUF_ERROR);\n    }\n\n    /* Start a new block or continue the current one.\n     */\n    if (strm->avail_in != 0 || s->lookahead != 0 ||\n        (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {\n        block_state bstate;\n\n        bstate = s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :\n                    (s->strategy == Z_RLE ? deflate_rle(s, flush) :\n                        (*(configuration_table[s->level].func))(s, flush));\n\n        if (bstate == finish_started || bstate == finish_done) {\n            s->status = FINISH_STATE;\n        }\n        if (bstate == need_more || bstate == finish_started) {\n            if (strm->avail_out == 0) {\n                s->last_flush = -1; /* avoid BUF_ERROR next call, see above */\n            }\n            return Z_OK;\n            /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n             * of deflate should use the same flush parameter to make sure\n             * that the flush is complete. So we don't have to output an\n             * empty block here, this will be done at next call. This also\n             * ensures that for a very small output buffer, we emit at most\n             * one empty block.\n             */\n        }\n        if (bstate == block_done) {\n            if (flush == Z_PARTIAL_FLUSH) {\n                _tr_align(s);\n            } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */\n                _tr_stored_block(s, (char*)0, 0L, 0);\n                /* For a full flush, this empty block will be recognized\n                 * as a special marker by inflate_sync().\n                 */\n                if (flush == Z_FULL_FLUSH) {\n                    CLEAR_HASH(s);             /* forget history */\n                    if (s->lookahead == 0) {\n                        s->strstart = 0;\n                        s->block_start = 0L;\n                    }\n                }\n            }\n            flush_pending(strm);\n            if (strm->avail_out == 0) {\n              s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n              return Z_OK;\n            }\n        }\n    }\n    Assert(strm->avail_out > 0, \"bug2\");\n\n    if (flush != Z_FINISH) return Z_OK;\n    if (s->wrap <= 0) return Z_STREAM_END;\n\n    /* Write the trailer */\n#ifdef GZIP\n    if (s->wrap == 2) {\n        put_byte(s, (Byte)(strm->adler & 0xff));\n        put_byte(s, (Byte)((strm->adler >> 8) & 0xff));\n        put_byte(s, (Byte)((strm->adler >> 16) & 0xff));\n        put_byte(s, (Byte)((strm->adler >> 24) & 0xff));\n        put_byte(s, (Byte)(strm->total_in & 0xff));\n        put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));\n        put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));\n        put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));\n    }\n    else\n#endif\n    {\n        putShortMSB(s, (uInt)(strm->adler >> 16));\n        putShortMSB(s, (uInt)(strm->adler & 0xffff));\n    }\n    flush_pending(strm);\n    /* If avail_out is zero, the application will call deflate again\n     * to flush the rest.\n     */\n    if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */\n    return s->pending != 0 ? Z_OK : Z_STREAM_END;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateEnd (strm)\n    z_streamp strm;\n{\n    int status;\n\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n\n    status = strm->state->status;\n    if (status != INIT_STATE &&\n        status != EXTRA_STATE &&\n        status != NAME_STATE &&\n        status != COMMENT_STATE &&\n        status != HCRC_STATE &&\n        status != BUSY_STATE &&\n        status != FINISH_STATE) {\n      return Z_STREAM_ERROR;\n    }\n\n    /* Deallocate in reverse order of allocations: */\n    TRY_FREE(strm, strm->state->pending_buf);\n    TRY_FREE(strm, strm->state->head);\n    TRY_FREE(strm, strm->state->prev);\n    TRY_FREE(strm, strm->state->window);\n\n    ZFREE(strm, strm->state);\n    strm->state = Z_NULL;\n\n    return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;\n}\n\n/* =========================================================================\n * Copy the source state to the destination state.\n * To simplify the source, this is not supported for 16-bit MSDOS (which\n * doesn't have enough memory anyway to duplicate compression states).\n */\nint ZEXPORT deflateCopy (dest, source)\n    z_streamp dest;\n    z_streamp source;\n{\n#ifdef MAXSEG_64K\n    return Z_STREAM_ERROR;\n#else\n    deflate_state *ds;\n    deflate_state *ss;\n    ushf *overlay;\n\n\n    if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {\n        return Z_STREAM_ERROR;\n    }\n\n    ss = source->state;\n\n    zmemcpy(dest, source, sizeof(z_stream));\n\n    ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));\n    if (ds == Z_NULL) return Z_MEM_ERROR;\n    dest->state = (struct internal_state FAR *) ds;\n    zmemcpy(ds, ss, sizeof(deflate_state));\n    ds->strm = dest;\n\n    ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));\n    ds->prev   = (Posf *)  ZALLOC(dest, ds->w_size, sizeof(Pos));\n    ds->head   = (Posf *)  ZALLOC(dest, ds->hash_size, sizeof(Pos));\n    overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);\n    ds->pending_buf = (uchf *) overlay;\n\n    if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||\n        ds->pending_buf == Z_NULL) {\n        deflateEnd (dest);\n        return Z_MEM_ERROR;\n    }\n    /* following zmemcpy do not work for 16-bit MSDOS */\n    zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));\n    zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));\n    zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));\n    zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);\n\n    ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);\n    ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);\n    ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;\n\n    ds->l_desc.dyn_tree = ds->dyn_ltree;\n    ds->d_desc.dyn_tree = ds->dyn_dtree;\n    ds->bl_desc.dyn_tree = ds->bl_tree;\n\n    return Z_OK;\n#endif /* MAXSEG_64K */\n}\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read.  All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->next_in buffer and copying from it.\n * (See also flush_pending()).\n */\nlocal int read_buf(strm, buf, size)\n    z_streamp strm;\n    Bytef *buf;\n    unsigned size;\n{\n    unsigned len = strm->avail_in;\n\n    if (len > size) len = size;\n    if (len == 0) return 0;\n\n    strm->avail_in  -= len;\n\n    if (strm->state->wrap == 1) {\n        strm->adler = adler32(strm->adler, strm->next_in, len);\n    }\n#ifdef GZIP\n    else if (strm->state->wrap == 2) {\n        strm->adler = crc32(strm->adler, strm->next_in, len);\n    }\n#endif\n    zmemcpy(buf, strm->next_in, len);\n    strm->next_in  += len;\n    strm->total_in += len;\n\n    return (int)len;\n}\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nlocal void lm_init (s)\n    deflate_state *s;\n{\n    s->window_size = (ulg)2L*s->w_size;\n\n    CLEAR_HASH(s);\n\n    /* Set the default configuration parameters:\n     */\n    s->max_lazy_match   = configuration_table[s->level].max_lazy;\n    s->good_match       = configuration_table[s->level].good_length;\n    s->nice_match       = configuration_table[s->level].nice_length;\n    s->max_chain_length = configuration_table[s->level].max_chain;\n\n    s->strstart = 0;\n    s->block_start = 0L;\n    s->lookahead = 0;\n    s->match_length = s->prev_length = MIN_MATCH-1;\n    s->match_available = 0;\n    s->ins_h = 0;\n#ifndef FASTEST\n#ifdef ASMV\n    match_init(); /* initialize the asm code */\n#endif\n#endif\n}\n\n#ifndef FASTEST\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\n#ifndef ASMV\n/* For 80x86 and 680x0, an optimized version will be provided in match.asm or\n * match.S. The code will be functionally equivalent.\n */\nlocal uInt longest_match(s, cur_match)\n    deflate_state *s;\n    IPos cur_match;                             /* current match */\n{\n    unsigned chain_length = s->max_chain_length;/* max hash chain length */\n    register Bytef *scan = s->window + s->strstart; /* current string */\n    register Bytef *match;                       /* matched string */\n    register int len;                           /* length of current match */\n    int best_len = s->prev_length;              /* best match length so far */\n    int nice_match = s->nice_match;             /* stop if match long enough */\n    IPos limit = s->strstart > (IPos)MAX_DIST(s) ?\n        s->strstart - (IPos)MAX_DIST(s) : NIL;\n    /* Stop when cur_match becomes <= limit. To simplify the code,\n     * we prevent matches with the string of window index 0.\n     */\n    Posf *prev = s->prev;\n    uInt wmask = s->w_mask;\n\n#ifdef UNALIGNED_OK\n    /* Compare two bytes at a time. Note: this is not always beneficial.\n     * Try with and without -DUNALIGNED_OK to check.\n     */\n    register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;\n    register ush scan_start = *(ushf*)scan;\n    register ush scan_end   = *(ushf*)(scan+best_len-1);\n#else\n    register Bytef *strend = s->window + s->strstart + MAX_MATCH;\n    register Byte scan_end1  = scan[best_len-1];\n    register Byte scan_end   = scan[best_len];\n#endif\n\n    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n     * It is easy to get rid of this optimization if necessary.\n     */\n    Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n    /* Do not waste too much time if we already have a good match: */\n    if (s->prev_length >= s->good_match) {\n        chain_length >>= 2;\n    }\n    /* Do not look for matches beyond the end of the input. This is necessary\n     * to make deflate deterministic.\n     */\n    if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;\n\n    Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n    do {\n        Assert(cur_match < s->strstart, \"no future\");\n        match = s->window + cur_match;\n\n        /* Skip to next match if the match length cannot increase\n         * or if the match length is less than 2.  Note that the checks below\n         * for insufficient lookahead only occur occasionally for performance\n         * reasons.  Therefore uninitialized memory will be accessed, and\n         * conditional jumps will be made that depend on those values.\n         * However the length of the match is limited to the lookahead, so\n         * the output of deflate is not affected by the uninitialized values.\n         */\n#if (defined(UNALIGNED_OK) && MAX_MATCH == 258)\n        /* This code assumes sizeof(unsigned short) == 2. Do not use\n         * UNALIGNED_OK if your compiler uses a different size.\n         */\n        if (*(ushf*)(match+best_len-1) != scan_end ||\n            *(ushf*)match != scan_start) continue;\n\n        /* It is not necessary to compare scan[2] and match[2] since they are\n         * always equal when the other bytes match, given that the hash keys\n         * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at\n         * strstart+3, +5, ... up to strstart+257. We check for insufficient\n         * lookahead only every 4th comparison; the 128th check will be made\n         * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is\n         * necessary to put more guard bytes at the end of the window, or\n         * to check more often for insufficient lookahead.\n         */\n        Assert(scan[2] == match[2], \"scan[2]?\");\n        scan++, match++;\n        do {\n        } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&\n                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&\n                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&\n                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&\n                 scan < strend);\n        /* The funny \"do {}\" generates better code on most compilers */\n\n        /* Here, scan <= window+strstart+257 */\n        Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n        if (*scan == *match) scan++;\n\n        len = (MAX_MATCH - 1) - (int)(strend-scan);\n        scan = strend - (MAX_MATCH-1);\n\n#else /* UNALIGNED_OK */\n\n        if (match[best_len]   != scan_end  ||\n            match[best_len-1] != scan_end1 ||\n            *match            != *scan     ||\n            *++match          != scan[1])      continue;\n\n        /* The check at best_len-1 can be removed because it will be made\n         * again later. (This heuristic is not always a win.)\n         * It is not necessary to compare scan[2] and match[2] since they\n         * are always equal when the other bytes match, given that\n         * the hash keys are equal and that HASH_BITS >= 8.\n         */\n        scan += 2, match++;\n        Assert(*scan == *match, \"match[2]?\");\n\n        /* We check for insufficient lookahead only every 8th comparison;\n         * the 256th check will be made at strstart+258.\n         */\n        do {\n        } while (*++scan == *++match && *++scan == *++match &&\n                 *++scan == *++match && *++scan == *++match &&\n                 *++scan == *++match && *++scan == *++match &&\n                 *++scan == *++match && *++scan == *++match &&\n                 scan < strend);\n\n        Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n        len = MAX_MATCH - (int)(strend - scan);\n        scan = strend - MAX_MATCH;\n\n#endif /* UNALIGNED_OK */\n\n        if (len > best_len) {\n            s->match_start = cur_match;\n            best_len = len;\n            if (len >= nice_match) break;\n#ifdef UNALIGNED_OK\n            scan_end = *(ushf*)(scan+best_len-1);\n#else\n            scan_end1  = scan[best_len-1];\n            scan_end   = scan[best_len];\n#endif\n        }\n    } while ((cur_match = prev[cur_match & wmask]) > limit\n             && --chain_length != 0);\n\n    if ((uInt)best_len <= s->lookahead) return (uInt)best_len;\n    return s->lookahead;\n}\n#endif /* ASMV */\n\n#else /* FASTEST */\n\n/* ---------------------------------------------------------------------------\n * Optimized version for FASTEST only\n */\nlocal uInt longest_match(s, cur_match)\n    deflate_state *s;\n    IPos cur_match;                             /* current match */\n{\n    register Bytef *scan = s->window + s->strstart; /* current string */\n    register Bytef *match;                       /* matched string */\n    register int len;                           /* length of current match */\n    register Bytef *strend = s->window + s->strstart + MAX_MATCH;\n\n    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n     * It is easy to get rid of this optimization if necessary.\n     */\n    Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n    Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n    Assert(cur_match < s->strstart, \"no future\");\n\n    match = s->window + cur_match;\n\n    /* Return failure if the match length is less than 2:\n     */\n    if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;\n\n    /* The check at best_len-1 can be removed because it will be made\n     * again later. (This heuristic is not always a win.)\n     * It is not necessary to compare scan[2] and match[2] since they\n     * are always equal when the other bytes match, given that\n     * the hash keys are equal and that HASH_BITS >= 8.\n     */\n    scan += 2, match += 2;\n    Assert(*scan == *match, \"match[2]?\");\n\n    /* We check for insufficient lookahead only every 8th comparison;\n     * the 256th check will be made at strstart+258.\n     */\n    do {\n    } while (*++scan == *++match && *++scan == *++match &&\n             *++scan == *++match && *++scan == *++match &&\n             *++scan == *++match && *++scan == *++match &&\n             *++scan == *++match && *++scan == *++match &&\n             scan < strend);\n\n    Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n    len = MAX_MATCH - (int)(strend - scan);\n\n    if (len < MIN_MATCH) return MIN_MATCH - 1;\n\n    s->match_start = cur_match;\n    return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;\n}\n\n#endif /* FASTEST */\n\n#ifdef DEBUG\n/* ===========================================================================\n * Check that the match at match_start is indeed a match.\n */\nlocal void check_match(s, start, match, length)\n    deflate_state *s;\n    IPos start, match;\n    int length;\n{\n    /* check that the match is indeed a match */\n    if (zmemcmp(s->window + match,\n                s->window + start, length) != EQUAL) {\n        fprintf(stderr, \" start %u, match %u, length %d\\n\",\n                start, match, length);\n        do {\n            fprintf(stderr, \"%c%c\", s->window[match++], s->window[start++]);\n        } while (--length != 0);\n        z_error(\"invalid match\");\n    }\n    if (z_verbose > 1) {\n        fprintf(stderr,\"\\\\[%d,%d]\", start-match, length);\n        do { putc(s->window[start++], stderr); } while (--length != 0);\n    }\n}\n#else\n#  define check_match(s, start, match, length)\n#endif /* DEBUG */\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n *    At least one byte has been read, or avail_in == 0; reads are\n *    performed for at least two bytes (required for the zip translate_eol\n *    option -- not supported here).\n */\nlocal void fill_window(s)\n    deflate_state *s;\n{\n    register unsigned n, m;\n    register Posf *p;\n    unsigned more;    /* Amount of free space at the end of the window. */\n    uInt wsize = s->w_size;\n\n    do {\n        more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);\n\n        /* Deal with !@#$% 64K limit: */\n        if (sizeof(int) <= 2) {\n            if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n                more = wsize;\n\n            } else if (more == (unsigned)(-1)) {\n                /* Very unlikely, but possible on 16 bit machine if\n                 * strstart == 0 && lookahead == 1 (input done a byte at time)\n                 */\n                more--;\n            }\n        }\n\n        /* If the window is almost full and there is insufficient lookahead,\n         * move the upper half to the lower one to make room in the upper half.\n         */\n        if (s->strstart >= wsize+MAX_DIST(s)) {\n\n            zmemcpy(s->window, s->window+wsize, (unsigned)wsize);\n            s->match_start -= wsize;\n            s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */\n            s->block_start -= (long) wsize;\n\n            /* Slide the hash table (could be avoided with 32 bit values\n               at the expense of memory usage). We slide even when level == 0\n               to keep the hash table consistent if we switch back to level > 0\n               later. (Using level 0 permanently is not an optimal usage of\n               zlib, so we don't care about this pathological case.)\n             */\n            n = s->hash_size;\n            p = &s->head[n];\n            do {\n                m = *--p;\n                *p = (Pos)(m >= wsize ? m-wsize : NIL);\n            } while (--n);\n\n            n = wsize;\n#ifndef FASTEST\n            p = &s->prev[n];\n            do {\n                m = *--p;\n                *p = (Pos)(m >= wsize ? m-wsize : NIL);\n                /* If n is not on any hash chain, prev[n] is garbage but\n                 * its value will never be used.\n                 */\n            } while (--n);\n#endif\n            more += wsize;\n        }\n        if (s->strm->avail_in == 0) return;\n\n        /* If there was no sliding:\n         *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n         *    more == window_size - lookahead - strstart\n         * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n         * => more >= window_size - 2*WSIZE + 2\n         * In the BIG_MEM or MMAP case (not yet supported),\n         *   window_size == input_size + MIN_LOOKAHEAD  &&\n         *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n         * Otherwise, window_size == 2*WSIZE so more >= 2.\n         * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n         */\n        Assert(more >= 2, \"more < 2\");\n\n        n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);\n        s->lookahead += n;\n\n        /* Initialize the hash value now that we have some input: */\n        if (s->lookahead >= MIN_MATCH) {\n            s->ins_h = s->window[s->strstart];\n            UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);\n#if MIN_MATCH != 3\n            Call UPDATE_HASH() MIN_MATCH-3 more times\n#endif\n        }\n        /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n         * but this is not important since only literal bytes will be emitted.\n         */\n\n    } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);\n\n    /* If the WIN_INIT bytes after the end of the current data have never been\n     * written, then zero those bytes in order to avoid memory check reports of\n     * the use of uninitialized (or uninitialised as Julian writes) bytes by\n     * the longest match routines.  Update the high water mark for the next\n     * time through here.  WIN_INIT is set to MAX_MATCH since the longest match\n     * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n     */\n    if (s->high_water < s->window_size) {\n        ulg curr = s->strstart + (ulg)(s->lookahead);\n        ulg init;\n\n        if (s->high_water < curr) {\n            /* Previous high water mark below current data -- zero WIN_INIT\n             * bytes or up to end of window, whichever is less.\n             */\n            init = s->window_size - curr;\n            if (init > WIN_INIT)\n                init = WIN_INIT;\n            zmemzero(s->window + curr, (unsigned)init);\n            s->high_water = curr + init;\n        }\n        else if (s->high_water < (ulg)curr + WIN_INIT) {\n            /* High water mark at or above current data, but below current data\n             * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n             * to end of window, whichever is less.\n             */\n            init = (ulg)curr + WIN_INIT - s->high_water;\n            if (init > s->window_size - s->high_water)\n                init = s->window_size - s->high_water;\n            zmemzero(s->window + s->high_water, (unsigned)init);\n            s->high_water += init;\n        }\n    }\n}\n\n/* ===========================================================================\n * Flush the current block, with given end-of-file flag.\n * IN assertion: strstart is set to the end of the current match.\n */\n#define FLUSH_BLOCK_ONLY(s, last) { \\\n   _tr_flush_block(s, (s->block_start >= 0L ? \\\n                   (charf *)&s->window[(unsigned)s->block_start] : \\\n                   (charf *)Z_NULL), \\\n                (ulg)((long)s->strstart - s->block_start), \\\n                (last)); \\\n   s->block_start = s->strstart; \\\n   flush_pending(s->strm); \\\n   Tracev((stderr,\"[FLUSH]\")); \\\n}\n\n/* Same but force premature exit if necessary. */\n#define FLUSH_BLOCK(s, last) { \\\n   FLUSH_BLOCK_ONLY(s, last); \\\n   if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \\\n}\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n * This function does not insert new strings in the dictionary since\n * uncompressible data is probably not useful. This function is used\n * only for the level=0 compression option.\n * NOTE: this function should be optimized to avoid extra copying from\n * window to pending_buf.\n */\nlocal block_state deflate_stored(s, flush)\n    deflate_state *s;\n    int flush;\n{\n    /* Stored blocks are limited to 0xffff bytes, pending_buf is limited\n     * to pending_buf_size, and each stored block has a 5 byte header:\n     */\n    ulg max_block_size = 0xffff;\n    ulg max_start;\n\n    if (max_block_size > s->pending_buf_size - 5) {\n        max_block_size = s->pending_buf_size - 5;\n    }\n\n    /* Copy as much as possible from input to output: */\n    for (;;) {\n        /* Fill the window as much as possible: */\n        if (s->lookahead <= 1) {\n\n            Assert(s->strstart < s->w_size+MAX_DIST(s) ||\n                   s->block_start >= (long)s->w_size, \"slide too late\");\n\n            fill_window(s);\n            if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;\n\n            if (s->lookahead == 0) break; /* flush the current block */\n        }\n        Assert(s->block_start >= 0L, \"block gone\");\n\n        s->strstart += s->lookahead;\n        s->lookahead = 0;\n\n        /* Emit a stored block if pending_buf will be full: */\n        max_start = s->block_start + max_block_size;\n        if (s->strstart == 0 || (ulg)s->strstart >= max_start) {\n            /* strstart == 0 is possible when wraparound on 16-bit machine */\n            s->lookahead = (uInt)(s->strstart - max_start);\n            s->strstart = (uInt)max_start;\n            FLUSH_BLOCK(s, 0);\n        }\n        /* Flush if we may have to slide, otherwise block_start may become\n         * negative and the data will be gone:\n         */\n        if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {\n            FLUSH_BLOCK(s, 0);\n        }\n    }\n    FLUSH_BLOCK(s, flush == Z_FINISH);\n    return flush == Z_FINISH ? finish_done : block_done;\n}\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nlocal block_state deflate_fast(s, flush)\n    deflate_state *s;\n    int flush;\n{\n    IPos hash_head;       /* head of the hash chain */\n    int bflush;           /* set if current block must be flushed */\n\n    for (;;) {\n        /* Make sure that we always have enough lookahead, except\n         * at the end of the input file. We need MAX_MATCH bytes\n         * for the next match, plus MIN_MATCH bytes to insert the\n         * string following the next match.\n         */\n        if (s->lookahead < MIN_LOOKAHEAD) {\n            fill_window(s);\n            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {\n                return need_more;\n            }\n            if (s->lookahead == 0) break; /* flush the current block */\n        }\n\n        /* Insert the string window[strstart .. strstart+2] in the\n         * dictionary, and set hash_head to the head of the hash chain:\n         */\n        hash_head = NIL;\n        if (s->lookahead >= MIN_MATCH) {\n            INSERT_STRING(s, s->strstart, hash_head);\n        }\n\n        /* Find the longest match, discarding those <= prev_length.\n         * At this point we have always match_length < MIN_MATCH\n         */\n        if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {\n            /* To simplify the code, we prevent matches with the string\n             * of window index 0 (in particular we have to avoid a match\n             * of the string with itself at the start of the input file).\n             */\n            s->match_length = longest_match (s, hash_head);\n            /* longest_match() sets match_start */\n        }\n        if (s->match_length >= MIN_MATCH) {\n            check_match(s, s->strstart, s->match_start, s->match_length);\n\n            _tr_tally_dist(s, s->strstart - s->match_start,\n                           s->match_length - MIN_MATCH, bflush);\n\n            s->lookahead -= s->match_length;\n\n            /* Insert new strings in the hash table only if the match length\n             * is not too large. This saves time but degrades compression.\n             */\n#ifndef FASTEST\n            if (s->match_length <= s->max_insert_length &&\n                s->lookahead >= MIN_MATCH) {\n                s->match_length--; /* string at strstart already in table */\n                do {\n                    s->strstart++;\n                    INSERT_STRING(s, s->strstart, hash_head);\n                    /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n                     * always MIN_MATCH bytes ahead.\n                     */\n                } while (--s->match_length != 0);\n                s->strstart++;\n            } else\n#endif\n            {\n                s->strstart += s->match_length;\n                s->match_length = 0;\n                s->ins_h = s->window[s->strstart];\n                UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);\n#if MIN_MATCH != 3\n                Call UPDATE_HASH() MIN_MATCH-3 more times\n#endif\n                /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n                 * matter since it will be recomputed at next deflate call.\n                 */\n            }\n        } else {\n            /* No match, output a literal byte */\n            Tracevv((stderr,\"%c\", s->window[s->strstart]));\n            _tr_tally_lit (s, s->window[s->strstart], bflush);\n            s->lookahead--;\n            s->strstart++;\n        }\n        if (bflush) FLUSH_BLOCK(s, 0);\n    }\n    FLUSH_BLOCK(s, flush == Z_FINISH);\n    return flush == Z_FINISH ? finish_done : block_done;\n}\n\n#ifndef FASTEST\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nlocal block_state deflate_slow(s, flush)\n    deflate_state *s;\n    int flush;\n{\n    IPos hash_head;          /* head of hash chain */\n    int bflush;              /* set if current block must be flushed */\n\n    /* Process the input block. */\n    for (;;) {\n        /* Make sure that we always have enough lookahead, except\n         * at the end of the input file. We need MAX_MATCH bytes\n         * for the next match, plus MIN_MATCH bytes to insert the\n         * string following the next match.\n         */\n        if (s->lookahead < MIN_LOOKAHEAD) {\n            fill_window(s);\n            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {\n                return need_more;\n            }\n            if (s->lookahead == 0) break; /* flush the current block */\n        }\n\n        /* Insert the string window[strstart .. strstart+2] in the\n         * dictionary, and set hash_head to the head of the hash chain:\n         */\n        hash_head = NIL;\n        if (s->lookahead >= MIN_MATCH) {\n            INSERT_STRING(s, s->strstart, hash_head);\n        }\n\n        /* Find the longest match, discarding those <= prev_length.\n         */\n        s->prev_length = s->match_length, s->prev_match = s->match_start;\n        s->match_length = MIN_MATCH-1;\n\n        if (hash_head != NIL && s->prev_length < s->max_lazy_match &&\n            s->strstart - hash_head <= MAX_DIST(s)) {\n            /* To simplify the code, we prevent matches with the string\n             * of window index 0 (in particular we have to avoid a match\n             * of the string with itself at the start of the input file).\n             */\n            s->match_length = longest_match (s, hash_head);\n            /* longest_match() sets match_start */\n\n            if (s->match_length <= 5 && (s->strategy == Z_FILTERED\n#if TOO_FAR <= 32767\n                || (s->match_length == MIN_MATCH &&\n                    s->strstart - s->match_start > TOO_FAR)\n#endif\n                )) {\n\n                /* If prev_match is also MIN_MATCH, match_start is garbage\n                 * but we will ignore the current match anyway.\n                 */\n                s->match_length = MIN_MATCH-1;\n            }\n        }\n        /* If there was a match at the previous step and the current\n         * match is not better, output the previous match:\n         */\n        if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {\n            uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;\n            /* Do not insert strings in hash table beyond this. */\n\n            check_match(s, s->strstart-1, s->prev_match, s->prev_length);\n\n            _tr_tally_dist(s, s->strstart -1 - s->prev_match,\n                           s->prev_length - MIN_MATCH, bflush);\n\n            /* Insert in hash table all strings up to the end of the match.\n             * strstart-1 and strstart are already inserted. If there is not\n             * enough lookahead, the last two strings are not inserted in\n             * the hash table.\n             */\n            s->lookahead -= s->prev_length-1;\n            s->prev_length -= 2;\n            do {\n                if (++s->strstart <= max_insert) {\n                    INSERT_STRING(s, s->strstart, hash_head);\n                }\n            } while (--s->prev_length != 0);\n            s->match_available = 0;\n            s->match_length = MIN_MATCH-1;\n            s->strstart++;\n\n            if (bflush) FLUSH_BLOCK(s, 0);\n\n        } else if (s->match_available) {\n            /* If there was no match at the previous position, output a\n             * single literal. If there was a match but the current match\n             * is longer, truncate the previous match to a single literal.\n             */\n            Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n            _tr_tally_lit(s, s->window[s->strstart-1], bflush);\n            if (bflush) {\n                FLUSH_BLOCK_ONLY(s, 0);\n            }\n            s->strstart++;\n            s->lookahead--;\n            if (s->strm->avail_out == 0) return need_more;\n        } else {\n            /* There is no previous match to compare with, wait for\n             * the next step to decide.\n             */\n            s->match_available = 1;\n            s->strstart++;\n            s->lookahead--;\n        }\n    }\n    Assert (flush != Z_NO_FLUSH, \"no flush?\");\n    if (s->match_available) {\n        Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n        _tr_tally_lit(s, s->window[s->strstart-1], bflush);\n        s->match_available = 0;\n    }\n    FLUSH_BLOCK(s, flush == Z_FINISH);\n    return flush == Z_FINISH ? finish_done : block_done;\n}\n#endif /* FASTEST */\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one.  Do not maintain a hash table.  (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nlocal block_state deflate_rle(s, flush)\n    deflate_state *s;\n    int flush;\n{\n    int bflush;             /* set if current block must be flushed */\n    uInt prev;              /* byte at distance one to match */\n    Bytef *scan, *strend;   /* scan goes up to strend for length of run */\n\n    for (;;) {\n        /* Make sure that we always have enough lookahead, except\n         * at the end of the input file. We need MAX_MATCH bytes\n         * for the longest encodable run.\n         */\n        if (s->lookahead < MAX_MATCH) {\n            fill_window(s);\n            if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {\n                return need_more;\n            }\n            if (s->lookahead == 0) break; /* flush the current block */\n        }\n\n        /* See how many times the previous byte repeats */\n        s->match_length = 0;\n        if (s->lookahead >= MIN_MATCH && s->strstart > 0) {\n            scan = s->window + s->strstart - 1;\n            prev = *scan;\n            if (prev == *++scan && prev == *++scan && prev == *++scan) {\n                strend = s->window + s->strstart + MAX_MATCH;\n                do {\n                } while (prev == *++scan && prev == *++scan &&\n                         prev == *++scan && prev == *++scan &&\n                         prev == *++scan && prev == *++scan &&\n                         prev == *++scan && prev == *++scan &&\n                         scan < strend);\n                s->match_length = MAX_MATCH - (int)(strend - scan);\n                if (s->match_length > s->lookahead)\n                    s->match_length = s->lookahead;\n            }\n        }\n\n        /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n        if (s->match_length >= MIN_MATCH) {\n            check_match(s, s->strstart, s->strstart - 1, s->match_length);\n\n            _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);\n\n            s->lookahead -= s->match_length;\n            s->strstart += s->match_length;\n            s->match_length = 0;\n        } else {\n            /* No match, output a literal byte */\n            Tracevv((stderr,\"%c\", s->window[s->strstart]));\n            _tr_tally_lit (s, s->window[s->strstart], bflush);\n            s->lookahead--;\n            s->strstart++;\n        }\n        if (bflush) FLUSH_BLOCK(s, 0);\n    }\n    FLUSH_BLOCK(s, flush == Z_FINISH);\n    return flush == Z_FINISH ? finish_done : block_done;\n}\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nlocal block_state deflate_huff(s, flush)\n    deflate_state *s;\n    int flush;\n{\n    int bflush;             /* set if current block must be flushed */\n\n    for (;;) {\n        /* Make sure that we have a literal to write. */\n        if (s->lookahead == 0) {\n            fill_window(s);\n            if (s->lookahead == 0) {\n                if (flush == Z_NO_FLUSH)\n                    return need_more;\n                break;      /* flush the current block */\n            }\n        }\n\n        /* Output a literal byte */\n        s->match_length = 0;\n        Tracevv((stderr,\"%c\", s->window[s->strstart]));\n        _tr_tally_lit (s, s->window[s->strstart], bflush);\n        s->lookahead--;\n        s->strstart++;\n        if (bflush) FLUSH_BLOCK(s, 0);\n    }\n    FLUSH_BLOCK(s, flush == Z_FINISH);\n    return flush == Z_FINISH ? finish_done : block_done;\n}\n"
  },
  {
    "path": "src/engine/external/zlib/deflate.h",
    "content": "/* deflate.h -- internal compression state\n * Copyright (C) 1995-2010 Jean-loup Gailly\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* WARNING: this file should *not* be used by applications. It is\n   part of the implementation of the compression library and is\n   subject to change. Applications should only use zlib.h.\n */\n\n/* @(#) $Id$ */\n\n#ifndef DEFLATE_H\n#define DEFLATE_H\n\n#include \"zutil.h\"\n\n/* define NO_GZIP when compiling if you want to disable gzip header and\n   trailer creation by deflate().  NO_GZIP would be used to avoid linking in\n   the crc code when it is not needed.  For shared libraries, gzip encoding\n   should be left enabled. */\n#ifndef NO_GZIP\n#  define GZIP\n#endif\n\n/* ===========================================================================\n * Internal compression state.\n */\n\n#define LENGTH_CODES 29\n/* number of length codes, not counting the special END_BLOCK code */\n\n#define LITERALS  256\n/* number of literal bytes 0..255 */\n\n#define L_CODES (LITERALS+1+LENGTH_CODES)\n/* number of Literal or Length codes, including the END_BLOCK code */\n\n#define D_CODES   30\n/* number of distance codes */\n\n#define BL_CODES  19\n/* number of codes used to transfer the bit lengths */\n\n#define HEAP_SIZE (2*L_CODES+1)\n/* maximum heap size */\n\n#define MAX_BITS 15\n/* All codes must not exceed MAX_BITS bits */\n\n#define INIT_STATE    42\n#define EXTRA_STATE   69\n#define NAME_STATE    73\n#define COMMENT_STATE 91\n#define HCRC_STATE   103\n#define BUSY_STATE   113\n#define FINISH_STATE 666\n/* Stream status */\n\n\n/* Data structure describing a single value and its code string. */\ntypedef struct ct_data_s {\n    union {\n        ush  freq;       /* frequency count */\n        ush  code;       /* bit string */\n    } fc;\n    union {\n        ush  dad;        /* father node in Huffman tree */\n        ush  len;        /* length of bit string */\n    } dl;\n} FAR ct_data;\n\n#define Freq fc.freq\n#define Code fc.code\n#define Dad  dl.dad\n#define Len  dl.len\n\ntypedef struct static_tree_desc_s  static_tree_desc;\n\ntypedef struct tree_desc_s {\n    ct_data *dyn_tree;           /* the dynamic tree */\n    int     max_code;            /* largest code with non zero frequency */\n    static_tree_desc *stat_desc; /* the corresponding static tree */\n} FAR tree_desc;\n\ntypedef ush Pos;\ntypedef Pos FAR Posf;\ntypedef unsigned IPos;\n\n/* A Pos is an index in the character window. We use short instead of int to\n * save space in the various tables. IPos is used only for parameter passing.\n */\n\ntypedef struct internal_state {\n    z_streamp strm;      /* pointer back to this zlib stream */\n    int   status;        /* as the name implies */\n    Bytef *pending_buf;  /* output still pending */\n    ulg   pending_buf_size; /* size of pending_buf */\n    Bytef *pending_out;  /* next pending byte to output to the stream */\n    uInt   pending;      /* nb of bytes in the pending buffer */\n    int   wrap;          /* bit 0 true for zlib, bit 1 true for gzip */\n    gz_headerp  gzhead;  /* gzip header information to write */\n    uInt   gzindex;      /* where in extra, name, or comment */\n    Byte  method;        /* STORED (for zip only) or DEFLATED */\n    int   last_flush;    /* value of flush param for previous deflate call */\n\n                /* used by deflate.c: */\n\n    uInt  w_size;        /* LZ77 window size (32K by default) */\n    uInt  w_bits;        /* log2(w_size)  (8..16) */\n    uInt  w_mask;        /* w_size - 1 */\n\n    Bytef *window;\n    /* Sliding window. Input bytes are read into the second half of the window,\n     * and move to the first half later to keep a dictionary of at least wSize\n     * bytes. With this organization, matches are limited to a distance of\n     * wSize-MAX_MATCH bytes, but this ensures that IO is always\n     * performed with a length multiple of the block size. Also, it limits\n     * the window size to 64K, which is quite useful on MSDOS.\n     * To do: use the user input buffer as sliding window.\n     */\n\n    ulg window_size;\n    /* Actual size of window: 2*wSize, except when the user input buffer\n     * is directly used as sliding window.\n     */\n\n    Posf *prev;\n    /* Link to older string with same hash index. To limit the size of this\n     * array to 64K, this link is maintained only for the last 32K strings.\n     * An index in this array is thus a window index modulo 32K.\n     */\n\n    Posf *head; /* Heads of the hash chains or NIL. */\n\n    uInt  ins_h;          /* hash index of string to be inserted */\n    uInt  hash_size;      /* number of elements in hash table */\n    uInt  hash_bits;      /* log2(hash_size) */\n    uInt  hash_mask;      /* hash_size-1 */\n\n    uInt  hash_shift;\n    /* Number of bits by which ins_h must be shifted at each input\n     * step. It must be such that after MIN_MATCH steps, the oldest\n     * byte no longer takes part in the hash key, that is:\n     *   hash_shift * MIN_MATCH >= hash_bits\n     */\n\n    long block_start;\n    /* Window position at the beginning of the current output block. Gets\n     * negative when the window is moved backwards.\n     */\n\n    uInt match_length;           /* length of best match */\n    IPos prev_match;             /* previous match */\n    int match_available;         /* set if previous match exists */\n    uInt strstart;               /* start of string to insert */\n    uInt match_start;            /* start of matching string */\n    uInt lookahead;              /* number of valid bytes ahead in window */\n\n    uInt prev_length;\n    /* Length of the best match at previous step. Matches not greater than this\n     * are discarded. This is used in the lazy match evaluation.\n     */\n\n    uInt max_chain_length;\n    /* To speed up deflation, hash chains are never searched beyond this\n     * length.  A higher limit improves compression ratio but degrades the\n     * speed.\n     */\n\n    uInt max_lazy_match;\n    /* Attempt to find a better match only when the current match is strictly\n     * smaller than this value. This mechanism is used only for compression\n     * levels >= 4.\n     */\n#   define max_insert_length  max_lazy_match\n    /* Insert new strings in the hash table only if the match length is not\n     * greater than this length. This saves time but degrades compression.\n     * max_insert_length is used only for compression levels <= 3.\n     */\n\n    int level;    /* compression level (1..9) */\n    int strategy; /* favor or force Huffman coding*/\n\n    uInt good_match;\n    /* Use a faster search when the previous match is longer than this */\n\n    int nice_match; /* Stop searching when current match exceeds this */\n\n                /* used by trees.c: */\n    /* Didn't use ct_data typedef below to supress compiler warning */\n    struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */\n    struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n    struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */\n\n    struct tree_desc_s l_desc;               /* desc. for literal tree */\n    struct tree_desc_s d_desc;               /* desc. for distance tree */\n    struct tree_desc_s bl_desc;              /* desc. for bit length tree */\n\n    ush bl_count[MAX_BITS+1];\n    /* number of codes at each bit length for an optimal tree */\n\n    int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */\n    int heap_len;               /* number of elements in the heap */\n    int heap_max;               /* element of largest frequency */\n    /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n     * The same heap array is used to build all trees.\n     */\n\n    uch depth[2*L_CODES+1];\n    /* Depth of each subtree used as tie breaker for trees of equal frequency\n     */\n\n    uchf *l_buf;          /* buffer for literals or lengths */\n\n    uInt  lit_bufsize;\n    /* Size of match buffer for literals/lengths.  There are 4 reasons for\n     * limiting lit_bufsize to 64K:\n     *   - frequencies can be kept in 16 bit counters\n     *   - if compression is not successful for the first block, all input\n     *     data is still in the window so we can still emit a stored block even\n     *     when input comes from standard input.  (This can also be done for\n     *     all blocks if lit_bufsize is not greater than 32K.)\n     *   - if compression is not successful for a file smaller than 64K, we can\n     *     even emit a stored file instead of a stored block (saving 5 bytes).\n     *     This is applicable only for zip (not gzip or zlib).\n     *   - creating new Huffman trees less frequently may not provide fast\n     *     adaptation to changes in the input data statistics. (Take for\n     *     example a binary file with poorly compressible code followed by\n     *     a highly compressible string table.) Smaller buffer sizes give\n     *     fast adaptation but have of course the overhead of transmitting\n     *     trees more frequently.\n     *   - I can't count above 4\n     */\n\n    uInt last_lit;      /* running index in l_buf */\n\n    ushf *d_buf;\n    /* Buffer for distances. To simplify the code, d_buf and l_buf have\n     * the same number of elements. To use different lengths, an extra flag\n     * array would be necessary.\n     */\n\n    ulg opt_len;        /* bit length of current block with optimal trees */\n    ulg static_len;     /* bit length of current block with static trees */\n    uInt matches;       /* number of string matches in current block */\n    int last_eob_len;   /* bit length of EOB code for last block */\n\n#ifdef DEBUG\n    ulg compressed_len; /* total bit length of compressed file mod 2^32 */\n    ulg bits_sent;      /* bit length of compressed data sent mod 2^32 */\n#endif\n\n    ush bi_buf;\n    /* Output buffer. bits are inserted starting at the bottom (least\n     * significant bits).\n     */\n    int bi_valid;\n    /* Number of valid bits in bi_buf.  All bits above the last valid bit\n     * are always zero.\n     */\n\n    ulg high_water;\n    /* High water mark offset in window for initialized bytes -- bytes above\n     * this are set to zero in order to avoid memory check warnings when\n     * longest match routines access bytes past the input.  This is then\n     * updated to the new high water mark.\n     */\n\n} FAR deflate_state;\n\n/* Output a byte on the stream.\n * IN assertion: there is enough room in pending_buf.\n */\n#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}\n\n\n#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)\n/* Minimum amount of lookahead, except at the end of the input file.\n * See deflate.c for comments about the MIN_MATCH+1.\n */\n\n#define MAX_DIST(s)  ((s)->w_size-MIN_LOOKAHEAD)\n/* In order to simplify the code, particularly on 16 bit machines, match\n * distances are limited to MAX_DIST instead of WSIZE.\n */\n\n#define WIN_INIT MAX_MATCH\n/* Number of bytes after end of data in window to initialize in order to avoid\n   memory checker errors from longest match routines */\n\n        /* in trees.c */\nvoid ZLIB_INTERNAL _tr_init OF((deflate_state *s));\nint ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));\nvoid ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf,\n                        ulg stored_len, int last));\nvoid ZLIB_INTERNAL _tr_align OF((deflate_state *s));\nvoid ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf,\n                        ulg stored_len, int last));\n\n#define d_code(dist) \\\n   ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])\n/* Mapping from a distance to a distance code. dist is the distance - 1 and\n * must not have side effects. _dist_code[256] and _dist_code[257] are never\n * used.\n */\n\n#ifndef DEBUG\n/* Inline versions of _tr_tally for speed: */\n\n#if defined(GEN_TREES_H) || !defined(STDC)\n  extern uch ZLIB_INTERNAL _length_code[];\n  extern uch ZLIB_INTERNAL _dist_code[];\n#else\n  extern const uch ZLIB_INTERNAL _length_code[];\n  extern const uch ZLIB_INTERNAL _dist_code[];\n#endif\n\n# define _tr_tally_lit(s, c, flush) \\\n  { uch cc = (c); \\\n    s->d_buf[s->last_lit] = 0; \\\n    s->l_buf[s->last_lit++] = cc; \\\n    s->dyn_ltree[cc].Freq++; \\\n    flush = (s->last_lit == s->lit_bufsize-1); \\\n   }\n# define _tr_tally_dist(s, distance, length, flush) \\\n  { uch len = (length); \\\n    ush dist = (distance); \\\n    s->d_buf[s->last_lit] = dist; \\\n    s->l_buf[s->last_lit++] = len; \\\n    dist--; \\\n    s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \\\n    s->dyn_dtree[d_code(dist)].Freq++; \\\n    flush = (s->last_lit == s->lit_bufsize-1); \\\n  }\n#else\n# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)\n# define _tr_tally_dist(s, distance, length, flush) \\\n              flush = _tr_tally(s, distance, length)\n#endif\n\n#endif /* DEFLATE_H */\n"
  },
  {
    "path": "src/engine/external/zlib/infback.c",
    "content": "/* infback.c -- inflate using a call-back interface\n * Copyright (C) 1995-2009 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/*\n   This code is largely copied from inflate.c.  Normally either infback.o or\n   inflate.o would be linked into an application--not both.  The interface\n   with inffast.c is retained so that optimized assembler-coded versions of\n   inflate_fast() can be used with either inflate.c or infback.c.\n */\n\n#include \"zutil.h\"\n#include \"inftrees.h\"\n#include \"inflate.h\"\n#include \"inffast.h\"\n\n/* function prototypes */\nlocal void fixedtables OF((struct inflate_state FAR *state));\n\n/*\n   strm provides memory allocation functions in zalloc and zfree, or\n   Z_NULL to use the library memory allocation functions.\n\n   windowBits is in the range 8..15, and window is a user-supplied\n   window and output buffer that is 2**windowBits bytes.\n */\nint ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size)\nz_streamp strm;\nint windowBits;\nunsigned char FAR *window;\nconst char *version;\nint stream_size;\n{\n    struct inflate_state FAR *state;\n\n    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||\n        stream_size != (int)(sizeof(z_stream)))\n        return Z_VERSION_ERROR;\n    if (strm == Z_NULL || window == Z_NULL ||\n        windowBits < 8 || windowBits > 15)\n        return Z_STREAM_ERROR;\n    strm->msg = Z_NULL;                 /* in case we return an error */\n    if (strm->zalloc == (alloc_func)0) {\n        strm->zalloc = zcalloc;\n        strm->opaque = (voidpf)0;\n    }\n    if (strm->zfree == (free_func)0) strm->zfree = zcfree;\n    state = (struct inflate_state FAR *)ZALLOC(strm, 1,\n                                               sizeof(struct inflate_state));\n    if (state == Z_NULL) return Z_MEM_ERROR;\n    Tracev((stderr, \"inflate: allocated\\n\"));\n    strm->state = (struct internal_state FAR *)state;\n    state->dmax = 32768U;\n    state->wbits = windowBits;\n    state->wsize = 1U << windowBits;\n    state->window = window;\n    state->wnext = 0;\n    state->whave = 0;\n    return Z_OK;\n}\n\n/*\n   Return state with length and distance decoding tables and index sizes set to\n   fixed code decoding.  Normally this returns fixed tables from inffixed.h.\n   If BUILDFIXED is defined, then instead this routine builds the tables the\n   first time it's called, and returns those tables the first time and\n   thereafter.  This reduces the size of the code by about 2K bytes, in\n   exchange for a little execution time.  However, BUILDFIXED should not be\n   used for threaded applications, since the rewriting of the tables and virgin\n   may not be thread-safe.\n */\nlocal void fixedtables(state)\nstruct inflate_state FAR *state;\n{\n#ifdef BUILDFIXED\n    static int virgin = 1;\n    static code *lenfix, *distfix;\n    static code fixed[544];\n\n    /* build fixed huffman tables if first call (may not be thread safe) */\n    if (virgin) {\n        unsigned sym, bits;\n        static code *next;\n\n        /* literal/length table */\n        sym = 0;\n        while (sym < 144) state->lens[sym++] = 8;\n        while (sym < 256) state->lens[sym++] = 9;\n        while (sym < 280) state->lens[sym++] = 7;\n        while (sym < 288) state->lens[sym++] = 8;\n        next = fixed;\n        lenfix = next;\n        bits = 9;\n        inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);\n\n        /* distance table */\n        sym = 0;\n        while (sym < 32) state->lens[sym++] = 5;\n        distfix = next;\n        bits = 5;\n        inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);\n\n        /* do this just once */\n        virgin = 0;\n    }\n#else /* !BUILDFIXED */\n#   include \"inffixed.h\"\n#endif /* BUILDFIXED */\n    state->lencode = lenfix;\n    state->lenbits = 9;\n    state->distcode = distfix;\n    state->distbits = 5;\n}\n\n/* Macros for inflateBack(): */\n\n/* Load returned state from inflate_fast() */\n#define LOAD() \\\n    do { \\\n        put = strm->next_out; \\\n        left = strm->avail_out; \\\n        next = strm->next_in; \\\n        have = strm->avail_in; \\\n        hold = state->hold; \\\n        bits = state->bits; \\\n    } while (0)\n\n/* Set state from registers for inflate_fast() */\n#define RESTORE() \\\n    do { \\\n        strm->next_out = put; \\\n        strm->avail_out = left; \\\n        strm->next_in = next; \\\n        strm->avail_in = have; \\\n        state->hold = hold; \\\n        state->bits = bits; \\\n    } while (0)\n\n/* Clear the input bit accumulator */\n#define INITBITS() \\\n    do { \\\n        hold = 0; \\\n        bits = 0; \\\n    } while (0)\n\n/* Assure that some input is available.  If input is requested, but denied,\n   then return a Z_BUF_ERROR from inflateBack(). */\n#define PULL() \\\n    do { \\\n        if (have == 0) { \\\n            have = in(in_desc, &next); \\\n            if (have == 0) { \\\n                next = Z_NULL; \\\n                ret = Z_BUF_ERROR; \\\n                goto inf_leave; \\\n            } \\\n        } \\\n    } while (0)\n\n/* Get a byte of input into the bit accumulator, or return from inflateBack()\n   with an error if there is no input available. */\n#define PULLBYTE() \\\n    do { \\\n        PULL(); \\\n        have--; \\\n        hold += (unsigned long)(*next++) << bits; \\\n        bits += 8; \\\n    } while (0)\n\n/* Assure that there are at least n bits in the bit accumulator.  If there is\n   not enough available input to do that, then return from inflateBack() with\n   an error. */\n#define NEEDBITS(n) \\\n    do { \\\n        while (bits < (unsigned)(n)) \\\n            PULLBYTE(); \\\n    } while (0)\n\n/* Return the low n bits of the bit accumulator (n < 16) */\n#define BITS(n) \\\n    ((unsigned)hold & ((1U << (n)) - 1))\n\n/* Remove n bits from the bit accumulator */\n#define DROPBITS(n) \\\n    do { \\\n        hold >>= (n); \\\n        bits -= (unsigned)(n); \\\n    } while (0)\n\n/* Remove zero to seven bits as needed to go to a byte boundary */\n#define BYTEBITS() \\\n    do { \\\n        hold >>= bits & 7; \\\n        bits -= bits & 7; \\\n    } while (0)\n\n/* Assure that some output space is available, by writing out the window\n   if it's full.  If the write fails, return from inflateBack() with a\n   Z_BUF_ERROR. */\n#define ROOM() \\\n    do { \\\n        if (left == 0) { \\\n            put = state->window; \\\n            left = state->wsize; \\\n            state->whave = left; \\\n            if (out(out_desc, put, left)) { \\\n                ret = Z_BUF_ERROR; \\\n                goto inf_leave; \\\n            } \\\n        } \\\n    } while (0)\n\n/*\n   strm provides the memory allocation functions and window buffer on input,\n   and provides information on the unused input on return.  For Z_DATA_ERROR\n   returns, strm will also provide an error message.\n\n   in() and out() are the call-back input and output functions.  When\n   inflateBack() needs more input, it calls in().  When inflateBack() has\n   filled the window with output, or when it completes with data in the\n   window, it calls out() to write out the data.  The application must not\n   change the provided input until in() is called again or inflateBack()\n   returns.  The application must not change the window/output buffer until\n   inflateBack() returns.\n\n   in() and out() are called with a descriptor parameter provided in the\n   inflateBack() call.  This parameter can be a structure that provides the\n   information required to do the read or write, as well as accumulated\n   information on the input and output such as totals and check values.\n\n   in() should return zero on failure.  out() should return non-zero on\n   failure.  If either in() or out() fails, than inflateBack() returns a\n   Z_BUF_ERROR.  strm->next_in can be checked for Z_NULL to see whether it\n   was in() or out() that caused in the error.  Otherwise,  inflateBack()\n   returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format\n   error, or Z_MEM_ERROR if it could not allocate memory for the state.\n   inflateBack() can also return Z_STREAM_ERROR if the input parameters\n   are not correct, i.e. strm is Z_NULL or the state was not initialized.\n */\nint ZEXPORT inflateBack(strm, in, in_desc, out, out_desc)\nz_streamp strm;\nin_func in;\nvoid FAR *in_desc;\nout_func out;\nvoid FAR *out_desc;\n{\n    struct inflate_state FAR *state;\n    unsigned char FAR *next;    /* next input */\n    unsigned char FAR *put;     /* next output */\n    unsigned have, left;        /* available input and output */\n    unsigned long hold;         /* bit buffer */\n    unsigned bits;              /* bits in bit buffer */\n    unsigned copy;              /* number of stored or match bytes to copy */\n    unsigned char FAR *from;    /* where to copy match bytes from */\n    code here;                  /* current decoding table entry */\n    code last;                  /* parent table entry */\n    unsigned len;               /* length to copy for repeats, bits to drop */\n    int ret;                    /* return code */\n    static const unsigned short order[19] = /* permutation of code lengths */\n        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};\n\n    /* Check that the strm exists and that the state was initialized */\n    if (strm == Z_NULL || strm->state == Z_NULL)\n        return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n\n    /* Reset the state */\n    strm->msg = Z_NULL;\n    state->mode = TYPE;\n    state->last = 0;\n    state->whave = 0;\n    next = strm->next_in;\n    have = next != Z_NULL ? strm->avail_in : 0;\n    hold = 0;\n    bits = 0;\n    put = state->window;\n    left = state->wsize;\n\n    /* Inflate until end of block marked as last */\n    for (;;)\n        switch (state->mode) {\n        case TYPE:\n            /* determine and dispatch block type */\n            if (state->last) {\n                BYTEBITS();\n                state->mode = DONE;\n                break;\n            }\n            NEEDBITS(3);\n            state->last = BITS(1);\n            DROPBITS(1);\n            switch (BITS(2)) {\n            case 0:                             /* stored block */\n                Tracev((stderr, \"inflate:     stored block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = STORED;\n                break;\n            case 1:                             /* fixed block */\n                fixedtables(state);\n                Tracev((stderr, \"inflate:     fixed codes block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = LEN;              /* decode codes */\n                break;\n            case 2:                             /* dynamic block */\n                Tracev((stderr, \"inflate:     dynamic codes block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = TABLE;\n                break;\n            case 3:\n                strm->msg = (char *)\"invalid block type\";\n                state->mode = BAD;\n            }\n            DROPBITS(2);\n            break;\n\n        case STORED:\n            /* get and verify stored block length */\n            BYTEBITS();                         /* go to byte boundary */\n            NEEDBITS(32);\n            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {\n                strm->msg = (char *)\"invalid stored block lengths\";\n                state->mode = BAD;\n                break;\n            }\n            state->length = (unsigned)hold & 0xffff;\n            Tracev((stderr, \"inflate:       stored length %u\\n\",\n                    state->length));\n            INITBITS();\n\n            /* copy stored block from input to output */\n            while (state->length != 0) {\n                copy = state->length;\n                PULL();\n                ROOM();\n                if (copy > have) copy = have;\n                if (copy > left) copy = left;\n                zmemcpy(put, next, copy);\n                have -= copy;\n                next += copy;\n                left -= copy;\n                put += copy;\n                state->length -= copy;\n            }\n            Tracev((stderr, \"inflate:       stored end\\n\"));\n            state->mode = TYPE;\n            break;\n\n        case TABLE:\n            /* get dynamic table entries descriptor */\n            NEEDBITS(14);\n            state->nlen = BITS(5) + 257;\n            DROPBITS(5);\n            state->ndist = BITS(5) + 1;\n            DROPBITS(5);\n            state->ncode = BITS(4) + 4;\n            DROPBITS(4);\n#ifndef PKZIP_BUG_WORKAROUND\n            if (state->nlen > 286 || state->ndist > 30) {\n                strm->msg = (char *)\"too many length or distance symbols\";\n                state->mode = BAD;\n                break;\n            }\n#endif\n            Tracev((stderr, \"inflate:       table sizes ok\\n\"));\n\n            /* get code length code lengths (not a typo) */\n            state->have = 0;\n            while (state->have < state->ncode) {\n                NEEDBITS(3);\n                state->lens[order[state->have++]] = (unsigned short)BITS(3);\n                DROPBITS(3);\n            }\n            while (state->have < 19)\n                state->lens[order[state->have++]] = 0;\n            state->next = state->codes;\n            state->lencode = (code const FAR *)(state->next);\n            state->lenbits = 7;\n            ret = inflate_table(CODES, state->lens, 19, &(state->next),\n                                &(state->lenbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid code lengths set\";\n                state->mode = BAD;\n                break;\n            }\n            Tracev((stderr, \"inflate:       code lengths ok\\n\"));\n\n            /* get length and distance code code lengths */\n            state->have = 0;\n            while (state->have < state->nlen + state->ndist) {\n                for (;;) {\n                    here = state->lencode[BITS(state->lenbits)];\n                    if ((unsigned)(here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                if (here.val < 16) {\n                    NEEDBITS(here.bits);\n                    DROPBITS(here.bits);\n                    state->lens[state->have++] = here.val;\n                }\n                else {\n                    if (here.val == 16) {\n                        NEEDBITS(here.bits + 2);\n                        DROPBITS(here.bits);\n                        if (state->have == 0) {\n                            strm->msg = (char *)\"invalid bit length repeat\";\n                            state->mode = BAD;\n                            break;\n                        }\n                        len = (unsigned)(state->lens[state->have - 1]);\n                        copy = 3 + BITS(2);\n                        DROPBITS(2);\n                    }\n                    else if (here.val == 17) {\n                        NEEDBITS(here.bits + 3);\n                        DROPBITS(here.bits);\n                        len = 0;\n                        copy = 3 + BITS(3);\n                        DROPBITS(3);\n                    }\n                    else {\n                        NEEDBITS(here.bits + 7);\n                        DROPBITS(here.bits);\n                        len = 0;\n                        copy = 11 + BITS(7);\n                        DROPBITS(7);\n                    }\n                    if (state->have + copy > state->nlen + state->ndist) {\n                        strm->msg = (char *)\"invalid bit length repeat\";\n                        state->mode = BAD;\n                        break;\n                    }\n                    while (copy--)\n                        state->lens[state->have++] = (unsigned short)len;\n                }\n            }\n\n            /* handle error breaks in while */\n            if (state->mode == BAD) break;\n\n            /* check for end-of-block code (better have one) */\n            if (state->lens[256] == 0) {\n                strm->msg = (char *)\"invalid code -- missing end-of-block\";\n                state->mode = BAD;\n                break;\n            }\n\n            /* build code tables -- note: do not change the lenbits or distbits\n               values here (9 and 6) without reading the comments in inftrees.h\n               concerning the ENOUGH constants, which depend on those values */\n            state->next = state->codes;\n            state->lencode = (code const FAR *)(state->next);\n            state->lenbits = 9;\n            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),\n                                &(state->lenbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid literal/lengths set\";\n                state->mode = BAD;\n                break;\n            }\n            state->distcode = (code const FAR *)(state->next);\n            state->distbits = 6;\n            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,\n                            &(state->next), &(state->distbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid distances set\";\n                state->mode = BAD;\n                break;\n            }\n            Tracev((stderr, \"inflate:       codes ok\\n\"));\n            state->mode = LEN;\n\n        case LEN:\n            /* use inflate_fast() if we have enough input and output */\n            if (have >= 6 && left >= 258) {\n                RESTORE();\n                if (state->whave < state->wsize)\n                    state->whave = state->wsize - left;\n                inflate_fast(strm, state->wsize);\n                LOAD();\n                break;\n            }\n\n            /* get a literal, length, or end-of-block code */\n            for (;;) {\n                here = state->lencode[BITS(state->lenbits)];\n                if ((unsigned)(here.bits) <= bits) break;\n                PULLBYTE();\n            }\n            if (here.op && (here.op & 0xf0) == 0) {\n                last = here;\n                for (;;) {\n                    here = state->lencode[last.val +\n                            (BITS(last.bits + last.op) >> last.bits)];\n                    if ((unsigned)(last.bits + here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                DROPBITS(last.bits);\n            }\n            DROPBITS(here.bits);\n            state->length = (unsigned)here.val;\n\n            /* process literal */\n            if (here.op == 0) {\n                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n                        \"inflate:         literal '%c'\\n\" :\n                        \"inflate:         literal 0x%02x\\n\", here.val));\n                ROOM();\n                *put++ = (unsigned char)(state->length);\n                left--;\n                state->mode = LEN;\n                break;\n            }\n\n            /* process end of block */\n            if (here.op & 32) {\n                Tracevv((stderr, \"inflate:         end of block\\n\"));\n                state->mode = TYPE;\n                break;\n            }\n\n            /* invalid code */\n            if (here.op & 64) {\n                strm->msg = (char *)\"invalid literal/length code\";\n                state->mode = BAD;\n                break;\n            }\n\n            /* length code -- get extra bits, if any */\n            state->extra = (unsigned)(here.op) & 15;\n            if (state->extra != 0) {\n                NEEDBITS(state->extra);\n                state->length += BITS(state->extra);\n                DROPBITS(state->extra);\n            }\n            Tracevv((stderr, \"inflate:         length %u\\n\", state->length));\n\n            /* get distance code */\n            for (;;) {\n                here = state->distcode[BITS(state->distbits)];\n                if ((unsigned)(here.bits) <= bits) break;\n                PULLBYTE();\n            }\n            if ((here.op & 0xf0) == 0) {\n                last = here;\n                for (;;) {\n                    here = state->distcode[last.val +\n                            (BITS(last.bits + last.op) >> last.bits)];\n                    if ((unsigned)(last.bits + here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                DROPBITS(last.bits);\n            }\n            DROPBITS(here.bits);\n            if (here.op & 64) {\n                strm->msg = (char *)\"invalid distance code\";\n                state->mode = BAD;\n                break;\n            }\n            state->offset = (unsigned)here.val;\n\n            /* get distance extra bits, if any */\n            state->extra = (unsigned)(here.op) & 15;\n            if (state->extra != 0) {\n                NEEDBITS(state->extra);\n                state->offset += BITS(state->extra);\n                DROPBITS(state->extra);\n            }\n            if (state->offset > state->wsize - (state->whave < state->wsize ?\n                                                left : 0)) {\n                strm->msg = (char *)\"invalid distance too far back\";\n                state->mode = BAD;\n                break;\n            }\n            Tracevv((stderr, \"inflate:         distance %u\\n\", state->offset));\n\n            /* copy match from window to output */\n            do {\n                ROOM();\n                copy = state->wsize - state->offset;\n                if (copy < left) {\n                    from = put + copy;\n                    copy = left - copy;\n                }\n                else {\n                    from = put - state->offset;\n                    copy = left;\n                }\n                if (copy > state->length) copy = state->length;\n                state->length -= copy;\n                left -= copy;\n                do {\n                    *put++ = *from++;\n                } while (--copy);\n            } while (state->length != 0);\n            break;\n\n        case DONE:\n            /* inflate stream terminated properly -- write leftover output */\n            ret = Z_STREAM_END;\n            if (left < state->wsize) {\n                if (out(out_desc, state->window, state->wsize - left))\n                    ret = Z_BUF_ERROR;\n            }\n            goto inf_leave;\n\n        case BAD:\n            ret = Z_DATA_ERROR;\n            goto inf_leave;\n\n        default:                /* can't happen, but makes compilers happy */\n            ret = Z_STREAM_ERROR;\n            goto inf_leave;\n        }\n\n    /* Return unused input */\n  inf_leave:\n    strm->next_in = next;\n    strm->avail_in = have;\n    return ret;\n}\n\nint ZEXPORT inflateBackEnd(strm)\nz_streamp strm;\n{\n    if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)\n        return Z_STREAM_ERROR;\n    ZFREE(strm, strm->state);\n    strm->state = Z_NULL;\n    Tracev((stderr, \"inflate: end\\n\"));\n    return Z_OK;\n}\n"
  },
  {
    "path": "src/engine/external/zlib/inffast.c",
    "content": "/* inffast.c -- fast decoding\n * Copyright (C) 1995-2008, 2010 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n#include \"zutil.h\"\n#include \"inftrees.h\"\n#include \"inflate.h\"\n#include \"inffast.h\"\n\n#ifndef ASMINF\n\n/* Allow machine dependent optimization for post-increment or pre-increment.\n   Based on testing to date,\n   Pre-increment preferred for:\n   - PowerPC G3 (Adler)\n   - MIPS R5000 (Randers-Pehrson)\n   Post-increment preferred for:\n   - none\n   No measurable difference:\n   - Pentium III (Anderson)\n   - M68060 (Nikl)\n */\n#ifdef POSTINC\n#  define OFF 0\n#  define PUP(a) *(a)++\n#else\n#  define OFF 1\n#  define PUP(a) *++(a)\n#endif\n\n/*\n   Decode literal, length, and distance codes and write out the resulting\n   literal and match bytes until either not enough input or output is\n   available, an end-of-block is encountered, or a data error is encountered.\n   When large enough input and output buffers are supplied to inflate(), for\n   example, a 16K input buffer and a 64K output buffer, more than 95% of the\n   inflate execution time is spent in this routine.\n\n   Entry assumptions:\n\n        state->mode == LEN\n        strm->avail_in >= 6\n        strm->avail_out >= 258\n        start >= strm->avail_out\n        state->bits < 8\n\n   On return, state->mode is one of:\n\n        LEN -- ran out of enough output space or enough available input\n        TYPE -- reached end of block code, inflate() to interpret next block\n        BAD -- error in block data\n\n   Notes:\n\n    - The maximum input bits used by a length/distance pair is 15 bits for the\n      length code, 5 bits for the length extra, 15 bits for the distance code,\n      and 13 bits for the distance extra.  This totals 48 bits, or six bytes.\n      Therefore if strm->avail_in >= 6, then there is enough input to avoid\n      checking for available input while decoding.\n\n    - The maximum bytes that a single length/distance pair can output is 258\n      bytes, which is the maximum length that can be coded.  inflate_fast()\n      requires strm->avail_out >= 258 for each loop to avoid checking for\n      output space.\n */\nvoid ZLIB_INTERNAL inflate_fast(strm, start)\nz_streamp strm;\nunsigned start;         /* inflate()'s starting value for strm->avail_out */\n{\n    struct inflate_state FAR *state;\n    unsigned char FAR *in;      /* local strm->next_in */\n    unsigned char FAR *last;    /* while in < last, enough input available */\n    unsigned char FAR *out;     /* local strm->next_out */\n    unsigned char FAR *beg;     /* inflate()'s initial strm->next_out */\n    unsigned char FAR *end;     /* while out < end, enough space available */\n#ifdef INFLATE_STRICT\n    unsigned dmax;              /* maximum distance from zlib header */\n#endif\n    unsigned wsize;             /* window size or zero if not using window */\n    unsigned whave;             /* valid bytes in the window */\n    unsigned wnext;             /* window write index */\n    unsigned char FAR *window;  /* allocated sliding window, if wsize != 0 */\n    unsigned long hold;         /* local strm->hold */\n    unsigned bits;              /* local strm->bits */\n    code const FAR *lcode;      /* local strm->lencode */\n    code const FAR *dcode;      /* local strm->distcode */\n    unsigned lmask;             /* mask for first level of length codes */\n    unsigned dmask;             /* mask for first level of distance codes */\n    code here;                  /* retrieved table entry */\n    unsigned op;                /* code bits, operation, extra bits, or */\n                                /*  window position, window bytes to copy */\n    unsigned len;               /* match length, unused bytes */\n    unsigned dist;              /* match distance */\n    unsigned char FAR *from;    /* where to copy match from */\n\n    /* copy state to local variables */\n    state = (struct inflate_state FAR *)strm->state;\n    in = strm->next_in - OFF;\n    last = in + (strm->avail_in - 5);\n    out = strm->next_out - OFF;\n    beg = out - (start - strm->avail_out);\n    end = out + (strm->avail_out - 257);\n#ifdef INFLATE_STRICT\n    dmax = state->dmax;\n#endif\n    wsize = state->wsize;\n    whave = state->whave;\n    wnext = state->wnext;\n    window = state->window;\n    hold = state->hold;\n    bits = state->bits;\n    lcode = state->lencode;\n    dcode = state->distcode;\n    lmask = (1U << state->lenbits) - 1;\n    dmask = (1U << state->distbits) - 1;\n\n    /* decode literals and length/distances until end-of-block or not enough\n       input data or output space */\n    do {\n        if (bits < 15) {\n            hold += (unsigned long)(PUP(in)) << bits;\n            bits += 8;\n            hold += (unsigned long)(PUP(in)) << bits;\n            bits += 8;\n        }\n        here = lcode[hold & lmask];\n      dolen:\n        op = (unsigned)(here.bits);\n        hold >>= op;\n        bits -= op;\n        op = (unsigned)(here.op);\n        if (op == 0) {                          /* literal */\n            Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n                    \"inflate:         literal '%c'\\n\" :\n                    \"inflate:         literal 0x%02x\\n\", here.val));\n            PUP(out) = (unsigned char)(here.val);\n        }\n        else if (op & 16) {                     /* length base */\n            len = (unsigned)(here.val);\n            op &= 15;                           /* number of extra bits */\n            if (op) {\n                if (bits < op) {\n                    hold += (unsigned long)(PUP(in)) << bits;\n                    bits += 8;\n                }\n                len += (unsigned)hold & ((1U << op) - 1);\n                hold >>= op;\n                bits -= op;\n            }\n            Tracevv((stderr, \"inflate:         length %u\\n\", len));\n            if (bits < 15) {\n                hold += (unsigned long)(PUP(in)) << bits;\n                bits += 8;\n                hold += (unsigned long)(PUP(in)) << bits;\n                bits += 8;\n            }\n            here = dcode[hold & dmask];\n          dodist:\n            op = (unsigned)(here.bits);\n            hold >>= op;\n            bits -= op;\n            op = (unsigned)(here.op);\n            if (op & 16) {                      /* distance base */\n                dist = (unsigned)(here.val);\n                op &= 15;                       /* number of extra bits */\n                if (bits < op) {\n                    hold += (unsigned long)(PUP(in)) << bits;\n                    bits += 8;\n                    if (bits < op) {\n                        hold += (unsigned long)(PUP(in)) << bits;\n                        bits += 8;\n                    }\n                }\n                dist += (unsigned)hold & ((1U << op) - 1);\n#ifdef INFLATE_STRICT\n                if (dist > dmax) {\n                    strm->msg = (char *)\"invalid distance too far back\";\n                    state->mode = BAD;\n                    break;\n                }\n#endif\n                hold >>= op;\n                bits -= op;\n                Tracevv((stderr, \"inflate:         distance %u\\n\", dist));\n                op = (unsigned)(out - beg);     /* max distance in output */\n                if (dist > op) {                /* see if copy from window */\n                    op = dist - op;             /* distance back in window */\n                    if (op > whave) {\n                        if (state->sane) {\n                            strm->msg =\n                                (char *)\"invalid distance too far back\";\n                            state->mode = BAD;\n                            break;\n                        }\n#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n                        if (len <= op - whave) {\n                            do {\n                                PUP(out) = 0;\n                            } while (--len);\n                            continue;\n                        }\n                        len -= op - whave;\n                        do {\n                            PUP(out) = 0;\n                        } while (--op > whave);\n                        if (op == 0) {\n                            from = out - dist;\n                            do {\n                                PUP(out) = PUP(from);\n                            } while (--len);\n                            continue;\n                        }\n#endif\n                    }\n                    from = window - OFF;\n                    if (wnext == 0) {           /* very common case */\n                        from += wsize - op;\n                        if (op < len) {         /* some from window */\n                            len -= op;\n                            do {\n                                PUP(out) = PUP(from);\n                            } while (--op);\n                            from = out - dist;  /* rest from output */\n                        }\n                    }\n                    else if (wnext < op) {      /* wrap around window */\n                        from += wsize + wnext - op;\n                        op -= wnext;\n                        if (op < len) {         /* some from end of window */\n                            len -= op;\n                            do {\n                                PUP(out) = PUP(from);\n                            } while (--op);\n                            from = window - OFF;\n                            if (wnext < len) {  /* some from start of window */\n                                op = wnext;\n                                len -= op;\n                                do {\n                                    PUP(out) = PUP(from);\n                                } while (--op);\n                                from = out - dist;      /* rest from output */\n                            }\n                        }\n                    }\n                    else {                      /* contiguous in window */\n                        from += wnext - op;\n                        if (op < len) {         /* some from window */\n                            len -= op;\n                            do {\n                                PUP(out) = PUP(from);\n                            } while (--op);\n                            from = out - dist;  /* rest from output */\n                        }\n                    }\n                    while (len > 2) {\n                        PUP(out) = PUP(from);\n                        PUP(out) = PUP(from);\n                        PUP(out) = PUP(from);\n                        len -= 3;\n                    }\n                    if (len) {\n                        PUP(out) = PUP(from);\n                        if (len > 1)\n                            PUP(out) = PUP(from);\n                    }\n                }\n                else {\n                    from = out - dist;          /* copy direct from output */\n                    do {                        /* minimum length is three */\n                        PUP(out) = PUP(from);\n                        PUP(out) = PUP(from);\n                        PUP(out) = PUP(from);\n                        len -= 3;\n                    } while (len > 2);\n                    if (len) {\n                        PUP(out) = PUP(from);\n                        if (len > 1)\n                            PUP(out) = PUP(from);\n                    }\n                }\n            }\n            else if ((op & 64) == 0) {          /* 2nd level distance code */\n                here = dcode[here.val + (hold & ((1U << op) - 1))];\n                goto dodist;\n            }\n            else {\n                strm->msg = (char *)\"invalid distance code\";\n                state->mode = BAD;\n                break;\n            }\n        }\n        else if ((op & 64) == 0) {              /* 2nd level length code */\n            here = lcode[here.val + (hold & ((1U << op) - 1))];\n            goto dolen;\n        }\n        else if (op & 32) {                     /* end-of-block */\n            Tracevv((stderr, \"inflate:         end of block\\n\"));\n            state->mode = TYPE;\n            break;\n        }\n        else {\n            strm->msg = (char *)\"invalid literal/length code\";\n            state->mode = BAD;\n            break;\n        }\n    } while (in < last && out < end);\n\n    /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n    len = bits >> 3;\n    in -= len;\n    bits -= len << 3;\n    hold &= (1U << bits) - 1;\n\n    /* update state and return */\n    strm->next_in = in + OFF;\n    strm->next_out = out + OFF;\n    strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));\n    strm->avail_out = (unsigned)(out < end ?\n                                 257 + (end - out) : 257 - (out - end));\n    state->hold = hold;\n    state->bits = bits;\n    return;\n}\n\n/*\n   inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):\n   - Using bit fields for code structure\n   - Different op definition to avoid & for extra bits (do & for table bits)\n   - Three separate decoding do-loops for direct, window, and wnext == 0\n   - Special case for distance > 1 copies to do overlapped load and store copy\n   - Explicit branch predictions (based on measured branch probabilities)\n   - Deferring match copy and interspersed it with decoding subsequent codes\n   - Swapping literal/length else\n   - Swapping window/direct else\n   - Larger unrolled copy loops (three is about right)\n   - Moving len -= 3 statement into middle of loop\n */\n\n#endif /* !ASMINF */\n"
  },
  {
    "path": "src/engine/external/zlib/inffast.h",
    "content": "/* inffast.h -- header to use inffast.c\n * Copyright (C) 1995-2003, 2010 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* WARNING: this file should *not* be used by applications. It is\n   part of the implementation of the compression library and is\n   subject to change. Applications should only use zlib.h.\n */\n\nvoid ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start));\n"
  },
  {
    "path": "src/engine/external/zlib/inffixed.h",
    "content": "    /* inffixed.h -- table for decoding fixed codes\n     * Generated automatically by makefixed().\n     */\n\n    /* WARNING: this file should *not* be used by applications. It\n       is part of the implementation of the compression library and\n       is subject to change. Applications should only use zlib.h.\n     */\n\n    static const code lenfix[512] = {\n        {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},\n        {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},\n        {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},\n        {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},\n        {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},\n        {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},\n        {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},\n        {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},\n        {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},\n        {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},\n        {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},\n        {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},\n        {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},\n        {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},\n        {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},\n        {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},\n        {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},\n        {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},\n        {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},\n        {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},\n        {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},\n        {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},\n        {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},\n        {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},\n        {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},\n        {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},\n        {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},\n        {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},\n        {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},\n        {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},\n        {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},\n        {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},\n        {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},\n        {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},\n        {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},\n        {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},\n        {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},\n        {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},\n        {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},\n        {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},\n        {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},\n        {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},\n        {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},\n        {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},\n        {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},\n        {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},\n        {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},\n        {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},\n        {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},\n        {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},\n        {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},\n        {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},\n        {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},\n        {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},\n        {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},\n        {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},\n        {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},\n        {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},\n        {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},\n        {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},\n        {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},\n        {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},\n        {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},\n        {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},\n        {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},\n        {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},\n        {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},\n        {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},\n        {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},\n        {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},\n        {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},\n        {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},\n        {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},\n        {0,9,255}\n    };\n\n    static const code distfix[32] = {\n        {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},\n        {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},\n        {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},\n        {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},\n        {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},\n        {22,5,193},{64,5,0}\n    };\n"
  },
  {
    "path": "src/engine/external/zlib/inflate.c",
    "content": "/* inflate.c -- zlib decompression\n * Copyright (C) 1995-2010 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/*\n * Change history:\n *\n * 1.2.beta0    24 Nov 2002\n * - First version -- complete rewrite of inflate to simplify code, avoid\n *   creation of window when not needed, minimize use of window when it is\n *   needed, make inffast.c even faster, implement gzip decoding, and to\n *   improve code readability and style over the previous zlib inflate code\n *\n * 1.2.beta1    25 Nov 2002\n * - Use pointers for available input and output checking in inffast.c\n * - Remove input and output counters in inffast.c\n * - Change inffast.c entry and loop from avail_in >= 7 to >= 6\n * - Remove unnecessary second byte pull from length extra in inffast.c\n * - Unroll direct copy to three copies per loop in inffast.c\n *\n * 1.2.beta2    4 Dec 2002\n * - Change external routine names to reduce potential conflicts\n * - Correct filename to inffixed.h for fixed tables in inflate.c\n * - Make hbuf[] unsigned char to match parameter type in inflate.c\n * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)\n *   to avoid negation problem on Alphas (64 bit) in inflate.c\n *\n * 1.2.beta3    22 Dec 2002\n * - Add comments on state->bits assertion in inffast.c\n * - Add comments on op field in inftrees.h\n * - Fix bug in reuse of allocated window after inflateReset()\n * - Remove bit fields--back to byte structure for speed\n * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths\n * - Change post-increments to pre-increments in inflate_fast(), PPC biased?\n * - Add compile time option, POSTINC, to use post-increments instead (Intel?)\n * - Make MATCH copy in inflate() much faster for when inflate_fast() not used\n * - Use local copies of stream next and avail values, as well as local bit\n *   buffer and bit count in inflate()--for speed when inflate_fast() not used\n *\n * 1.2.beta4    1 Jan 2003\n * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings\n * - Move a comment on output buffer sizes from inffast.c to inflate.c\n * - Add comments in inffast.c to introduce the inflate_fast() routine\n * - Rearrange window copies in inflate_fast() for speed and simplification\n * - Unroll last copy for window match in inflate_fast()\n * - Use local copies of window variables in inflate_fast() for speed\n * - Pull out common wnext == 0 case for speed in inflate_fast()\n * - Make op and len in inflate_fast() unsigned for consistency\n * - Add FAR to lcode and dcode declarations in inflate_fast()\n * - Simplified bad distance check in inflate_fast()\n * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new\n *   source file infback.c to provide a call-back interface to inflate for\n *   programs like gzip and unzip -- uses window as output buffer to avoid\n *   window copying\n *\n * 1.2.beta5    1 Jan 2003\n * - Improved inflateBack() interface to allow the caller to provide initial\n *   input in strm.\n * - Fixed stored blocks bug in inflateBack()\n *\n * 1.2.beta6    4 Jan 2003\n * - Added comments in inffast.c on effectiveness of POSTINC\n * - Typecasting all around to reduce compiler warnings\n * - Changed loops from while (1) or do {} while (1) to for (;;), again to\n *   make compilers happy\n * - Changed type of window in inflateBackInit() to unsigned char *\n *\n * 1.2.beta7    27 Jan 2003\n * - Changed many types to unsigned or unsigned short to avoid warnings\n * - Added inflateCopy() function\n *\n * 1.2.0        9 Mar 2003\n * - Changed inflateBack() interface to provide separate opaque descriptors\n *   for the in() and out() functions\n * - Changed inflateBack() argument and in_func typedef to swap the length\n *   and buffer address return values for the input function\n * - Check next_in and next_out for Z_NULL on entry to inflate()\n *\n * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.\n */\n\n#include \"zutil.h\"\n#include \"inftrees.h\"\n#include \"inflate.h\"\n#include \"inffast.h\"\n\n#ifdef MAKEFIXED\n#  ifndef BUILDFIXED\n#    define BUILDFIXED\n#  endif\n#endif\n\n/* function prototypes */\nlocal void fixedtables OF((struct inflate_state FAR *state));\nlocal int updatewindow OF((z_streamp strm, unsigned out));\n#ifdef BUILDFIXED\n   void makefixed OF((void));\n#endif\nlocal unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,\n                              unsigned len));\n\nint ZEXPORT inflateReset(strm)\nz_streamp strm;\n{\n    struct inflate_state FAR *state;\n\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    strm->total_in = strm->total_out = state->total = 0;\n    strm->msg = Z_NULL;\n    strm->adler = 1;        /* to support ill-conceived Java test suite */\n    state->mode = HEAD;\n    state->last = 0;\n    state->havedict = 0;\n    state->dmax = 32768U;\n    state->head = Z_NULL;\n    state->wsize = 0;\n    state->whave = 0;\n    state->wnext = 0;\n    state->hold = 0;\n    state->bits = 0;\n    state->lencode = state->distcode = state->next = state->codes;\n    state->sane = 1;\n    state->back = -1;\n    Tracev((stderr, \"inflate: reset\\n\"));\n    return Z_OK;\n}\n\nint ZEXPORT inflateReset2(strm, windowBits)\nz_streamp strm;\nint windowBits;\n{\n    int wrap;\n    struct inflate_state FAR *state;\n\n    /* get the state */\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n\n    /* extract wrap request from windowBits parameter */\n    if (windowBits < 0) {\n        wrap = 0;\n        windowBits = -windowBits;\n    }\n    else {\n        wrap = (windowBits >> 4) + 1;\n#ifdef GUNZIP\n        if (windowBits < 48)\n            windowBits &= 15;\n#endif\n    }\n\n    /* set number of window bits, free window if different */\n    if (windowBits && (windowBits < 8 || windowBits > 15))\n        return Z_STREAM_ERROR;\n    if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) {\n        ZFREE(strm, state->window);\n        state->window = Z_NULL;\n    }\n\n    /* update state and reset the rest of it */\n    state->wrap = wrap;\n    state->wbits = (unsigned)windowBits;\n    return inflateReset(strm);\n}\n\nint ZEXPORT inflateInit2_(strm, windowBits, version, stream_size)\nz_streamp strm;\nint windowBits;\nconst char *version;\nint stream_size;\n{\n    int ret;\n    struct inflate_state FAR *state;\n\n    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||\n        stream_size != (int)(sizeof(z_stream)))\n        return Z_VERSION_ERROR;\n    if (strm == Z_NULL) return Z_STREAM_ERROR;\n    strm->msg = Z_NULL;                 /* in case we return an error */\n    if (strm->zalloc == (alloc_func)0) {\n        strm->zalloc = zcalloc;\n        strm->opaque = (voidpf)0;\n    }\n    if (strm->zfree == (free_func)0) strm->zfree = zcfree;\n    state = (struct inflate_state FAR *)\n            ZALLOC(strm, 1, sizeof(struct inflate_state));\n    if (state == Z_NULL) return Z_MEM_ERROR;\n    Tracev((stderr, \"inflate: allocated\\n\"));\n    strm->state = (struct internal_state FAR *)state;\n    state->window = Z_NULL;\n    ret = inflateReset2(strm, windowBits);\n    if (ret != Z_OK) {\n        ZFREE(strm, state);\n        strm->state = Z_NULL;\n    }\n    return ret;\n}\n\nint ZEXPORT inflateInit_(strm, version, stream_size)\nz_streamp strm;\nconst char *version;\nint stream_size;\n{\n    return inflateInit2_(strm, DEF_WBITS, version, stream_size);\n}\n\nint ZEXPORT inflatePrime(strm, bits, value)\nz_streamp strm;\nint bits;\nint value;\n{\n    struct inflate_state FAR *state;\n\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    if (bits < 0) {\n        state->hold = 0;\n        state->bits = 0;\n        return Z_OK;\n    }\n    if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;\n    value &= (1L << bits) - 1;\n    state->hold += value << state->bits;\n    state->bits += bits;\n    return Z_OK;\n}\n\n/*\n   Return state with length and distance decoding tables and index sizes set to\n   fixed code decoding.  Normally this returns fixed tables from inffixed.h.\n   If BUILDFIXED is defined, then instead this routine builds the tables the\n   first time it's called, and returns those tables the first time and\n   thereafter.  This reduces the size of the code by about 2K bytes, in\n   exchange for a little execution time.  However, BUILDFIXED should not be\n   used for threaded applications, since the rewriting of the tables and virgin\n   may not be thread-safe.\n */\nlocal void fixedtables(state)\nstruct inflate_state FAR *state;\n{\n#ifdef BUILDFIXED\n    static int virgin = 1;\n    static code *lenfix, *distfix;\n    static code fixed[544];\n\n    /* build fixed huffman tables if first call (may not be thread safe) */\n    if (virgin) {\n        unsigned sym, bits;\n        static code *next;\n\n        /* literal/length table */\n        sym = 0;\n        while (sym < 144) state->lens[sym++] = 8;\n        while (sym < 256) state->lens[sym++] = 9;\n        while (sym < 280) state->lens[sym++] = 7;\n        while (sym < 288) state->lens[sym++] = 8;\n        next = fixed;\n        lenfix = next;\n        bits = 9;\n        inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);\n\n        /* distance table */\n        sym = 0;\n        while (sym < 32) state->lens[sym++] = 5;\n        distfix = next;\n        bits = 5;\n        inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);\n\n        /* do this just once */\n        virgin = 0;\n    }\n#else /* !BUILDFIXED */\n#   include \"inffixed.h\"\n#endif /* BUILDFIXED */\n    state->lencode = lenfix;\n    state->lenbits = 9;\n    state->distcode = distfix;\n    state->distbits = 5;\n}\n\n#ifdef MAKEFIXED\n#include <stdio.h>\n\n/*\n   Write out the inffixed.h that is #include'd above.  Defining MAKEFIXED also\n   defines BUILDFIXED, so the tables are built on the fly.  makefixed() writes\n   those tables to stdout, which would be piped to inffixed.h.  A small program\n   can simply call makefixed to do this:\n\n    void makefixed(void);\n\n    int main(void)\n    {\n        makefixed();\n        return 0;\n    }\n\n   Then that can be linked with zlib built with MAKEFIXED defined and run:\n\n    a.out > inffixed.h\n */\nvoid makefixed()\n{\n    unsigned low, size;\n    struct inflate_state state;\n\n    fixedtables(&state);\n    puts(\"    /* inffixed.h -- table for decoding fixed codes\");\n    puts(\"     * Generated automatically by makefixed().\");\n    puts(\"     */\");\n    puts(\"\");\n    puts(\"    /* WARNING: this file should *not* be used by applications.\");\n    puts(\"       It is part of the implementation of this library and is\");\n    puts(\"       subject to change. Applications should only use zlib.h.\");\n    puts(\"     */\");\n    puts(\"\");\n    size = 1U << 9;\n    printf(\"    static const code lenfix[%u] = {\", size);\n    low = 0;\n    for (;;) {\n        if ((low % 7) == 0) printf(\"\\n        \");\n        printf(\"{%u,%u,%d}\", state.lencode[low].op, state.lencode[low].bits,\n               state.lencode[low].val);\n        if (++low == size) break;\n        putchar(',');\n    }\n    puts(\"\\n    };\");\n    size = 1U << 5;\n    printf(\"\\n    static const code distfix[%u] = {\", size);\n    low = 0;\n    for (;;) {\n        if ((low % 6) == 0) printf(\"\\n        \");\n        printf(\"{%u,%u,%d}\", state.distcode[low].op, state.distcode[low].bits,\n               state.distcode[low].val);\n        if (++low == size) break;\n        putchar(',');\n    }\n    puts(\"\\n    };\");\n}\n#endif /* MAKEFIXED */\n\n/*\n   Update the window with the last wsize (normally 32K) bytes written before\n   returning.  If window does not exist yet, create it.  This is only called\n   when a window is already in use, or when output has been written during this\n   inflate call, but the end of the deflate stream has not been reached yet.\n   It is also called to create a window for dictionary data when a dictionary\n   is loaded.\n\n   Providing output buffers larger than 32K to inflate() should provide a speed\n   advantage, since only the last 32K of output is copied to the sliding window\n   upon return from inflate(), and since all distances after the first 32K of\n   output will fall in the output data, making match copies simpler and faster.\n   The advantage may be dependent on the size of the processor's data caches.\n */\nlocal int updatewindow(strm, out)\nz_streamp strm;\nunsigned out;\n{\n    struct inflate_state FAR *state;\n    unsigned copy, dist;\n\n    state = (struct inflate_state FAR *)strm->state;\n\n    /* if it hasn't been done already, allocate space for the window */\n    if (state->window == Z_NULL) {\n        state->window = (unsigned char FAR *)\n                        ZALLOC(strm, 1U << state->wbits,\n                               sizeof(unsigned char));\n        if (state->window == Z_NULL) return 1;\n    }\n\n    /* if window not in use yet, initialize */\n    if (state->wsize == 0) {\n        state->wsize = 1U << state->wbits;\n        state->wnext = 0;\n        state->whave = 0;\n    }\n\n    /* copy state->wsize or less output bytes into the circular window */\n    copy = out - strm->avail_out;\n    if (copy >= state->wsize) {\n        zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);\n        state->wnext = 0;\n        state->whave = state->wsize;\n    }\n    else {\n        dist = state->wsize - state->wnext;\n        if (dist > copy) dist = copy;\n        zmemcpy(state->window + state->wnext, strm->next_out - copy, dist);\n        copy -= dist;\n        if (copy) {\n            zmemcpy(state->window, strm->next_out - copy, copy);\n            state->wnext = copy;\n            state->whave = state->wsize;\n        }\n        else {\n            state->wnext += dist;\n            if (state->wnext == state->wsize) state->wnext = 0;\n            if (state->whave < state->wsize) state->whave += dist;\n        }\n    }\n    return 0;\n}\n\n/* Macros for inflate(): */\n\n/* check function to use adler32() for zlib or crc32() for gzip */\n#ifdef GUNZIP\n#  define UPDATE(check, buf, len) \\\n    (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))\n#else\n#  define UPDATE(check, buf, len) adler32(check, buf, len)\n#endif\n\n/* check macros for header crc */\n#ifdef GUNZIP\n#  define CRC2(check, word) \\\n    do { \\\n        hbuf[0] = (unsigned char)(word); \\\n        hbuf[1] = (unsigned char)((word) >> 8); \\\n        check = crc32(check, hbuf, 2); \\\n    } while (0)\n\n#  define CRC4(check, word) \\\n    do { \\\n        hbuf[0] = (unsigned char)(word); \\\n        hbuf[1] = (unsigned char)((word) >> 8); \\\n        hbuf[2] = (unsigned char)((word) >> 16); \\\n        hbuf[3] = (unsigned char)((word) >> 24); \\\n        check = crc32(check, hbuf, 4); \\\n    } while (0)\n#endif\n\n/* Load registers with state in inflate() for speed */\n#define LOAD() \\\n    do { \\\n        put = strm->next_out; \\\n        left = strm->avail_out; \\\n        next = strm->next_in; \\\n        have = strm->avail_in; \\\n        hold = state->hold; \\\n        bits = state->bits; \\\n    } while (0)\n\n/* Restore state from registers in inflate() */\n#define RESTORE() \\\n    do { \\\n        strm->next_out = put; \\\n        strm->avail_out = left; \\\n        strm->next_in = next; \\\n        strm->avail_in = have; \\\n        state->hold = hold; \\\n        state->bits = bits; \\\n    } while (0)\n\n/* Clear the input bit accumulator */\n#define INITBITS() \\\n    do { \\\n        hold = 0; \\\n        bits = 0; \\\n    } while (0)\n\n/* Get a byte of input into the bit accumulator, or return from inflate()\n   if there is no input available. */\n#define PULLBYTE() \\\n    do { \\\n        if (have == 0) goto inf_leave; \\\n        have--; \\\n        hold += (unsigned long)(*next++) << bits; \\\n        bits += 8; \\\n    } while (0)\n\n/* Assure that there are at least n bits in the bit accumulator.  If there is\n   not enough available input to do that, then return from inflate(). */\n#define NEEDBITS(n) \\\n    do { \\\n        while (bits < (unsigned)(n)) \\\n            PULLBYTE(); \\\n    } while (0)\n\n/* Return the low n bits of the bit accumulator (n < 16) */\n#define BITS(n) \\\n    ((unsigned)hold & ((1U << (n)) - 1))\n\n/* Remove n bits from the bit accumulator */\n#define DROPBITS(n) \\\n    do { \\\n        hold >>= (n); \\\n        bits -= (unsigned)(n); \\\n    } while (0)\n\n/* Remove zero to seven bits as needed to go to a byte boundary */\n#define BYTEBITS() \\\n    do { \\\n        hold >>= bits & 7; \\\n        bits -= bits & 7; \\\n    } while (0)\n\n/* Reverse the bytes in a 32-bit value */\n#define REVERSE(q) \\\n    ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \\\n     (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))\n\n/*\n   inflate() uses a state machine to process as much input data and generate as\n   much output data as possible before returning.  The state machine is\n   structured roughly as follows:\n\n    for (;;) switch (state) {\n    ...\n    case STATEn:\n        if (not enough input data or output space to make progress)\n            return;\n        ... make progress ...\n        state = STATEm;\n        break;\n    ...\n    }\n\n   so when inflate() is called again, the same case is attempted again, and\n   if the appropriate resources are provided, the machine proceeds to the\n   next state.  The NEEDBITS() macro is usually the way the state evaluates\n   whether it can proceed or should return.  NEEDBITS() does the return if\n   the requested bits are not available.  The typical use of the BITS macros\n   is:\n\n        NEEDBITS(n);\n        ... do something with BITS(n) ...\n        DROPBITS(n);\n\n   where NEEDBITS(n) either returns from inflate() if there isn't enough\n   input left to load n bits into the accumulator, or it continues.  BITS(n)\n   gives the low n bits in the accumulator.  When done, DROPBITS(n) drops\n   the low n bits off the accumulator.  INITBITS() clears the accumulator\n   and sets the number of available bits to zero.  BYTEBITS() discards just\n   enough bits to put the accumulator on a byte boundary.  After BYTEBITS()\n   and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.\n\n   NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return\n   if there is no input available.  The decoding of variable length codes uses\n   PULLBYTE() directly in order to pull just enough bytes to decode the next\n   code, and no more.\n\n   Some states loop until they get enough input, making sure that enough\n   state information is maintained to continue the loop where it left off\n   if NEEDBITS() returns in the loop.  For example, want, need, and keep\n   would all have to actually be part of the saved state in case NEEDBITS()\n   returns:\n\n    case STATEw:\n        while (want < need) {\n            NEEDBITS(n);\n            keep[want++] = BITS(n);\n            DROPBITS(n);\n        }\n        state = STATEx;\n    case STATEx:\n\n   As shown above, if the next state is also the next case, then the break\n   is omitted.\n\n   A state may also return if there is not enough output space available to\n   complete that state.  Those states are copying stored data, writing a\n   literal byte, and copying a matching string.\n\n   When returning, a \"goto inf_leave\" is used to update the total counters,\n   update the check value, and determine whether any progress has been made\n   during that inflate() call in order to return the proper return code.\n   Progress is defined as a change in either strm->avail_in or strm->avail_out.\n   When there is a window, goto inf_leave will update the window with the last\n   output written.  If a goto inf_leave occurs in the middle of decompression\n   and there is no window currently, goto inf_leave will create one and copy\n   output to the window for the next call of inflate().\n\n   In this implementation, the flush parameter of inflate() only affects the\n   return code (per zlib.h).  inflate() always writes as much as possible to\n   strm->next_out, given the space available and the provided input--the effect\n   documented in zlib.h of Z_SYNC_FLUSH.  Furthermore, inflate() always defers\n   the allocation of and copying into a sliding window until necessary, which\n   provides the effect documented in zlib.h for Z_FINISH when the entire input\n   stream available.  So the only thing the flush parameter actually does is:\n   when flush is set to Z_FINISH, inflate() cannot return Z_OK.  Instead it\n   will return Z_BUF_ERROR if it has not reached the end of the stream.\n */\n\nint ZEXPORT inflate(strm, flush)\nz_streamp strm;\nint flush;\n{\n    struct inflate_state FAR *state;\n    unsigned char FAR *next;    /* next input */\n    unsigned char FAR *put;     /* next output */\n    unsigned have, left;        /* available input and output */\n    unsigned long hold;         /* bit buffer */\n    unsigned bits;              /* bits in bit buffer */\n    unsigned in, out;           /* save starting available input and output */\n    unsigned copy;              /* number of stored or match bytes to copy */\n    unsigned char FAR *from;    /* where to copy match bytes from */\n    code here;                  /* current decoding table entry */\n    code last;                  /* parent table entry */\n    unsigned len;               /* length to copy for repeats, bits to drop */\n    int ret;                    /* return code */\n#ifdef GUNZIP\n    unsigned char hbuf[4];      /* buffer for gzip header crc calculation */\n#endif\n    static const unsigned short order[19] = /* permutation of code lengths */\n        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};\n\n    if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||\n        (strm->next_in == Z_NULL && strm->avail_in != 0))\n        return Z_STREAM_ERROR;\n\n    state = (struct inflate_state FAR *)strm->state;\n    if (state->mode == TYPE) state->mode = TYPEDO;      /* skip check */\n    LOAD();\n    in = have;\n    out = left;\n    ret = Z_OK;\n    for (;;)\n        switch (state->mode) {\n        case HEAD:\n            if (state->wrap == 0) {\n                state->mode = TYPEDO;\n                break;\n            }\n            NEEDBITS(16);\n#ifdef GUNZIP\n            if ((state->wrap & 2) && hold == 0x8b1f) {  /* gzip header */\n                state->check = crc32(0L, Z_NULL, 0);\n                CRC2(state->check, hold);\n                INITBITS();\n                state->mode = FLAGS;\n                break;\n            }\n            state->flags = 0;           /* expect zlib header */\n            if (state->head != Z_NULL)\n                state->head->done = -1;\n            if (!(state->wrap & 1) ||   /* check if zlib header allowed */\n#else\n            if (\n#endif\n                ((BITS(8) << 8) + (hold >> 8)) % 31) {\n                strm->msg = (char *)\"incorrect header check\";\n                state->mode = BAD;\n                break;\n            }\n            if (BITS(4) != Z_DEFLATED) {\n                strm->msg = (char *)\"unknown compression method\";\n                state->mode = BAD;\n                break;\n            }\n            DROPBITS(4);\n            len = BITS(4) + 8;\n            if (state->wbits == 0)\n                state->wbits = len;\n            else if (len > state->wbits) {\n                strm->msg = (char *)\"invalid window size\";\n                state->mode = BAD;\n                break;\n            }\n            state->dmax = 1U << len;\n            Tracev((stderr, \"inflate:   zlib header ok\\n\"));\n            strm->adler = state->check = adler32(0L, Z_NULL, 0);\n            state->mode = hold & 0x200 ? DICTID : TYPE;\n            INITBITS();\n            break;\n#ifdef GUNZIP\n        case FLAGS:\n            NEEDBITS(16);\n            state->flags = (int)(hold);\n            if ((state->flags & 0xff) != Z_DEFLATED) {\n                strm->msg = (char *)\"unknown compression method\";\n                state->mode = BAD;\n                break;\n            }\n            if (state->flags & 0xe000) {\n                strm->msg = (char *)\"unknown header flags set\";\n                state->mode = BAD;\n                break;\n            }\n            if (state->head != Z_NULL)\n                state->head->text = (int)((hold >> 8) & 1);\n            if (state->flags & 0x0200) CRC2(state->check, hold);\n            INITBITS();\n            state->mode = TIME;\n        case TIME:\n            NEEDBITS(32);\n            if (state->head != Z_NULL)\n                state->head->time = hold;\n            if (state->flags & 0x0200) CRC4(state->check, hold);\n            INITBITS();\n            state->mode = OS;\n        case OS:\n            NEEDBITS(16);\n            if (state->head != Z_NULL) {\n                state->head->xflags = (int)(hold & 0xff);\n                state->head->os = (int)(hold >> 8);\n            }\n            if (state->flags & 0x0200) CRC2(state->check, hold);\n            INITBITS();\n            state->mode = EXLEN;\n        case EXLEN:\n            if (state->flags & 0x0400) {\n                NEEDBITS(16);\n                state->length = (unsigned)(hold);\n                if (state->head != Z_NULL)\n                    state->head->extra_len = (unsigned)hold;\n                if (state->flags & 0x0200) CRC2(state->check, hold);\n                INITBITS();\n            }\n            else if (state->head != Z_NULL)\n                state->head->extra = Z_NULL;\n            state->mode = EXTRA;\n        case EXTRA:\n            if (state->flags & 0x0400) {\n                copy = state->length;\n                if (copy > have) copy = have;\n                if (copy) {\n                    if (state->head != Z_NULL &&\n                        state->head->extra != Z_NULL) {\n                        len = state->head->extra_len - state->length;\n                        zmemcpy(state->head->extra + len, next,\n                                len + copy > state->head->extra_max ?\n                                state->head->extra_max - len : copy);\n                    }\n                    if (state->flags & 0x0200)\n                        state->check = crc32(state->check, next, copy);\n                    have -= copy;\n                    next += copy;\n                    state->length -= copy;\n                }\n                if (state->length) goto inf_leave;\n            }\n            state->length = 0;\n            state->mode = NAME;\n        case NAME:\n            if (state->flags & 0x0800) {\n                if (have == 0) goto inf_leave;\n                copy = 0;\n                do {\n                    len = (unsigned)(next[copy++]);\n                    if (state->head != Z_NULL &&\n                            state->head->name != Z_NULL &&\n                            state->length < state->head->name_max)\n                        state->head->name[state->length++] = len;\n                } while (len && copy < have);\n                if (state->flags & 0x0200)\n                    state->check = crc32(state->check, next, copy);\n                have -= copy;\n                next += copy;\n                if (len) goto inf_leave;\n            }\n            else if (state->head != Z_NULL)\n                state->head->name = Z_NULL;\n            state->length = 0;\n            state->mode = COMMENT;\n        case COMMENT:\n            if (state->flags & 0x1000) {\n                if (have == 0) goto inf_leave;\n                copy = 0;\n                do {\n                    len = (unsigned)(next[copy++]);\n                    if (state->head != Z_NULL &&\n                            state->head->comment != Z_NULL &&\n                            state->length < state->head->comm_max)\n                        state->head->comment[state->length++] = len;\n                } while (len && copy < have);\n                if (state->flags & 0x0200)\n                    state->check = crc32(state->check, next, copy);\n                have -= copy;\n                next += copy;\n                if (len) goto inf_leave;\n            }\n            else if (state->head != Z_NULL)\n                state->head->comment = Z_NULL;\n            state->mode = HCRC;\n        case HCRC:\n            if (state->flags & 0x0200) {\n                NEEDBITS(16);\n                if (hold != (state->check & 0xffff)) {\n                    strm->msg = (char *)\"header crc mismatch\";\n                    state->mode = BAD;\n                    break;\n                }\n                INITBITS();\n            }\n            if (state->head != Z_NULL) {\n                state->head->hcrc = (int)((state->flags >> 9) & 1);\n                state->head->done = 1;\n            }\n            strm->adler = state->check = crc32(0L, Z_NULL, 0);\n            state->mode = TYPE;\n            break;\n#endif\n        case DICTID:\n            NEEDBITS(32);\n            strm->adler = state->check = REVERSE(hold);\n            INITBITS();\n            state->mode = DICT;\n        case DICT:\n            if (state->havedict == 0) {\n                RESTORE();\n                return Z_NEED_DICT;\n            }\n            strm->adler = state->check = adler32(0L, Z_NULL, 0);\n            state->mode = TYPE;\n        case TYPE:\n            if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;\n        case TYPEDO:\n            if (state->last) {\n                BYTEBITS();\n                state->mode = CHECK;\n                break;\n            }\n            NEEDBITS(3);\n            state->last = BITS(1);\n            DROPBITS(1);\n            switch (BITS(2)) {\n            case 0:                             /* stored block */\n                Tracev((stderr, \"inflate:     stored block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = STORED;\n                break;\n            case 1:                             /* fixed block */\n                fixedtables(state);\n                Tracev((stderr, \"inflate:     fixed codes block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = LEN_;             /* decode codes */\n                if (flush == Z_TREES) {\n                    DROPBITS(2);\n                    goto inf_leave;\n                }\n                break;\n            case 2:                             /* dynamic block */\n                Tracev((stderr, \"inflate:     dynamic codes block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = TABLE;\n                break;\n            case 3:\n                strm->msg = (char *)\"invalid block type\";\n                state->mode = BAD;\n            }\n            DROPBITS(2);\n            break;\n        case STORED:\n            BYTEBITS();                         /* go to byte boundary */\n            NEEDBITS(32);\n            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {\n                strm->msg = (char *)\"invalid stored block lengths\";\n                state->mode = BAD;\n                break;\n            }\n            state->length = (unsigned)hold & 0xffff;\n            Tracev((stderr, \"inflate:       stored length %u\\n\",\n                    state->length));\n            INITBITS();\n            state->mode = COPY_;\n            if (flush == Z_TREES) goto inf_leave;\n        case COPY_:\n            state->mode = COPY;\n        case COPY:\n            copy = state->length;\n            if (copy) {\n                if (copy > have) copy = have;\n                if (copy > left) copy = left;\n                if (copy == 0) goto inf_leave;\n                zmemcpy(put, next, copy);\n                have -= copy;\n                next += copy;\n                left -= copy;\n                put += copy;\n                state->length -= copy;\n                break;\n            }\n            Tracev((stderr, \"inflate:       stored end\\n\"));\n            state->mode = TYPE;\n            break;\n        case TABLE:\n            NEEDBITS(14);\n            state->nlen = BITS(5) + 257;\n            DROPBITS(5);\n            state->ndist = BITS(5) + 1;\n            DROPBITS(5);\n            state->ncode = BITS(4) + 4;\n            DROPBITS(4);\n#ifndef PKZIP_BUG_WORKAROUND\n            if (state->nlen > 286 || state->ndist > 30) {\n                strm->msg = (char *)\"too many length or distance symbols\";\n                state->mode = BAD;\n                break;\n            }\n#endif\n            Tracev((stderr, \"inflate:       table sizes ok\\n\"));\n            state->have = 0;\n            state->mode = LENLENS;\n        case LENLENS:\n            while (state->have < state->ncode) {\n                NEEDBITS(3);\n                state->lens[order[state->have++]] = (unsigned short)BITS(3);\n                DROPBITS(3);\n            }\n            while (state->have < 19)\n                state->lens[order[state->have++]] = 0;\n            state->next = state->codes;\n            state->lencode = (code const FAR *)(state->next);\n            state->lenbits = 7;\n            ret = inflate_table(CODES, state->lens, 19, &(state->next),\n                                &(state->lenbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid code lengths set\";\n                state->mode = BAD;\n                break;\n            }\n            Tracev((stderr, \"inflate:       code lengths ok\\n\"));\n            state->have = 0;\n            state->mode = CODELENS;\n        case CODELENS:\n            while (state->have < state->nlen + state->ndist) {\n                for (;;) {\n                    here = state->lencode[BITS(state->lenbits)];\n                    if ((unsigned)(here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                if (here.val < 16) {\n                    NEEDBITS(here.bits);\n                    DROPBITS(here.bits);\n                    state->lens[state->have++] = here.val;\n                }\n                else {\n                    if (here.val == 16) {\n                        NEEDBITS(here.bits + 2);\n                        DROPBITS(here.bits);\n                        if (state->have == 0) {\n                            strm->msg = (char *)\"invalid bit length repeat\";\n                            state->mode = BAD;\n                            break;\n                        }\n                        len = state->lens[state->have - 1];\n                        copy = 3 + BITS(2);\n                        DROPBITS(2);\n                    }\n                    else if (here.val == 17) {\n                        NEEDBITS(here.bits + 3);\n                        DROPBITS(here.bits);\n                        len = 0;\n                        copy = 3 + BITS(3);\n                        DROPBITS(3);\n                    }\n                    else {\n                        NEEDBITS(here.bits + 7);\n                        DROPBITS(here.bits);\n                        len = 0;\n                        copy = 11 + BITS(7);\n                        DROPBITS(7);\n                    }\n                    if (state->have + copy > state->nlen + state->ndist) {\n                        strm->msg = (char *)\"invalid bit length repeat\";\n                        state->mode = BAD;\n                        break;\n                    }\n                    while (copy--)\n                        state->lens[state->have++] = (unsigned short)len;\n                }\n            }\n\n            /* handle error breaks in while */\n            if (state->mode == BAD) break;\n\n            /* check for end-of-block code (better have one) */\n            if (state->lens[256] == 0) {\n                strm->msg = (char *)\"invalid code -- missing end-of-block\";\n                state->mode = BAD;\n                break;\n            }\n\n            /* build code tables -- note: do not change the lenbits or distbits\n               values here (9 and 6) without reading the comments in inftrees.h\n               concerning the ENOUGH constants, which depend on those values */\n            state->next = state->codes;\n            state->lencode = (code const FAR *)(state->next);\n            state->lenbits = 9;\n            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),\n                                &(state->lenbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid literal/lengths set\";\n                state->mode = BAD;\n                break;\n            }\n            state->distcode = (code const FAR *)(state->next);\n            state->distbits = 6;\n            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,\n                            &(state->next), &(state->distbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid distances set\";\n                state->mode = BAD;\n                break;\n            }\n            Tracev((stderr, \"inflate:       codes ok\\n\"));\n            state->mode = LEN_;\n            if (flush == Z_TREES) goto inf_leave;\n        case LEN_:\n            state->mode = LEN;\n        case LEN:\n            if (have >= 6 && left >= 258) {\n                RESTORE();\n                inflate_fast(strm, out);\n                LOAD();\n                if (state->mode == TYPE)\n                    state->back = -1;\n                break;\n            }\n            state->back = 0;\n            for (;;) {\n                here = state->lencode[BITS(state->lenbits)];\n                if ((unsigned)(here.bits) <= bits) break;\n                PULLBYTE();\n            }\n            if (here.op && (here.op & 0xf0) == 0) {\n                last = here;\n                for (;;) {\n                    here = state->lencode[last.val +\n                            (BITS(last.bits + last.op) >> last.bits)];\n                    if ((unsigned)(last.bits + here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                DROPBITS(last.bits);\n                state->back += last.bits;\n            }\n            DROPBITS(here.bits);\n            state->back += here.bits;\n            state->length = (unsigned)here.val;\n            if ((int)(here.op) == 0) {\n                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n                        \"inflate:         literal '%c'\\n\" :\n                        \"inflate:         literal 0x%02x\\n\", here.val));\n                state->mode = LIT;\n                break;\n            }\n            if (here.op & 32) {\n                Tracevv((stderr, \"inflate:         end of block\\n\"));\n                state->back = -1;\n                state->mode = TYPE;\n                break;\n            }\n            if (here.op & 64) {\n                strm->msg = (char *)\"invalid literal/length code\";\n                state->mode = BAD;\n                break;\n            }\n            state->extra = (unsigned)(here.op) & 15;\n            state->mode = LENEXT;\n        case LENEXT:\n            if (state->extra) {\n                NEEDBITS(state->extra);\n                state->length += BITS(state->extra);\n                DROPBITS(state->extra);\n                state->back += state->extra;\n            }\n            Tracevv((stderr, \"inflate:         length %u\\n\", state->length));\n            state->was = state->length;\n            state->mode = DIST;\n        case DIST:\n            for (;;) {\n                here = state->distcode[BITS(state->distbits)];\n                if ((unsigned)(here.bits) <= bits) break;\n                PULLBYTE();\n            }\n            if ((here.op & 0xf0) == 0) {\n                last = here;\n                for (;;) {\n                    here = state->distcode[last.val +\n                            (BITS(last.bits + last.op) >> last.bits)];\n                    if ((unsigned)(last.bits + here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                DROPBITS(last.bits);\n                state->back += last.bits;\n            }\n            DROPBITS(here.bits);\n            state->back += here.bits;\n            if (here.op & 64) {\n                strm->msg = (char *)\"invalid distance code\";\n                state->mode = BAD;\n                break;\n            }\n            state->offset = (unsigned)here.val;\n            state->extra = (unsigned)(here.op) & 15;\n            state->mode = DISTEXT;\n        case DISTEXT:\n            if (state->extra) {\n                NEEDBITS(state->extra);\n                state->offset += BITS(state->extra);\n                DROPBITS(state->extra);\n                state->back += state->extra;\n            }\n#ifdef INFLATE_STRICT\n            if (state->offset > state->dmax) {\n                strm->msg = (char *)\"invalid distance too far back\";\n                state->mode = BAD;\n                break;\n            }\n#endif\n            Tracevv((stderr, \"inflate:         distance %u\\n\", state->offset));\n            state->mode = MATCH;\n        case MATCH:\n            if (left == 0) goto inf_leave;\n            copy = out - left;\n            if (state->offset > copy) {         /* copy from window */\n                copy = state->offset - copy;\n                if (copy > state->whave) {\n                    if (state->sane) {\n                        strm->msg = (char *)\"invalid distance too far back\";\n                        state->mode = BAD;\n                        break;\n                    }\n#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n                    Trace((stderr, \"inflate.c too far\\n\"));\n                    copy -= state->whave;\n                    if (copy > state->length) copy = state->length;\n                    if (copy > left) copy = left;\n                    left -= copy;\n                    state->length -= copy;\n                    do {\n                        *put++ = 0;\n                    } while (--copy);\n                    if (state->length == 0) state->mode = LEN;\n                    break;\n#endif\n                }\n                if (copy > state->wnext) {\n                    copy -= state->wnext;\n                    from = state->window + (state->wsize - copy);\n                }\n                else\n                    from = state->window + (state->wnext - copy);\n                if (copy > state->length) copy = state->length;\n            }\n            else {                              /* copy from output */\n                from = put - state->offset;\n                copy = state->length;\n            }\n            if (copy > left) copy = left;\n            left -= copy;\n            state->length -= copy;\n            do {\n                *put++ = *from++;\n            } while (--copy);\n            if (state->length == 0) state->mode = LEN;\n            break;\n        case LIT:\n            if (left == 0) goto inf_leave;\n            *put++ = (unsigned char)(state->length);\n            left--;\n            state->mode = LEN;\n            break;\n        case CHECK:\n            if (state->wrap) {\n                NEEDBITS(32);\n                out -= left;\n                strm->total_out += out;\n                state->total += out;\n                if (out)\n                    strm->adler = state->check =\n                        UPDATE(state->check, put - out, out);\n                out = left;\n                if ((\n#ifdef GUNZIP\n                     state->flags ? hold :\n#endif\n                     REVERSE(hold)) != state->check) {\n                    strm->msg = (char *)\"incorrect data check\";\n                    state->mode = BAD;\n                    break;\n                }\n                INITBITS();\n                Tracev((stderr, \"inflate:   check matches trailer\\n\"));\n            }\n#ifdef GUNZIP\n            state->mode = LENGTH;\n        case LENGTH:\n            if (state->wrap && state->flags) {\n                NEEDBITS(32);\n                if (hold != (state->total & 0xffffffffUL)) {\n                    strm->msg = (char *)\"incorrect length check\";\n                    state->mode = BAD;\n                    break;\n                }\n                INITBITS();\n                Tracev((stderr, \"inflate:   length matches trailer\\n\"));\n            }\n#endif\n            state->mode = DONE;\n        case DONE:\n            ret = Z_STREAM_END;\n            goto inf_leave;\n        case BAD:\n            ret = Z_DATA_ERROR;\n            goto inf_leave;\n        case MEM:\n            return Z_MEM_ERROR;\n        case SYNC:\n        default:\n            return Z_STREAM_ERROR;\n        }\n\n    /*\n       Return from inflate(), updating the total counts and the check value.\n       If there was no progress during the inflate() call, return a buffer\n       error.  Call updatewindow() to create and/or update the window state.\n       Note: a memory error from inflate() is non-recoverable.\n     */\n  inf_leave:\n    RESTORE();\n    if (state->wsize || (state->mode < CHECK && out != strm->avail_out))\n        if (updatewindow(strm, out)) {\n            state->mode = MEM;\n            return Z_MEM_ERROR;\n        }\n    in -= strm->avail_in;\n    out -= strm->avail_out;\n    strm->total_in += in;\n    strm->total_out += out;\n    state->total += out;\n    if (state->wrap && out)\n        strm->adler = state->check =\n            UPDATE(state->check, strm->next_out - out, out);\n    strm->data_type = state->bits + (state->last ? 64 : 0) +\n                      (state->mode == TYPE ? 128 : 0) +\n                      (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0);\n    if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)\n        ret = Z_BUF_ERROR;\n    return ret;\n}\n\nint ZEXPORT inflateEnd(strm)\nz_streamp strm;\n{\n    struct inflate_state FAR *state;\n    if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)\n        return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    if (state->window != Z_NULL) ZFREE(strm, state->window);\n    ZFREE(strm, strm->state);\n    strm->state = Z_NULL;\n    Tracev((stderr, \"inflate: end\\n\"));\n    return Z_OK;\n}\n\nint ZEXPORT inflateSetDictionary(strm, dictionary, dictLength)\nz_streamp strm;\nconst Bytef *dictionary;\nuInt dictLength;\n{\n    struct inflate_state FAR *state;\n    unsigned long id;\n\n    /* check state */\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    if (state->wrap != 0 && state->mode != DICT)\n        return Z_STREAM_ERROR;\n\n    /* check for correct dictionary id */\n    if (state->mode == DICT) {\n        id = adler32(0L, Z_NULL, 0);\n        id = adler32(id, dictionary, dictLength);\n        if (id != state->check)\n            return Z_DATA_ERROR;\n    }\n\n    /* copy dictionary to window */\n    if (updatewindow(strm, strm->avail_out)) {\n        state->mode = MEM;\n        return Z_MEM_ERROR;\n    }\n    if (dictLength > state->wsize) {\n        zmemcpy(state->window, dictionary + dictLength - state->wsize,\n                state->wsize);\n        state->whave = state->wsize;\n    }\n    else {\n        zmemcpy(state->window + state->wsize - dictLength, dictionary,\n                dictLength);\n        state->whave = dictLength;\n    }\n    state->havedict = 1;\n    Tracev((stderr, \"inflate:   dictionary set\\n\"));\n    return Z_OK;\n}\n\nint ZEXPORT inflateGetHeader(strm, head)\nz_streamp strm;\ngz_headerp head;\n{\n    struct inflate_state FAR *state;\n\n    /* check state */\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;\n\n    /* save header structure */\n    state->head = head;\n    head->done = 0;\n    return Z_OK;\n}\n\n/*\n   Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff.  Return when found\n   or when out of input.  When called, *have is the number of pattern bytes\n   found in order so far, in 0..3.  On return *have is updated to the new\n   state.  If on return *have equals four, then the pattern was found and the\n   return value is how many bytes were read including the last byte of the\n   pattern.  If *have is less than four, then the pattern has not been found\n   yet and the return value is len.  In the latter case, syncsearch() can be\n   called again with more data and the *have state.  *have is initialized to\n   zero for the first call.\n */\nlocal unsigned syncsearch(have, buf, len)\nunsigned FAR *have;\nunsigned char FAR *buf;\nunsigned len;\n{\n    unsigned got;\n    unsigned next;\n\n    got = *have;\n    next = 0;\n    while (next < len && got < 4) {\n        if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))\n            got++;\n        else if (buf[next])\n            got = 0;\n        else\n            got = 4 - got;\n        next++;\n    }\n    *have = got;\n    return next;\n}\n\nint ZEXPORT inflateSync(strm)\nz_streamp strm;\n{\n    unsigned len;               /* number of bytes to look at or looked at */\n    unsigned long in, out;      /* temporary to save total_in and total_out */\n    unsigned char buf[4];       /* to restore bit buffer to byte string */\n    struct inflate_state FAR *state;\n\n    /* check parameters */\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;\n\n    /* if first time, start search in bit buffer */\n    if (state->mode != SYNC) {\n        state->mode = SYNC;\n        state->hold <<= state->bits & 7;\n        state->bits -= state->bits & 7;\n        len = 0;\n        while (state->bits >= 8) {\n            buf[len++] = (unsigned char)(state->hold);\n            state->hold >>= 8;\n            state->bits -= 8;\n        }\n        state->have = 0;\n        syncsearch(&(state->have), buf, len);\n    }\n\n    /* search available input */\n    len = syncsearch(&(state->have), strm->next_in, strm->avail_in);\n    strm->avail_in -= len;\n    strm->next_in += len;\n    strm->total_in += len;\n\n    /* return no joy or set up to restart inflate() on a new block */\n    if (state->have != 4) return Z_DATA_ERROR;\n    in = strm->total_in;  out = strm->total_out;\n    inflateReset(strm);\n    strm->total_in = in;  strm->total_out = out;\n    state->mode = TYPE;\n    return Z_OK;\n}\n\n/*\n   Returns true if inflate is currently at the end of a block generated by\n   Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP\n   implementation to provide an additional safety check. PPP uses\n   Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored\n   block. When decompressing, PPP checks that at the end of input packet,\n   inflate is waiting for these length bytes.\n */\nint ZEXPORT inflateSyncPoint(strm)\nz_streamp strm;\n{\n    struct inflate_state FAR *state;\n\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    return state->mode == STORED && state->bits == 0;\n}\n\nint ZEXPORT inflateCopy(dest, source)\nz_streamp dest;\nz_streamp source;\n{\n    struct inflate_state FAR *state;\n    struct inflate_state FAR *copy;\n    unsigned char FAR *window;\n    unsigned wsize;\n\n    /* check input */\n    if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||\n        source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)\n        return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)source->state;\n\n    /* allocate space */\n    copy = (struct inflate_state FAR *)\n           ZALLOC(source, 1, sizeof(struct inflate_state));\n    if (copy == Z_NULL) return Z_MEM_ERROR;\n    window = Z_NULL;\n    if (state->window != Z_NULL) {\n        window = (unsigned char FAR *)\n                 ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));\n        if (window == Z_NULL) {\n            ZFREE(source, copy);\n            return Z_MEM_ERROR;\n        }\n    }\n\n    /* copy state */\n    zmemcpy(dest, source, sizeof(z_stream));\n    zmemcpy(copy, state, sizeof(struct inflate_state));\n    if (state->lencode >= state->codes &&\n        state->lencode <= state->codes + ENOUGH - 1) {\n        copy->lencode = copy->codes + (state->lencode - state->codes);\n        copy->distcode = copy->codes + (state->distcode - state->codes);\n    }\n    copy->next = copy->codes + (state->next - state->codes);\n    if (window != Z_NULL) {\n        wsize = 1U << state->wbits;\n        zmemcpy(window, state->window, wsize);\n    }\n    copy->window = window;\n    dest->state = (struct internal_state FAR *)copy;\n    return Z_OK;\n}\n\nint ZEXPORT inflateUndermine(strm, subvert)\nz_streamp strm;\nint subvert;\n{\n    struct inflate_state FAR *state;\n\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    state->sane = !subvert;\n#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n    return Z_OK;\n#else\n    state->sane = 1;\n    return Z_DATA_ERROR;\n#endif\n}\n\nlong ZEXPORT inflateMark(strm)\nz_streamp strm;\n{\n    struct inflate_state FAR *state;\n\n    if (strm == Z_NULL || strm->state == Z_NULL) return -1L << 16;\n    state = (struct inflate_state FAR *)strm->state;\n    return ((long)(state->back) << 16) +\n        (state->mode == COPY ? state->length :\n            (state->mode == MATCH ? state->was - state->length : 0));\n}\n"
  },
  {
    "path": "src/engine/external/zlib/inflate.h",
    "content": "/* inflate.h -- internal inflate state definition\n * Copyright (C) 1995-2009 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* WARNING: this file should *not* be used by applications. It is\n   part of the implementation of the compression library and is\n   subject to change. Applications should only use zlib.h.\n */\n\n/* define NO_GZIP when compiling if you want to disable gzip header and\n   trailer decoding by inflate().  NO_GZIP would be used to avoid linking in\n   the crc code when it is not needed.  For shared libraries, gzip decoding\n   should be left enabled. */\n#ifndef NO_GZIP\n#  define GUNZIP\n#endif\n\n/* Possible inflate modes between inflate() calls */\ntypedef enum {\n    HEAD,       /* i: waiting for magic header */\n    FLAGS,      /* i: waiting for method and flags (gzip) */\n    TIME,       /* i: waiting for modification time (gzip) */\n    OS,         /* i: waiting for extra flags and operating system (gzip) */\n    EXLEN,      /* i: waiting for extra length (gzip) */\n    EXTRA,      /* i: waiting for extra bytes (gzip) */\n    NAME,       /* i: waiting for end of file name (gzip) */\n    COMMENT,    /* i: waiting for end of comment (gzip) */\n    HCRC,       /* i: waiting for header crc (gzip) */\n    DICTID,     /* i: waiting for dictionary check value */\n    DICT,       /* waiting for inflateSetDictionary() call */\n        TYPE,       /* i: waiting for type bits, including last-flag bit */\n        TYPEDO,     /* i: same, but skip check to exit inflate on new block */\n        STORED,     /* i: waiting for stored size (length and complement) */\n        COPY_,      /* i/o: same as COPY below, but only first time in */\n        COPY,       /* i/o: waiting for input or output to copy stored block */\n        TABLE,      /* i: waiting for dynamic block table lengths */\n        LENLENS,    /* i: waiting for code length code lengths */\n        CODELENS,   /* i: waiting for length/lit and distance code lengths */\n            LEN_,       /* i: same as LEN below, but only first time in */\n            LEN,        /* i: waiting for length/lit/eob code */\n            LENEXT,     /* i: waiting for length extra bits */\n            DIST,       /* i: waiting for distance code */\n            DISTEXT,    /* i: waiting for distance extra bits */\n            MATCH,      /* o: waiting for output space to copy string */\n            LIT,        /* o: waiting for output space to write literal */\n    CHECK,      /* i: waiting for 32-bit check value */\n    LENGTH,     /* i: waiting for 32-bit length (gzip) */\n    DONE,       /* finished check, done -- remain here until reset */\n    BAD,        /* got a data error -- remain here until reset */\n    MEM,        /* got an inflate() memory error -- remain here until reset */\n    SYNC        /* looking for synchronization bytes to restart inflate() */\n} inflate_mode;\n\n/*\n    State transitions between above modes -\n\n    (most modes can go to BAD or MEM on error -- not shown for clarity)\n\n    Process header:\n        HEAD -> (gzip) or (zlib) or (raw)\n        (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT ->\n                  HCRC -> TYPE\n        (zlib) -> DICTID or TYPE\n        DICTID -> DICT -> TYPE\n        (raw) -> TYPEDO\n    Read deflate blocks:\n            TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK\n            STORED -> COPY_ -> COPY -> TYPE\n            TABLE -> LENLENS -> CODELENS -> LEN_\n            LEN_ -> LEN\n    Read deflate codes in fixed or dynamic block:\n                LEN -> LENEXT or LIT or TYPE\n                LENEXT -> DIST -> DISTEXT -> MATCH -> LEN\n                LIT -> LEN\n    Process trailer:\n        CHECK -> LENGTH -> DONE\n */\n\n/* state maintained between inflate() calls.  Approximately 10K bytes. */\nstruct inflate_state {\n    inflate_mode mode;          /* current inflate mode */\n    int last;                   /* true if processing last block */\n    int wrap;                   /* bit 0 true for zlib, bit 1 true for gzip */\n    int havedict;               /* true if dictionary provided */\n    int flags;                  /* gzip header method and flags (0 if zlib) */\n    unsigned dmax;              /* zlib header max distance (INFLATE_STRICT) */\n    unsigned long check;        /* protected copy of check value */\n    unsigned long total;        /* protected copy of output count */\n    gz_headerp head;            /* where to save gzip header information */\n        /* sliding window */\n    unsigned wbits;             /* log base 2 of requested window size */\n    unsigned wsize;             /* window size or zero if not using window */\n    unsigned whave;             /* valid bytes in the window */\n    unsigned wnext;             /* window write index */\n    unsigned char FAR *window;  /* allocated sliding window, if needed */\n        /* bit accumulator */\n    unsigned long hold;         /* input bit accumulator */\n    unsigned bits;              /* number of bits in \"in\" */\n        /* for string and stored block copying */\n    unsigned length;            /* literal or length of data to copy */\n    unsigned offset;            /* distance back to copy string from */\n        /* for table and code decoding */\n    unsigned extra;             /* extra bits needed */\n        /* fixed and dynamic code tables */\n    code const FAR *lencode;    /* starting table for length/literal codes */\n    code const FAR *distcode;   /* starting table for distance codes */\n    unsigned lenbits;           /* index bits for lencode */\n    unsigned distbits;          /* index bits for distcode */\n        /* dynamic table building */\n    unsigned ncode;             /* number of code length code lengths */\n    unsigned nlen;              /* number of length code lengths */\n    unsigned ndist;             /* number of distance code lengths */\n    unsigned have;              /* number of code lengths in lens[] */\n    code FAR *next;             /* next available space in codes[] */\n    unsigned short lens[320];   /* temporary storage for code lengths */\n    unsigned short work[288];   /* work area for code table building */\n    code codes[ENOUGH];         /* space for code tables */\n    int sane;                   /* if false, allow invalid distance too far */\n    int back;                   /* bits back of last unprocessed length/lit */\n    unsigned was;               /* initial length of match */\n};\n"
  },
  {
    "path": "src/engine/external/zlib/inftrees.c",
    "content": "/* inftrees.c -- generate Huffman trees for efficient decoding\n * Copyright (C) 1995-2010 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n#include \"zutil.h\"\n#include \"inftrees.h\"\n\n#define MAXBITS 15\n\nconst char inflate_copyright[] =\n   \" inflate 1.2.5 Copyright 1995-2010 Mark Adler \";\n/*\n  If you use the zlib library in a product, an acknowledgment is welcome\n  in the documentation of your product. If for some reason you cannot\n  include such an acknowledgment, I would appreciate that you keep this\n  copyright string in the executable of your product.\n */\n\n/*\n   Build a set of tables to decode the provided canonical Huffman code.\n   The code lengths are lens[0..codes-1].  The result starts at *table,\n   whose indices are 0..2^bits-1.  work is a writable array of at least\n   lens shorts, which is used as a work area.  type is the type of code\n   to be generated, CODES, LENS, or DISTS.  On return, zero is success,\n   -1 is an invalid code, and +1 means that ENOUGH isn't enough.  table\n   on return points to the next available entry's address.  bits is the\n   requested root table index bits, and on return it is the actual root\n   table index bits.  It will differ if the request is greater than the\n   longest code or if it is less than the shortest code.\n */\nint ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work)\ncodetype type;\nunsigned short FAR *lens;\nunsigned codes;\ncode FAR * FAR *table;\nunsigned FAR *bits;\nunsigned short FAR *work;\n{\n    unsigned len;               /* a code's length in bits */\n    unsigned sym;               /* index of code symbols */\n    unsigned min, max;          /* minimum and maximum code lengths */\n    unsigned root;              /* number of index bits for root table */\n    unsigned curr;              /* number of index bits for current table */\n    unsigned drop;              /* code bits to drop for sub-table */\n    int left;                   /* number of prefix codes available */\n    unsigned used;              /* code entries in table used */\n    unsigned huff;              /* Huffman code */\n    unsigned incr;              /* for incrementing code, index */\n    unsigned fill;              /* index for replicating entries */\n    unsigned low;               /* low bits for current root entry */\n    unsigned mask;              /* mask for low root bits */\n    code here;                  /* table entry for duplication */\n    code FAR *next;             /* next available space in table */\n    const unsigned short FAR *base;     /* base value table to use */\n    const unsigned short FAR *extra;    /* extra bits table to use */\n    int end;                    /* use base and extra for symbol > end */\n    unsigned short count[MAXBITS+1];    /* number of codes of each length */\n    unsigned short offs[MAXBITS+1];     /* offsets in table for each length */\n    static const unsigned short lbase[31] = { /* Length codes 257..285 base */\n        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n        35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};\n    static const unsigned short lext[31] = { /* Length codes 257..285 extra */\n        16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 73, 195};\n    static const unsigned short dbase[32] = { /* Distance codes 0..29 base */\n        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n        257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n        8193, 12289, 16385, 24577, 0, 0};\n    static const unsigned short dext[32] = { /* Distance codes 0..29 extra */\n        16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n        23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n        28, 28, 29, 29, 64, 64};\n\n    /*\n       Process a set of code lengths to create a canonical Huffman code.  The\n       code lengths are lens[0..codes-1].  Each length corresponds to the\n       symbols 0..codes-1.  The Huffman code is generated by first sorting the\n       symbols by length from short to long, and retaining the symbol order\n       for codes with equal lengths.  Then the code starts with all zero bits\n       for the first code of the shortest length, and the codes are integer\n       increments for the same length, and zeros are appended as the length\n       increases.  For the deflate format, these bits are stored backwards\n       from their more natural integer increment ordering, and so when the\n       decoding tables are built in the large loop below, the integer codes\n       are incremented backwards.\n\n       This routine assumes, but does not check, that all of the entries in\n       lens[] are in the range 0..MAXBITS.  The caller must assure this.\n       1..MAXBITS is interpreted as that code length.  zero means that that\n       symbol does not occur in this code.\n\n       The codes are sorted by computing a count of codes for each length,\n       creating from that a table of starting indices for each length in the\n       sorted table, and then entering the symbols in order in the sorted\n       table.  The sorted table is work[], with that space being provided by\n       the caller.\n\n       The length counts are used for other purposes as well, i.e. finding\n       the minimum and maximum length codes, determining if there are any\n       codes at all, checking for a valid set of lengths, and looking ahead\n       at length counts to determine sub-table sizes when building the\n       decoding tables.\n     */\n\n    /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n    for (len = 0; len <= MAXBITS; len++)\n        count[len] = 0;\n    for (sym = 0; sym < codes; sym++)\n        count[lens[sym]]++;\n\n    /* bound code lengths, force root to be within code lengths */\n    root = *bits;\n    for (max = MAXBITS; max >= 1; max--)\n        if (count[max] != 0) break;\n    if (root > max) root = max;\n    if (max == 0) {                     /* no symbols to code at all */\n        here.op = (unsigned char)64;    /* invalid code marker */\n        here.bits = (unsigned char)1;\n        here.val = (unsigned short)0;\n        *(*table)++ = here;             /* make a table to force an error */\n        *(*table)++ = here;\n        *bits = 1;\n        return 0;     /* no symbols, but wait for decoding to report error */\n    }\n    for (min = 1; min < max; min++)\n        if (count[min] != 0) break;\n    if (root < min) root = min;\n\n    /* check for an over-subscribed or incomplete set of lengths */\n    left = 1;\n    for (len = 1; len <= MAXBITS; len++) {\n        left <<= 1;\n        left -= count[len];\n        if (left < 0) return -1;        /* over-subscribed */\n    }\n    if (left > 0 && (type == CODES || max != 1))\n        return -1;                      /* incomplete set */\n\n    /* generate offsets into symbol table for each length for sorting */\n    offs[1] = 0;\n    for (len = 1; len < MAXBITS; len++)\n        offs[len + 1] = offs[len] + count[len];\n\n    /* sort symbols by length, by symbol order within each length */\n    for (sym = 0; sym < codes; sym++)\n        if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;\n\n    /*\n       Create and fill in decoding tables.  In this loop, the table being\n       filled is at next and has curr index bits.  The code being used is huff\n       with length len.  That code is converted to an index by dropping drop\n       bits off of the bottom.  For codes where len is less than drop + curr,\n       those top drop + curr - len bits are incremented through all values to\n       fill the table with replicated entries.\n\n       root is the number of index bits for the root table.  When len exceeds\n       root, sub-tables are created pointed to by the root entry with an index\n       of the low root bits of huff.  This is saved in low to check for when a\n       new sub-table should be started.  drop is zero when the root table is\n       being filled, and drop is root when sub-tables are being filled.\n\n       When a new sub-table is needed, it is necessary to look ahead in the\n       code lengths to determine what size sub-table is needed.  The length\n       counts are used for this, and so count[] is decremented as codes are\n       entered in the tables.\n\n       used keeps track of how many table entries have been allocated from the\n       provided *table space.  It is checked for LENS and DIST tables against\n       the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n       the initial root table size constants.  See the comments in inftrees.h\n       for more information.\n\n       sym increments through all symbols, and the loop terminates when\n       all codes of length max, i.e. all codes, have been processed.  This\n       routine permits incomplete codes, so another loop after this one fills\n       in the rest of the decoding tables with invalid code markers.\n     */\n\n    /* set up for code type */\n    switch (type) {\n    case CODES:\n        base = extra = work;    /* dummy value--not used */\n        end = 19;\n        break;\n    case LENS:\n        base = lbase;\n        base -= 257;\n        extra = lext;\n        extra -= 257;\n        end = 256;\n        break;\n    default:            /* DISTS */\n        base = dbase;\n        extra = dext;\n        end = -1;\n    }\n\n    /* initialize state for loop */\n    huff = 0;                   /* starting code */\n    sym = 0;                    /* starting code symbol */\n    len = min;                  /* starting code length */\n    next = *table;              /* current table to fill in */\n    curr = root;                /* current table index bits */\n    drop = 0;                   /* current bits to drop from code for index */\n    low = (unsigned)(-1);       /* trigger new sub-table when len > root */\n    used = 1U << root;          /* use root table entries */\n    mask = used - 1;            /* mask for comparing low */\n\n    /* check available table space */\n    if ((type == LENS && used >= ENOUGH_LENS) ||\n        (type == DISTS && used >= ENOUGH_DISTS))\n        return 1;\n\n    /* process all codes and make table entries */\n    for (;;) {\n        /* create table entry */\n        here.bits = (unsigned char)(len - drop);\n        if ((int)(work[sym]) < end) {\n            here.op = (unsigned char)0;\n            here.val = work[sym];\n        }\n        else if ((int)(work[sym]) > end) {\n            here.op = (unsigned char)(extra[work[sym]]);\n            here.val = base[work[sym]];\n        }\n        else {\n            here.op = (unsigned char)(32 + 64);         /* end of block */\n            here.val = 0;\n        }\n\n        /* replicate for those indices with low len bits equal to huff */\n        incr = 1U << (len - drop);\n        fill = 1U << curr;\n        min = fill;                 /* save offset to next table */\n        do {\n            fill -= incr;\n            next[(huff >> drop) + fill] = here;\n        } while (fill != 0);\n\n        /* backwards increment the len-bit code huff */\n        incr = 1U << (len - 1);\n        while (huff & incr)\n            incr >>= 1;\n        if (incr != 0) {\n            huff &= incr - 1;\n            huff += incr;\n        }\n        else\n            huff = 0;\n\n        /* go to next symbol, update count, len */\n        sym++;\n        if (--(count[len]) == 0) {\n            if (len == max) break;\n            len = lens[work[sym]];\n        }\n\n        /* create new sub-table if needed */\n        if (len > root && (huff & mask) != low) {\n            /* if first time, transition to sub-tables */\n            if (drop == 0)\n                drop = root;\n\n            /* increment past last table */\n            next += min;            /* here min is 1 << curr */\n\n            /* determine length of next table */\n            curr = len - drop;\n            left = (int)(1 << curr);\n            while (curr + drop < max) {\n                left -= count[curr + drop];\n                if (left <= 0) break;\n                curr++;\n                left <<= 1;\n            }\n\n            /* check for enough space */\n            used += 1U << curr;\n            if ((type == LENS && used >= ENOUGH_LENS) ||\n                (type == DISTS && used >= ENOUGH_DISTS))\n                return 1;\n\n            /* point entry in root table to sub-table */\n            low = huff & mask;\n            (*table)[low].op = (unsigned char)curr;\n            (*table)[low].bits = (unsigned char)root;\n            (*table)[low].val = (unsigned short)(next - *table);\n        }\n    }\n\n    /*\n       Fill in rest of table for incomplete codes.  This loop is similar to the\n       loop above in incrementing huff for table indices.  It is assumed that\n       len is equal to curr + drop, so there is no loop needed to increment\n       through high index bits.  When the current sub-table is filled, the loop\n       drops back to the root table to fill in any remaining entries there.\n     */\n    here.op = (unsigned char)64;                /* invalid code marker */\n    here.bits = (unsigned char)(len - drop);\n    here.val = (unsigned short)0;\n    while (huff != 0) {\n        /* when done with sub-table, drop back to root table */\n        if (drop != 0 && (huff & mask) != low) {\n            drop = 0;\n            len = root;\n            next = *table;\n            here.bits = (unsigned char)len;\n        }\n\n        /* put invalid code marker in table */\n        next[huff >> drop] = here;\n\n        /* backwards increment the len-bit code huff */\n        incr = 1U << (len - 1);\n        while (huff & incr)\n            incr >>= 1;\n        if (incr != 0) {\n            huff &= incr - 1;\n            huff += incr;\n        }\n        else\n            huff = 0;\n    }\n\n    /* set return parameters */\n    *table += used;\n    *bits = root;\n    return 0;\n}\n"
  },
  {
    "path": "src/engine/external/zlib/inftrees.h",
    "content": "/* inftrees.h -- header to use inftrees.c\n * Copyright (C) 1995-2005, 2010 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* WARNING: this file should *not* be used by applications. It is\n   part of the implementation of the compression library and is\n   subject to change. Applications should only use zlib.h.\n */\n\n/* Structure for decoding tables.  Each entry provides either the\n   information needed to do the operation requested by the code that\n   indexed that table entry, or it provides a pointer to another\n   table that indexes more bits of the code.  op indicates whether\n   the entry is a pointer to another table, a literal, a length or\n   distance, an end-of-block, or an invalid code.  For a table\n   pointer, the low four bits of op is the number of index bits of\n   that table.  For a length or distance, the low four bits of op\n   is the number of extra bits to get after the code.  bits is\n   the number of bits in this code or part of the code to drop off\n   of the bit buffer.  val is the actual byte to output in the case\n   of a literal, the base length or distance, or the offset from\n   the current table to the next table.  Each entry is four bytes. */\ntypedef struct {\n    unsigned char op;           /* operation, extra bits, table bits */\n    unsigned char bits;         /* bits in this part of the code */\n    unsigned short val;         /* offset in table or code value */\n} code;\n\n/* op values as set by inflate_table():\n    00000000 - literal\n    0000tttt - table link, tttt != 0 is the number of table index bits\n    0001eeee - length or distance, eeee is the number of extra bits\n    01100000 - end of block\n    01000000 - invalid code\n */\n\n/* Maximum size of the dynamic table.  The maximum number of code structures is\n   1444, which is the sum of 852 for literal/length codes and 592 for distance\n   codes.  These values were found by exhaustive searches using the program\n   examples/enough.c found in the zlib distribtution.  The arguments to that\n   program are the number of symbols, the initial root table size, and the\n   maximum bit length of a code.  \"enough 286 9 15\" for literal/length codes\n   returns returns 852, and \"enough 30 6 15\" for distance codes returns 592.\n   The initial root table size (9 or 6) is found in the fifth argument of the\n   inflate_table() calls in inflate.c and infback.c.  If the root table size is\n   changed, then these maximum sizes would be need to be recalculated and\n   updated. */\n#define ENOUGH_LENS 852\n#define ENOUGH_DISTS 592\n#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS)\n\n/* Type of code to build for inflate_table() */\ntypedef enum {\n    CODES,\n    LENS,\n    DISTS\n} codetype;\n\nint ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens,\n                             unsigned codes, code FAR * FAR *table,\n                             unsigned FAR *bits, unsigned short FAR *work));\n"
  },
  {
    "path": "src/engine/external/zlib/trees.c",
    "content": "/* trees.c -- output deflated data using Huffman coding\n * Copyright (C) 1995-2010 Jean-loup Gailly\n * detect_data_type() function provided freely by Cosmin Truta, 2006\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/*\n *  ALGORITHM\n *\n *      The \"deflation\" process uses several Huffman trees. The more\n *      common source values are represented by shorter bit sequences.\n *\n *      Each code tree is stored in a compressed form which is itself\n * a Huffman encoding of the lengths of all the code strings (in\n * ascending order by source values).  The actual code strings are\n * reconstructed from the lengths in the inflate process, as described\n * in the deflate specification.\n *\n *  REFERENCES\n *\n *      Deutsch, L.P.,\"'Deflate' Compressed Data Format Specification\".\n *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc\n *\n *      Storer, James A.\n *          Data Compression:  Methods and Theory, pp. 49-50.\n *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.\n *\n *      Sedgewick, R.\n *          Algorithms, p290.\n *          Addison-Wesley, 1983. ISBN 0-201-06672-6.\n */\n\n/* @(#) $Id$ */\n\n/* #define GEN_TREES_H */\n\n#include \"deflate.h\"\n\n#ifdef DEBUG\n#  include <ctype.h>\n#endif\n\n/* ===========================================================================\n * Constants\n */\n\n#define MAX_BL_BITS 7\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\n#define END_BLOCK 256\n/* end of block literal code */\n\n#define REP_3_6      16\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\n#define REPZ_3_10    17\n/* repeat a zero length 3-10 times  (3 bits of repeat count) */\n\n#define REPZ_11_138  18\n/* repeat a zero length 11-138 times  (7 bits of repeat count) */\n\nlocal const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */\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};\n\nlocal const int extra_dbits[D_CODES] /* extra bits for each distance code */\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\nlocal const int extra_blbits[BL_CODES]/* extra bits for each bit length code */\n   = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};\n\nlocal const uch bl_order[BL_CODES]\n   = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n#define Buf_size (8 * 2*sizeof(char))\n/* Number of bits used within bi_buf. (bi_buf might be implemented on\n * more than 16 bits on some systems.)\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n#define DIST_CODE_LEN  512 /* see definition of array dist_code below */\n\n#if defined(GEN_TREES_H) || !defined(STDC)\n/* non ANSI compilers may not accept trees.h */\n\nlocal ct_data static_ltree[L_CODES+2];\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nlocal ct_data static_dtree[D_CODES];\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nuch _dist_code[DIST_CODE_LEN];\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nuch _length_code[MAX_MATCH-MIN_MATCH+1];\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nlocal int base_length[LENGTH_CODES];\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nlocal int base_dist[D_CODES];\n/* First normalized distance for each code (0 = distance of 1) */\n\n#else\n#  include \"trees.h\"\n#endif /* GEN_TREES_H */\n\nstruct static_tree_desc_s {\n    const ct_data *static_tree;  /* static tree or NULL */\n    const intf *extra_bits;      /* extra bits for each code or NULL */\n    int     extra_base;          /* base index for extra_bits */\n    int     elems;               /* max number of elements in the tree */\n    int     max_length;          /* max bit length for the codes */\n};\n\nlocal static_tree_desc  static_l_desc =\n{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};\n\nlocal static_tree_desc  static_d_desc =\n{static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};\n\nlocal static_tree_desc  static_bl_desc =\n{(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};\n\n/* ===========================================================================\n * Local (static) routines in this file.\n */\n\nlocal void tr_static_init OF((void));\nlocal void init_block     OF((deflate_state *s));\nlocal void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));\nlocal void gen_bitlen     OF((deflate_state *s, tree_desc *desc));\nlocal void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));\nlocal void build_tree     OF((deflate_state *s, tree_desc *desc));\nlocal void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));\nlocal void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));\nlocal int  build_bl_tree  OF((deflate_state *s));\nlocal void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,\n                              int blcodes));\nlocal void compress_block OF((deflate_state *s, ct_data *ltree,\n                              ct_data *dtree));\nlocal int  detect_data_type OF((deflate_state *s));\nlocal unsigned bi_reverse OF((unsigned value, int length));\nlocal void bi_windup      OF((deflate_state *s));\nlocal void bi_flush       OF((deflate_state *s));\nlocal void copy_block     OF((deflate_state *s, charf *buf, unsigned len,\n                              int header));\n\n#ifdef GEN_TREES_H\nlocal void gen_trees_header OF((void));\n#endif\n\n#ifndef DEBUG\n#  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)\n   /* Send a code of the given tree. c and tree must not have side effects */\n\n#else /* DEBUG */\n#  define send_code(s, c, tree) \\\n     { if (z_verbose>2) fprintf(stderr,\"\\ncd %3d \",(c)); \\\n       send_bits(s, tree[c].Code, tree[c].Len); }\n#endif\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\n#define put_short(s, w) { \\\n    put_byte(s, (uch)((w) & 0xff)); \\\n    put_byte(s, (uch)((ush)(w) >> 8)); \\\n}\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\n#ifdef DEBUG\nlocal void send_bits      OF((deflate_state *s, int value, int length));\n\nlocal void send_bits(s, value, length)\n    deflate_state *s;\n    int value;  /* value to send */\n    int length; /* number of bits */\n{\n    Tracevv((stderr,\" l %2d v %4x \", length, value));\n    Assert(length > 0 && length <= 15, \"invalid length\");\n    s->bits_sent += (ulg)length;\n\n    /* If not enough room in bi_buf, use (valid) bits from bi_buf and\n     * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))\n     * unused bits in value.\n     */\n    if (s->bi_valid > (int)Buf_size - length) {\n        s->bi_buf |= (ush)value << s->bi_valid;\n        put_short(s, s->bi_buf);\n        s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);\n        s->bi_valid += length - Buf_size;\n    } else {\n        s->bi_buf |= (ush)value << s->bi_valid;\n        s->bi_valid += length;\n    }\n}\n#else /* !DEBUG */\n\n#define send_bits(s, value, length) \\\n{ int len = length;\\\n  if (s->bi_valid > (int)Buf_size - len) {\\\n    int val = value;\\\n    s->bi_buf |= (ush)val << s->bi_valid;\\\n    put_short(s, s->bi_buf);\\\n    s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\\\n    s->bi_valid += len - Buf_size;\\\n  } else {\\\n    s->bi_buf |= (ush)(value) << s->bi_valid;\\\n    s->bi_valid += len;\\\n  }\\\n}\n#endif /* DEBUG */\n\n\n/* the arguments must not have side effects */\n\n/* ===========================================================================\n * Initialize the various 'constant' tables.\n */\nlocal void tr_static_init()\n{\n#if defined(GEN_TREES_H) || !defined(STDC)\n    static int static_init_done = 0;\n    int n;        /* iterates over tree elements */\n    int bits;     /* bit counter */\n    int length;   /* length value */\n    int code;     /* code value */\n    int dist;     /* distance index */\n    ush bl_count[MAX_BITS+1];\n    /* number of codes at each bit length for an optimal tree */\n\n    if (static_init_done) return;\n\n    /* For some embedded targets, global variables are not initialized: */\n#ifdef NO_INIT_GLOBAL_POINTERS\n    static_l_desc.static_tree = static_ltree;\n    static_l_desc.extra_bits = extra_lbits;\n    static_d_desc.static_tree = static_dtree;\n    static_d_desc.extra_bits = extra_dbits;\n    static_bl_desc.extra_bits = extra_blbits;\n#endif\n\n    /* Initialize the mapping length (0..255) -> length code (0..28) */\n    length = 0;\n    for (code = 0; code < LENGTH_CODES-1; code++) {\n        base_length[code] = length;\n        for (n = 0; n < (1<<extra_lbits[code]); n++) {\n            _length_code[length++] = (uch)code;\n        }\n    }\n    Assert (length == 256, \"tr_static_init: length != 256\");\n    /* Note that the length 255 (match length 258) can be represented\n     * in two different ways: code 284 + 5 bits or code 285, so we\n     * overwrite length_code[255] to use the best encoding:\n     */\n    _length_code[length-1] = (uch)code;\n\n    /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n    dist = 0;\n    for (code = 0 ; code < 16; code++) {\n        base_dist[code] = dist;\n        for (n = 0; n < (1<<extra_dbits[code]); n++) {\n            _dist_code[dist++] = (uch)code;\n        }\n    }\n    Assert (dist == 256, \"tr_static_init: dist != 256\");\n    dist >>= 7; /* from now on, all distances are divided by 128 */\n    for ( ; code < D_CODES; code++) {\n        base_dist[code] = dist << 7;\n        for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {\n            _dist_code[256 + dist++] = (uch)code;\n        }\n    }\n    Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n    /* Construct the codes of the static literal tree */\n    for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;\n    n = 0;\n    while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;\n    while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;\n    while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;\n    while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;\n    /* Codes 286 and 287 do not exist, but we must include them in the\n     * tree construction to get a canonical Huffman tree (longest code\n     * all ones)\n     */\n    gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);\n\n    /* The static distance tree is trivial: */\n    for (n = 0; n < D_CODES; n++) {\n        static_dtree[n].Len = 5;\n        static_dtree[n].Code = bi_reverse((unsigned)n, 5);\n    }\n    static_init_done = 1;\n\n#  ifdef GEN_TREES_H\n    gen_trees_header();\n#  endif\n#endif /* defined(GEN_TREES_H) || !defined(STDC) */\n}\n\n/* ===========================================================================\n * Genererate the file trees.h describing the static trees.\n */\n#ifdef GEN_TREES_H\n#  ifndef DEBUG\n#    include <stdio.h>\n#  endif\n\n#  define SEPARATOR(i, last, width) \\\n      ((i) == (last)? \"\\n};\\n\\n\" :    \\\n       ((i) % (width) == (width)-1 ? \",\\n\" : \", \"))\n\nvoid gen_trees_header()\n{\n    FILE *header = fopen(\"trees.h\", \"w\");\n    int i;\n\n    Assert (header != NULL, \"Can't open trees.h\");\n    fprintf(header,\n            \"/* header created automatically with -DGEN_TREES_H */\\n\\n\");\n\n    fprintf(header, \"local const ct_data static_ltree[L_CODES+2] = {\\n\");\n    for (i = 0; i < L_CODES+2; i++) {\n        fprintf(header, \"{{%3u},{%3u}}%s\", static_ltree[i].Code,\n                static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));\n    }\n\n    fprintf(header, \"local const ct_data static_dtree[D_CODES] = {\\n\");\n    for (i = 0; i < D_CODES; i++) {\n        fprintf(header, \"{{%2u},{%2u}}%s\", static_dtree[i].Code,\n                static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));\n    }\n\n    fprintf(header, \"const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\\n\");\n    for (i = 0; i < DIST_CODE_LEN; i++) {\n        fprintf(header, \"%2u%s\", _dist_code[i],\n                SEPARATOR(i, DIST_CODE_LEN-1, 20));\n    }\n\n    fprintf(header,\n        \"const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\\n\");\n    for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {\n        fprintf(header, \"%2u%s\", _length_code[i],\n                SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));\n    }\n\n    fprintf(header, \"local const int base_length[LENGTH_CODES] = {\\n\");\n    for (i = 0; i < LENGTH_CODES; i++) {\n        fprintf(header, \"%1u%s\", base_length[i],\n                SEPARATOR(i, LENGTH_CODES-1, 20));\n    }\n\n    fprintf(header, \"local const int base_dist[D_CODES] = {\\n\");\n    for (i = 0; i < D_CODES; i++) {\n        fprintf(header, \"%5u%s\", base_dist[i],\n                SEPARATOR(i, D_CODES-1, 10));\n    }\n\n    fclose(header);\n}\n#endif /* GEN_TREES_H */\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nvoid ZLIB_INTERNAL _tr_init(s)\n    deflate_state *s;\n{\n    tr_static_init();\n\n    s->l_desc.dyn_tree = s->dyn_ltree;\n    s->l_desc.stat_desc = &static_l_desc;\n\n    s->d_desc.dyn_tree = s->dyn_dtree;\n    s->d_desc.stat_desc = &static_d_desc;\n\n    s->bl_desc.dyn_tree = s->bl_tree;\n    s->bl_desc.stat_desc = &static_bl_desc;\n\n    s->bi_buf = 0;\n    s->bi_valid = 0;\n    s->last_eob_len = 8; /* enough lookahead for inflate */\n#ifdef DEBUG\n    s->compressed_len = 0L;\n    s->bits_sent = 0L;\n#endif\n\n    /* Initialize the first block of the first file: */\n    init_block(s);\n}\n\n/* ===========================================================================\n * Initialize a new block.\n */\nlocal void init_block(s)\n    deflate_state *s;\n{\n    int n; /* iterates over tree elements */\n\n    /* Initialize the trees. */\n    for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;\n    for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;\n    for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;\n\n    s->dyn_ltree[END_BLOCK].Freq = 1;\n    s->opt_len = s->static_len = 0L;\n    s->last_lit = s->matches = 0;\n}\n\n#define SMALLEST 1\n/* Index within the heap array of least frequent node in the Huffman tree */\n\n\n/* ===========================================================================\n * Remove the smallest element from the heap and recreate the heap with\n * one less element. Updates heap and heap_len.\n */\n#define pqremove(s, tree, top) \\\n{\\\n    top = s->heap[SMALLEST]; \\\n    s->heap[SMALLEST] = s->heap[s->heap_len--]; \\\n    pqdownheap(s, tree, SMALLEST); \\\n}\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\n#define smaller(tree, n, m, depth) \\\n   (tree[n].Freq < tree[m].Freq || \\\n   (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nlocal void pqdownheap(s, tree, k)\n    deflate_state *s;\n    ct_data *tree;  /* the tree to restore */\n    int k;               /* node to move down */\n{\n    int v = s->heap[k];\n    int j = k << 1;  /* left son of k */\n    while (j <= s->heap_len) {\n        /* Set j to the smallest of the two sons: */\n        if (j < s->heap_len &&\n            smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {\n            j++;\n        }\n        /* Exit if v is smaller than both sons */\n        if (smaller(tree, v, s->heap[j], s->depth)) break;\n\n        /* Exchange v with the smallest son */\n        s->heap[k] = s->heap[j];  k = j;\n\n        /* And continue down the tree, setting j to the left son of k */\n        j <<= 1;\n    }\n    s->heap[k] = v;\n}\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n *    above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n *     array bl_count contains the frequencies for each bit length.\n *     The length opt_len is updated; static_len is also updated if stree is\n *     not null.\n */\nlocal void gen_bitlen(s, desc)\n    deflate_state *s;\n    tree_desc *desc;    /* the tree descriptor */\n{\n    ct_data *tree        = desc->dyn_tree;\n    int max_code         = desc->max_code;\n    const ct_data *stree = desc->stat_desc->static_tree;\n    const intf *extra    = desc->stat_desc->extra_bits;\n    int base             = desc->stat_desc->extra_base;\n    int max_length       = desc->stat_desc->max_length;\n    int h;              /* heap index */\n    int n, m;           /* iterate over the tree elements */\n    int bits;           /* bit length */\n    int xbits;          /* extra bits */\n    ush f;              /* frequency */\n    int overflow = 0;   /* number of elements with bit length too large */\n\n    for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;\n\n    /* In a first pass, compute the optimal bit lengths (which may\n     * overflow in the case of the bit length tree).\n     */\n    tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */\n\n    for (h = s->heap_max+1; h < HEAP_SIZE; h++) {\n        n = s->heap[h];\n        bits = tree[tree[n].Dad].Len + 1;\n        if (bits > max_length) bits = max_length, overflow++;\n        tree[n].Len = (ush)bits;\n        /* We overwrite tree[n].Dad which is no longer needed */\n\n        if (n > max_code) continue; /* not a leaf node */\n\n        s->bl_count[bits]++;\n        xbits = 0;\n        if (n >= base) xbits = extra[n-base];\n        f = tree[n].Freq;\n        s->opt_len += (ulg)f * (bits + xbits);\n        if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);\n    }\n    if (overflow == 0) return;\n\n    Trace((stderr,\"\\nbit length overflow\\n\"));\n    /* This happens for example on obj2 and pic of the Calgary corpus */\n\n    /* Find the first bit length which could increase: */\n    do {\n        bits = max_length-1;\n        while (s->bl_count[bits] == 0) bits--;\n        s->bl_count[bits]--;      /* move one leaf down the tree */\n        s->bl_count[bits+1] += 2; /* move one overflow item as its brother */\n        s->bl_count[max_length]--;\n        /* The brother of the overflow item also moves one step up,\n         * but this does not affect bl_count[max_length]\n         */\n        overflow -= 2;\n    } while (overflow > 0);\n\n    /* Now recompute all bit lengths, scanning in increasing frequency.\n     * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n     * lengths instead of fixing only the wrong ones. This idea is taken\n     * from 'ar' written by Haruhiko Okumura.)\n     */\n    for (bits = max_length; bits != 0; bits--) {\n        n = s->bl_count[bits];\n        while (n != 0) {\n            m = s->heap[--h];\n            if (m > max_code) continue;\n            if ((unsigned) tree[m].Len != (unsigned) bits) {\n                Trace((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n                s->opt_len += ((long)bits - (long)tree[m].Len)\n                              *(long)tree[m].Freq;\n                tree[m].Len = (ush)bits;\n            }\n            n--;\n        }\n    }\n}\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n *     zero code length.\n */\nlocal void gen_codes (tree, max_code, bl_count)\n    ct_data *tree;             /* the tree to decorate */\n    int max_code;              /* largest code with non zero frequency */\n    ushf *bl_count;            /* number of codes at each bit length */\n{\n    ush next_code[MAX_BITS+1]; /* next code value for each bit length */\n    ush code = 0;              /* running code value */\n    int bits;                  /* bit index */\n    int n;                     /* code index */\n\n    /* The distribution counts are first used to generate the code values\n     * without bit reversal.\n     */\n    for (bits = 1; bits <= MAX_BITS; bits++) {\n        next_code[bits] = code = (code + bl_count[bits-1]) << 1;\n    }\n    /* Check that the bit counts in bl_count are consistent. The last code\n     * must be all ones.\n     */\n    Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,\n            \"inconsistent bit counts\");\n    Tracev((stderr,\"\\ngen_codes: max_code %d \", max_code));\n\n    for (n = 0;  n <= max_code; n++) {\n        int len = tree[n].Len;\n        if (len == 0) continue;\n        /* Now reverse the bits */\n        tree[n].Code = bi_reverse(next_code[len]++, len);\n\n        Tracecv(tree != static_ltree, (stderr,\"\\nn %3d %c l %2d c %4x (%x) \",\n             n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));\n    }\n}\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n *     and corresponding code. The length opt_len is updated; static_len is\n *     also updated if stree is not null. The field max_code is set.\n */\nlocal void build_tree(s, desc)\n    deflate_state *s;\n    tree_desc *desc; /* the tree descriptor */\n{\n    ct_data *tree         = desc->dyn_tree;\n    const ct_data *stree  = desc->stat_desc->static_tree;\n    int elems             = desc->stat_desc->elems;\n    int n, m;          /* iterate over heap elements */\n    int max_code = -1; /* largest code with non zero frequency */\n    int node;          /* new node being created */\n\n    /* Construct the initial heap, with least frequent element in\n     * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n     * heap[0] is not used.\n     */\n    s->heap_len = 0, s->heap_max = HEAP_SIZE;\n\n    for (n = 0; n < elems; n++) {\n        if (tree[n].Freq != 0) {\n            s->heap[++(s->heap_len)] = max_code = n;\n            s->depth[n] = 0;\n        } else {\n            tree[n].Len = 0;\n        }\n    }\n\n    /* The pkzip format requires that at least one distance code exists,\n     * and that at least one bit should be sent even if there is only one\n     * possible code. So to avoid special checks later on we force at least\n     * two codes of non zero frequency.\n     */\n    while (s->heap_len < 2) {\n        node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);\n        tree[node].Freq = 1;\n        s->depth[node] = 0;\n        s->opt_len--; if (stree) s->static_len -= stree[node].Len;\n        /* node is 0 or 1 so it does not have extra bits */\n    }\n    desc->max_code = max_code;\n\n    /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n     * establish sub-heaps of increasing lengths:\n     */\n    for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);\n\n    /* Construct the Huffman tree by repeatedly combining the least two\n     * frequent nodes.\n     */\n    node = elems;              /* next internal node of the tree */\n    do {\n        pqremove(s, tree, n);  /* n = node of least frequency */\n        m = s->heap[SMALLEST]; /* m = node of next least frequency */\n\n        s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */\n        s->heap[--(s->heap_max)] = m;\n\n        /* Create a new node father of n and m */\n        tree[node].Freq = tree[n].Freq + tree[m].Freq;\n        s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?\n                                s->depth[n] : s->depth[m]) + 1);\n        tree[n].Dad = tree[m].Dad = (ush)node;\n#ifdef DUMP_BL_TREE\n        if (tree == s->bl_tree) {\n            fprintf(stderr,\"\\nnode %d(%d), sons %d(%d) %d(%d)\",\n                    node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);\n        }\n#endif\n        /* and insert the new node in the heap */\n        s->heap[SMALLEST] = node++;\n        pqdownheap(s, tree, SMALLEST);\n\n    } while (s->heap_len >= 2);\n\n    s->heap[--(s->heap_max)] = s->heap[SMALLEST];\n\n    /* At this point, the fields freq and dad are set. We can now\n     * generate the bit lengths.\n     */\n    gen_bitlen(s, (tree_desc *)desc);\n\n    /* The field len is now set, we can generate the bit codes */\n    gen_codes ((ct_data *)tree, max_code, s->bl_count);\n}\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nlocal void scan_tree (s, tree, max_code)\n    deflate_state *s;\n    ct_data *tree;   /* the tree to be scanned */\n    int max_code;    /* and its largest code of non zero frequency */\n{\n    int n;                     /* iterates over all tree elements */\n    int prevlen = -1;          /* last emitted length */\n    int curlen;                /* length of current code */\n    int nextlen = tree[0].Len; /* length of next code */\n    int count = 0;             /* repeat count of the current code */\n    int max_count = 7;         /* max repeat count */\n    int min_count = 4;         /* min repeat count */\n\n    if (nextlen == 0) max_count = 138, min_count = 3;\n    tree[max_code+1].Len = (ush)0xffff; /* guard */\n\n    for (n = 0; n <= max_code; n++) {\n        curlen = nextlen; nextlen = tree[n+1].Len;\n        if (++count < max_count && curlen == nextlen) {\n            continue;\n        } else if (count < min_count) {\n            s->bl_tree[curlen].Freq += count;\n        } else if (curlen != 0) {\n            if (curlen != prevlen) s->bl_tree[curlen].Freq++;\n            s->bl_tree[REP_3_6].Freq++;\n        } else if (count <= 10) {\n            s->bl_tree[REPZ_3_10].Freq++;\n        } else {\n            s->bl_tree[REPZ_11_138].Freq++;\n        }\n        count = 0; prevlen = curlen;\n        if (nextlen == 0) {\n            max_count = 138, min_count = 3;\n        } else if (curlen == nextlen) {\n            max_count = 6, min_count = 3;\n        } else {\n            max_count = 7, min_count = 4;\n        }\n    }\n}\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nlocal void send_tree (s, tree, max_code)\n    deflate_state *s;\n    ct_data *tree; /* the tree to be scanned */\n    int max_code;       /* and its largest code of non zero frequency */\n{\n    int n;                     /* iterates over all tree elements */\n    int prevlen = -1;          /* last emitted length */\n    int curlen;                /* length of current code */\n    int nextlen = tree[0].Len; /* length of next code */\n    int count = 0;             /* repeat count of the current code */\n    int max_count = 7;         /* max repeat count */\n    int min_count = 4;         /* min repeat count */\n\n    /* tree[max_code+1].Len = -1; */  /* guard already set */\n    if (nextlen == 0) max_count = 138, min_count = 3;\n\n    for (n = 0; n <= max_code; n++) {\n        curlen = nextlen; nextlen = tree[n+1].Len;\n        if (++count < max_count && curlen == nextlen) {\n            continue;\n        } else if (count < min_count) {\n            do { send_code(s, curlen, s->bl_tree); } while (--count != 0);\n\n        } else if (curlen != 0) {\n            if (curlen != prevlen) {\n                send_code(s, curlen, s->bl_tree); count--;\n            }\n            Assert(count >= 3 && count <= 6, \" 3_6?\");\n            send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);\n\n        } else if (count <= 10) {\n            send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);\n\n        } else {\n            send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);\n        }\n        count = 0; prevlen = curlen;\n        if (nextlen == 0) {\n            max_count = 138, min_count = 3;\n        } else if (curlen == nextlen) {\n            max_count = 6, min_count = 3;\n        } else {\n            max_count = 7, min_count = 4;\n        }\n    }\n}\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nlocal int build_bl_tree(s)\n    deflate_state *s;\n{\n    int max_blindex;  /* index of last bit length code of non zero freq */\n\n    /* Determine the bit length frequencies for literal and distance trees */\n    scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);\n    scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);\n\n    /* Build the bit length tree: */\n    build_tree(s, (tree_desc *)(&(s->bl_desc)));\n    /* opt_len now includes the length of the tree representations, except\n     * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n     */\n\n    /* Determine the number of bit length codes to send. The pkzip format\n     * requires that at least 4 bit length codes be sent. (appnote.txt says\n     * 3 but the actual value used is 4.)\n     */\n    for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {\n        if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;\n    }\n    /* Update opt_len to include the bit length tree and counts */\n    s->opt_len += 3*(max_blindex+1) + 5+5+4;\n    Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n            s->opt_len, s->static_len));\n\n    return max_blindex;\n}\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nlocal void send_all_trees(s, lcodes, dcodes, blcodes)\n    deflate_state *s;\n    int lcodes, dcodes, blcodes; /* number of codes for each tree */\n{\n    int rank;                    /* index in bl_order */\n\n    Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n    Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n            \"too many codes\");\n    Tracev((stderr, \"\\nbl counts: \"));\n    send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */\n    send_bits(s, dcodes-1,   5);\n    send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */\n    for (rank = 0; rank < blcodes; rank++) {\n        Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n        send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);\n    }\n    Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n    send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */\n    Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n    send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */\n    Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n}\n\n/* ===========================================================================\n * Send a stored block\n */\nvoid ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)\n    deflate_state *s;\n    charf *buf;       /* input block */\n    ulg stored_len;   /* length of input block */\n    int last;         /* one if this is the last block for a file */\n{\n    send_bits(s, (STORED_BLOCK<<1)+last, 3);    /* send block type */\n#ifdef DEBUG\n    s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;\n    s->compressed_len += (stored_len + 4) << 3;\n#endif\n    copy_block(s, buf, (unsigned)stored_len, 1); /* with header */\n}\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n * The current inflate code requires 9 bits of lookahead. If the\n * last two codes for the previous block (real code plus EOB) were coded\n * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode\n * the last real code. In this case we send two empty static blocks instead\n * of one. (There are no problems if the previous block is stored or fixed.)\n * To simplify the code, we assume the worst case of last real code encoded\n * on one bit only.\n */\nvoid ZLIB_INTERNAL _tr_align(s)\n    deflate_state *s;\n{\n    send_bits(s, STATIC_TREES<<1, 3);\n    send_code(s, END_BLOCK, static_ltree);\n#ifdef DEBUG\n    s->compressed_len += 10L; /* 3 for block type, 7 for EOB */\n#endif\n    bi_flush(s);\n    /* Of the 10 bits for the empty block, we have already sent\n     * (10 - bi_valid) bits. The lookahead for the last real code (before\n     * the EOB of the previous block) was thus at least one plus the length\n     * of the EOB plus what we have just sent of the empty static block.\n     */\n    if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {\n        send_bits(s, STATIC_TREES<<1, 3);\n        send_code(s, END_BLOCK, static_ltree);\n#ifdef DEBUG\n        s->compressed_len += 10L;\n#endif\n        bi_flush(s);\n    }\n    s->last_eob_len = 7;\n}\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and output the encoded block to the zip file.\n */\nvoid ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)\n    deflate_state *s;\n    charf *buf;       /* input block, or NULL if too old */\n    ulg stored_len;   /* length of input block */\n    int last;         /* one if this is the last block for a file */\n{\n    ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n    int max_blindex = 0;  /* index of last bit length code of non zero freq */\n\n    /* Build the Huffman trees unless a stored block is forced */\n    if (s->level > 0) {\n\n        /* Check if the file is binary or text */\n        if (s->strm->data_type == Z_UNKNOWN)\n            s->strm->data_type = detect_data_type(s);\n\n        /* Construct the literal and distance trees */\n        build_tree(s, (tree_desc *)(&(s->l_desc)));\n        Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n                s->static_len));\n\n        build_tree(s, (tree_desc *)(&(s->d_desc)));\n        Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n                s->static_len));\n        /* At this point, opt_len and static_len are the total bit lengths of\n         * the compressed block data, excluding the tree representations.\n         */\n\n        /* Build the bit length tree for the above two trees, and get the index\n         * in bl_order of the last bit length code to send.\n         */\n        max_blindex = build_bl_tree(s);\n\n        /* Determine the best encoding. Compute the block lengths in bytes. */\n        opt_lenb = (s->opt_len+3+7)>>3;\n        static_lenb = (s->static_len+3+7)>>3;\n\n        Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n                opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n                s->last_lit));\n\n        if (static_lenb <= opt_lenb) opt_lenb = static_lenb;\n\n    } else {\n        Assert(buf != (char*)0, \"lost buf\");\n        opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n    }\n\n#ifdef FORCE_STORED\n    if (buf != (char*)0) { /* force stored block */\n#else\n    if (stored_len+4 <= opt_lenb && buf != (char*)0) {\n                       /* 4: two words for the lengths */\n#endif\n        /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n         * Otherwise we can't have processed more than WSIZE input bytes since\n         * the last block flush, because compression would have been\n         * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n         * transform a block into a stored block.\n         */\n        _tr_stored_block(s, buf, stored_len, last);\n\n#ifdef FORCE_STATIC\n    } else if (static_lenb >= 0) { /* force static trees */\n#else\n    } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {\n#endif\n        send_bits(s, (STATIC_TREES<<1)+last, 3);\n        compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);\n#ifdef DEBUG\n        s->compressed_len += 3 + s->static_len;\n#endif\n    } else {\n        send_bits(s, (DYN_TREES<<1)+last, 3);\n        send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,\n                       max_blindex+1);\n        compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);\n#ifdef DEBUG\n        s->compressed_len += 3 + s->opt_len;\n#endif\n    }\n    Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n    /* The above check is made mod 2^32, for files larger than 512 MB\n     * and uLong implemented on 32 bits.\n     */\n    init_block(s);\n\n    if (last) {\n        bi_windup(s);\n#ifdef DEBUG\n        s->compressed_len += 7;  /* align on byte boundary */\n#endif\n    }\n    Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n           s->compressed_len-7*last));\n}\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nint ZLIB_INTERNAL _tr_tally (s, dist, lc)\n    deflate_state *s;\n    unsigned dist;  /* distance of matched string */\n    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */\n{\n    s->d_buf[s->last_lit] = (ush)dist;\n    s->l_buf[s->last_lit++] = (uch)lc;\n    if (dist == 0) {\n        /* lc is the unmatched char */\n        s->dyn_ltree[lc].Freq++;\n    } else {\n        s->matches++;\n        /* Here, lc is the match length - MIN_MATCH */\n        dist--;             /* dist = match distance - 1 */\n        Assert((ush)dist < (ush)MAX_DIST(s) &&\n               (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n               (ush)d_code(dist) < (ush)D_CODES,  \"_tr_tally: bad match\");\n\n        s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;\n        s->dyn_dtree[d_code(dist)].Freq++;\n    }\n\n#ifdef TRUNCATE_BLOCK\n    /* Try to guess if it is profitable to stop the current block here */\n    if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {\n        /* Compute an upper bound for the compressed length */\n        ulg out_length = (ulg)s->last_lit*8L;\n        ulg in_length = (ulg)((long)s->strstart - s->block_start);\n        int dcode;\n        for (dcode = 0; dcode < D_CODES; dcode++) {\n            out_length += (ulg)s->dyn_dtree[dcode].Freq *\n                (5L+extra_dbits[dcode]);\n        }\n        out_length >>= 3;\n        Tracev((stderr,\"\\nlast_lit %u, in %ld, out ~%ld(%ld%%) \",\n               s->last_lit, in_length, out_length,\n               100L - out_length*100L/in_length));\n        if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;\n    }\n#endif\n    return (s->last_lit == s->lit_bufsize-1);\n    /* We avoid equality with lit_bufsize because of wraparound at 64K\n     * on 16 bit machines and because stored blocks are restricted to\n     * 64K-1 bytes.\n     */\n}\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nlocal void compress_block(s, ltree, dtree)\n    deflate_state *s;\n    ct_data *ltree; /* literal tree */\n    ct_data *dtree; /* distance tree */\n{\n    unsigned dist;      /* distance of matched string */\n    int lc;             /* match length or unmatched char (if dist == 0) */\n    unsigned lx = 0;    /* running index in l_buf */\n    unsigned code;      /* the code to send */\n    int extra;          /* number of extra bits to send */\n\n    if (s->last_lit != 0) do {\n        dist = s->d_buf[lx];\n        lc = s->l_buf[lx++];\n        if (dist == 0) {\n            send_code(s, lc, ltree); /* send a literal byte */\n            Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n        } else {\n            /* Here, lc is the match length - MIN_MATCH */\n            code = _length_code[lc];\n            send_code(s, code+LITERALS+1, ltree); /* send the length code */\n            extra = extra_lbits[code];\n            if (extra != 0) {\n                lc -= base_length[code];\n                send_bits(s, lc, extra);       /* send the extra length bits */\n            }\n            dist--; /* dist is now the match distance - 1 */\n            code = d_code(dist);\n            Assert (code < D_CODES, \"bad d_code\");\n\n            send_code(s, code, dtree);       /* send the distance code */\n            extra = extra_dbits[code];\n            if (extra != 0) {\n                dist -= base_dist[code];\n                send_bits(s, dist, extra);   /* send the extra distance bits */\n            }\n        } /* literal or match pair ? */\n\n        /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */\n        Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,\n               \"pendingBuf overflow\");\n\n    } while (lx < s->last_lit);\n\n    send_code(s, END_BLOCK, ltree);\n    s->last_eob_len = ltree[END_BLOCK].Len;\n}\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n *    a) There are no non-portable control characters belonging to the\n *       \"black list\" (0..6, 14..25, 28..31).\n *    b) There is at least one printable character belonging to the\n *       \"white list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n *   \"gray list\" that is ignored in this detection algorithm:\n *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nlocal int detect_data_type(s)\n    deflate_state *s;\n{\n    /* black_mask is the bit mask of black-listed bytes\n     * set bits 0..6, 14..25, and 28..31\n     * 0xf3ffc07f = binary 11110011111111111100000001111111\n     */\n    unsigned long black_mask = 0xf3ffc07fUL;\n    int n;\n\n    /* Check for non-textual (\"black-listed\") bytes. */\n    for (n = 0; n <= 31; n++, black_mask >>= 1)\n        if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0))\n            return Z_BINARY;\n\n    /* Check for textual (\"white-listed\") bytes. */\n    if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0\n            || s->dyn_ltree[13].Freq != 0)\n        return Z_TEXT;\n    for (n = 32; n < LITERALS; n++)\n        if (s->dyn_ltree[n].Freq != 0)\n            return Z_TEXT;\n\n    /* There are no \"black-listed\" or \"white-listed\" bytes:\n     * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n     */\n    return Z_BINARY;\n}\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nlocal unsigned bi_reverse(code, len)\n    unsigned code; /* the value to invert */\n    int len;       /* its bit length */\n{\n    register unsigned res = 0;\n    do {\n        res |= code & 1;\n        code >>= 1, res <<= 1;\n    } while (--len > 0);\n    return res >> 1;\n}\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nlocal void bi_flush(s)\n    deflate_state *s;\n{\n    if (s->bi_valid == 16) {\n        put_short(s, s->bi_buf);\n        s->bi_buf = 0;\n        s->bi_valid = 0;\n    } else if (s->bi_valid >= 8) {\n        put_byte(s, (Byte)s->bi_buf);\n        s->bi_buf >>= 8;\n        s->bi_valid -= 8;\n    }\n}\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nlocal void bi_windup(s)\n    deflate_state *s;\n{\n    if (s->bi_valid > 8) {\n        put_short(s, s->bi_buf);\n    } else if (s->bi_valid > 0) {\n        put_byte(s, (Byte)s->bi_buf);\n    }\n    s->bi_buf = 0;\n    s->bi_valid = 0;\n#ifdef DEBUG\n    s->bits_sent = (s->bits_sent+7) & ~7;\n#endif\n}\n\n/* ===========================================================================\n * Copy a stored block, storing first the length and its\n * one's complement if requested.\n */\nlocal void copy_block(s, buf, len, header)\n    deflate_state *s;\n    charf    *buf;    /* the input data */\n    unsigned len;     /* its length */\n    int      header;  /* true if block header must be written */\n{\n    bi_windup(s);        /* align on byte boundary */\n    s->last_eob_len = 8; /* enough lookahead for inflate */\n\n    if (header) {\n        put_short(s, (ush)len);\n        put_short(s, (ush)~len);\n#ifdef DEBUG\n        s->bits_sent += 2*16;\n#endif\n    }\n#ifdef DEBUG\n    s->bits_sent += (ulg)len<<3;\n#endif\n    while (len--) {\n        put_byte(s, *buf++);\n    }\n}\n"
  },
  {
    "path": "src/engine/external/zlib/trees.h",
    "content": "/* header created automatically with -DGEN_TREES_H */\n\nlocal const ct_data static_ltree[L_CODES+2] = {\n{{ 12},{  8}}, {{140},{  8}}, {{ 76},{  8}}, {{204},{  8}}, {{ 44},{  8}},\n{{172},{  8}}, {{108},{  8}}, {{236},{  8}}, {{ 28},{  8}}, {{156},{  8}},\n{{ 92},{  8}}, {{220},{  8}}, {{ 60},{  8}}, {{188},{  8}}, {{124},{  8}},\n{{252},{  8}}, {{  2},{  8}}, {{130},{  8}}, {{ 66},{  8}}, {{194},{  8}},\n{{ 34},{  8}}, {{162},{  8}}, {{ 98},{  8}}, {{226},{  8}}, {{ 18},{  8}},\n{{146},{  8}}, {{ 82},{  8}}, {{210},{  8}}, {{ 50},{  8}}, {{178},{  8}},\n{{114},{  8}}, {{242},{  8}}, {{ 10},{  8}}, {{138},{  8}}, {{ 74},{  8}},\n{{202},{  8}}, {{ 42},{  8}}, {{170},{  8}}, {{106},{  8}}, {{234},{  8}},\n{{ 26},{  8}}, {{154},{  8}}, {{ 90},{  8}}, {{218},{  8}}, {{ 58},{  8}},\n{{186},{  8}}, {{122},{  8}}, {{250},{  8}}, {{  6},{  8}}, {{134},{  8}},\n{{ 70},{  8}}, {{198},{  8}}, {{ 38},{  8}}, {{166},{  8}}, {{102},{  8}},\n{{230},{  8}}, {{ 22},{  8}}, {{150},{  8}}, {{ 86},{  8}}, {{214},{  8}},\n{{ 54},{  8}}, {{182},{  8}}, {{118},{  8}}, {{246},{  8}}, {{ 14},{  8}},\n{{142},{  8}}, {{ 78},{  8}}, {{206},{  8}}, {{ 46},{  8}}, {{174},{  8}},\n{{110},{  8}}, {{238},{  8}}, {{ 30},{  8}}, {{158},{  8}}, {{ 94},{  8}},\n{{222},{  8}}, {{ 62},{  8}}, {{190},{  8}}, {{126},{  8}}, {{254},{  8}},\n{{  1},{  8}}, {{129},{  8}}, {{ 65},{  8}}, {{193},{  8}}, {{ 33},{  8}},\n{{161},{  8}}, {{ 97},{  8}}, {{225},{  8}}, {{ 17},{  8}}, {{145},{  8}},\n{{ 81},{  8}}, {{209},{  8}}, {{ 49},{  8}}, {{177},{  8}}, {{113},{  8}},\n{{241},{  8}}, {{  9},{  8}}, {{137},{  8}}, {{ 73},{  8}}, {{201},{  8}},\n{{ 41},{  8}}, {{169},{  8}}, {{105},{  8}}, {{233},{  8}}, {{ 25},{  8}},\n{{153},{  8}}, {{ 89},{  8}}, {{217},{  8}}, {{ 57},{  8}}, {{185},{  8}},\n{{121},{  8}}, {{249},{  8}}, {{  5},{  8}}, {{133},{  8}}, {{ 69},{  8}},\n{{197},{  8}}, {{ 37},{  8}}, {{165},{  8}}, {{101},{  8}}, {{229},{  8}},\n{{ 21},{  8}}, {{149},{  8}}, {{ 85},{  8}}, {{213},{  8}}, {{ 53},{  8}},\n{{181},{  8}}, {{117},{  8}}, {{245},{  8}}, {{ 13},{  8}}, {{141},{  8}},\n{{ 77},{  8}}, {{205},{  8}}, {{ 45},{  8}}, {{173},{  8}}, {{109},{  8}},\n{{237},{  8}}, {{ 29},{  8}}, {{157},{  8}}, {{ 93},{  8}}, {{221},{  8}},\n{{ 61},{  8}}, {{189},{  8}}, {{125},{  8}}, {{253},{  8}}, {{ 19},{  9}},\n{{275},{  9}}, {{147},{  9}}, {{403},{  9}}, {{ 83},{  9}}, {{339},{  9}},\n{{211},{  9}}, {{467},{  9}}, {{ 51},{  9}}, {{307},{  9}}, {{179},{  9}},\n{{435},{  9}}, {{115},{  9}}, {{371},{  9}}, {{243},{  9}}, {{499},{  9}},\n{{ 11},{  9}}, {{267},{  9}}, {{139},{  9}}, {{395},{  9}}, {{ 75},{  9}},\n{{331},{  9}}, {{203},{  9}}, {{459},{  9}}, {{ 43},{  9}}, {{299},{  9}},\n{{171},{  9}}, {{427},{  9}}, {{107},{  9}}, {{363},{  9}}, {{235},{  9}},\n{{491},{  9}}, {{ 27},{  9}}, {{283},{  9}}, {{155},{  9}}, {{411},{  9}},\n{{ 91},{  9}}, {{347},{  9}}, {{219},{  9}}, {{475},{  9}}, {{ 59},{  9}},\n{{315},{  9}}, {{187},{  9}}, {{443},{  9}}, {{123},{  9}}, {{379},{  9}},\n{{251},{  9}}, {{507},{  9}}, {{  7},{  9}}, {{263},{  9}}, {{135},{  9}},\n{{391},{  9}}, {{ 71},{  9}}, {{327},{  9}}, {{199},{  9}}, {{455},{  9}},\n{{ 39},{  9}}, {{295},{  9}}, {{167},{  9}}, {{423},{  9}}, {{103},{  9}},\n{{359},{  9}}, {{231},{  9}}, {{487},{  9}}, {{ 23},{  9}}, {{279},{  9}},\n{{151},{  9}}, {{407},{  9}}, {{ 87},{  9}}, {{343},{  9}}, {{215},{  9}},\n{{471},{  9}}, {{ 55},{  9}}, {{311},{  9}}, {{183},{  9}}, {{439},{  9}},\n{{119},{  9}}, {{375},{  9}}, {{247},{  9}}, {{503},{  9}}, {{ 15},{  9}},\n{{271},{  9}}, {{143},{  9}}, {{399},{  9}}, {{ 79},{  9}}, {{335},{  9}},\n{{207},{  9}}, {{463},{  9}}, {{ 47},{  9}}, {{303},{  9}}, {{175},{  9}},\n{{431},{  9}}, {{111},{  9}}, {{367},{  9}}, {{239},{  9}}, {{495},{  9}},\n{{ 31},{  9}}, {{287},{  9}}, {{159},{  9}}, {{415},{  9}}, {{ 95},{  9}},\n{{351},{  9}}, {{223},{  9}}, {{479},{  9}}, {{ 63},{  9}}, {{319},{  9}},\n{{191},{  9}}, {{447},{  9}}, {{127},{  9}}, {{383},{  9}}, {{255},{  9}},\n{{511},{  9}}, {{  0},{  7}}, {{ 64},{  7}}, {{ 32},{  7}}, {{ 96},{  7}},\n{{ 16},{  7}}, {{ 80},{  7}}, {{ 48},{  7}}, {{112},{  7}}, {{  8},{  7}},\n{{ 72},{  7}}, {{ 40},{  7}}, {{104},{  7}}, {{ 24},{  7}}, {{ 88},{  7}},\n{{ 56},{  7}}, {{120},{  7}}, {{  4},{  7}}, {{ 68},{  7}}, {{ 36},{  7}},\n{{100},{  7}}, {{ 20},{  7}}, {{ 84},{  7}}, {{ 52},{  7}}, {{116},{  7}},\n{{  3},{  8}}, {{131},{  8}}, {{ 67},{  8}}, {{195},{  8}}, {{ 35},{  8}},\n{{163},{  8}}, {{ 99},{  8}}, {{227},{  8}}\n};\n\nlocal const ct_data static_dtree[D_CODES] = {\n{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},\n{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},\n{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},\n{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},\n{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},\n{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}\n};\n\nconst uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n 0,  1,  2,  3,  4,  4,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  8,\n 8,  8,  8,  8,  9,  9,  9,  9,  9,  9,  9,  9, 10, 10, 10, 10, 10, 10, 10, 10,\n10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,\n11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,\n12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,\n13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,\n13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,\n14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,\n14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,\n14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,\n15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,\n15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,\n15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,  0,  0, 16, 17,\n18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,\n23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,\n26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,\n27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,\n27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,\n28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,\n28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,\n28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,\n29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,\n29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,\n29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29\n};\n\nconst uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n 0,  1,  2,  3,  4,  5,  6,  7,  8,  8,  9,  9, 10, 10, 11, 11, 12, 12, 12, 12,\n13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,\n17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,\n19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,\n22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,\n23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,\n26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,\n26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,\n27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28\n};\n\nlocal const int base_length[LENGTH_CODES] = {\n0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,\n64, 80, 96, 112, 128, 160, 192, 224, 0\n};\n\nlocal const int base_dist[D_CODES] = {\n    0,     1,     2,     3,     4,     6,     8,    12,    16,    24,\n   32,    48,    64,    96,   128,   192,   256,   384,   512,   768,\n 1024,  1536,  2048,  3072,  4096,  6144,  8192, 12288, 16384, 24576\n};\n\n"
  },
  {
    "path": "src/engine/external/zlib/uncompr.c",
    "content": "/* uncompr.c -- decompress a memory buffer\n * Copyright (C) 1995-2003, 2010 Jean-loup Gailly.\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* @(#) $Id$ */\n\n#define ZLIB_INTERNAL\n#include \"zlib.h\"\n\n/* ===========================================================================\n     Decompresses the source buffer into the destination buffer.  sourceLen is\n   the byte length of the source buffer. Upon entry, destLen is the total\n   size of the destination buffer, which must be large enough to hold the\n   entire uncompressed data. (The size of the uncompressed data must have\n   been saved previously by the compressor and transmitted to the decompressor\n   by some mechanism outside the scope of this compression library.)\n   Upon exit, destLen is the actual size of the compressed buffer.\n\n     uncompress returns Z_OK if success, Z_MEM_ERROR if there was not\n   enough memory, Z_BUF_ERROR if there was not enough room in the output\n   buffer, or Z_DATA_ERROR if the input data was corrupted.\n*/\nint ZEXPORT uncompress (dest, destLen, source, sourceLen)\n    Bytef *dest;\n    uLongf *destLen;\n    const Bytef *source;\n    uLong sourceLen;\n{\n    z_stream stream;\n    int err;\n\n    stream.next_in = (Bytef*)source;\n    stream.avail_in = (uInt)sourceLen;\n    /* Check for source > 64K on 16-bit machine: */\n    if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;\n\n    stream.next_out = dest;\n    stream.avail_out = (uInt)*destLen;\n    if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;\n\n    stream.zalloc = (alloc_func)0;\n    stream.zfree = (free_func)0;\n\n    err = inflateInit(&stream);\n    if (err != Z_OK) return err;\n\n    err = inflate(&stream, Z_FINISH);\n    if (err != Z_STREAM_END) {\n        inflateEnd(&stream);\n        if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0))\n            return Z_DATA_ERROR;\n        return err;\n    }\n    *destLen = stream.total_out;\n\n    err = inflateEnd(&stream);\n    return err;\n}\n"
  },
  {
    "path": "src/engine/external/zlib/zconf.h",
    "content": "/* zconf.h -- configuration of the zlib compression library\n * Copyright (C) 1995-2010 Jean-loup Gailly.\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* @(#) $Id$ */\n\n#ifndef ZCONF_H\n#define ZCONF_H\n\n/*\n * If you *really* need a unique prefix for all types and library functions,\n * compile with -DZ_PREFIX. The \"standard\" zlib should be compiled without it.\n * Even better than compiling with -DZ_PREFIX would be to use configure to set\n * this permanently in zconf.h using \"./configure --zprefix\".\n */\n#ifdef Z_PREFIX     /* may be set to #if 1 by ./configure */\n\n/* all linked symbols */\n#  define _dist_code            z__dist_code\n#  define _length_code          z__length_code\n#  define _tr_align             z__tr_align\n#  define _tr_flush_block       z__tr_flush_block\n#  define _tr_init              z__tr_init\n#  define _tr_stored_block      z__tr_stored_block\n#  define _tr_tally             z__tr_tally\n#  define adler32               z_adler32\n#  define adler32_combine       z_adler32_combine\n#  define adler32_combine64     z_adler32_combine64\n#  define compress              z_compress\n#  define compress2             z_compress2\n#  define compressBound         z_compressBound\n#  define crc32                 z_crc32\n#  define crc32_combine         z_crc32_combine\n#  define crc32_combine64       z_crc32_combine64\n#  define deflate               z_deflate\n#  define deflateBound          z_deflateBound\n#  define deflateCopy           z_deflateCopy\n#  define deflateEnd            z_deflateEnd\n#  define deflateInit2_         z_deflateInit2_\n#  define deflateInit_          z_deflateInit_\n#  define deflateParams         z_deflateParams\n#  define deflatePrime          z_deflatePrime\n#  define deflateReset          z_deflateReset\n#  define deflateSetDictionary  z_deflateSetDictionary\n#  define deflateSetHeader      z_deflateSetHeader\n#  define deflateTune           z_deflateTune\n#  define deflate_copyright     z_deflate_copyright\n#  define get_crc_table         z_get_crc_table\n#  define gz_error              z_gz_error\n#  define gz_intmax             z_gz_intmax\n#  define gz_strwinerror        z_gz_strwinerror\n#  define gzbuffer              z_gzbuffer\n#  define gzclearerr            z_gzclearerr\n#  define gzclose               z_gzclose\n#  define gzclose_r             z_gzclose_r\n#  define gzclose_w             z_gzclose_w\n#  define gzdirect              z_gzdirect\n#  define gzdopen               z_gzdopen\n#  define gzeof                 z_gzeof\n#  define gzerror               z_gzerror\n#  define gzflush               z_gzflush\n#  define gzgetc                z_gzgetc\n#  define gzgets                z_gzgets\n#  define gzoffset              z_gzoffset\n#  define gzoffset64            z_gzoffset64\n#  define gzopen                z_gzopen\n#  define gzopen64              z_gzopen64\n#  define gzprintf              z_gzprintf\n#  define gzputc                z_gzputc\n#  define gzputs                z_gzputs\n#  define gzread                z_gzread\n#  define gzrewind              z_gzrewind\n#  define gzseek                z_gzseek\n#  define gzseek64              z_gzseek64\n#  define gzsetparams           z_gzsetparams\n#  define gztell                z_gztell\n#  define gztell64              z_gztell64\n#  define gzungetc              z_gzungetc\n#  define gzwrite               z_gzwrite\n#  define inflate               z_inflate\n#  define inflateBack           z_inflateBack\n#  define inflateBackEnd        z_inflateBackEnd\n#  define inflateBackInit_      z_inflateBackInit_\n#  define inflateCopy           z_inflateCopy\n#  define inflateEnd            z_inflateEnd\n#  define inflateGetHeader      z_inflateGetHeader\n#  define inflateInit2_         z_inflateInit2_\n#  define inflateInit_          z_inflateInit_\n#  define inflateMark           z_inflateMark\n#  define inflatePrime          z_inflatePrime\n#  define inflateReset          z_inflateReset\n#  define inflateReset2         z_inflateReset2\n#  define inflateSetDictionary  z_inflateSetDictionary\n#  define inflateSync           z_inflateSync\n#  define inflateSyncPoint      z_inflateSyncPoint\n#  define inflateUndermine      z_inflateUndermine\n#  define inflate_copyright     z_inflate_copyright\n#  define inflate_fast          z_inflate_fast\n#  define inflate_table         z_inflate_table\n#  define uncompress            z_uncompress\n#  define zError                z_zError\n#  define zcalloc               z_zcalloc\n#  define zcfree                z_zcfree\n#  define zlibCompileFlags      z_zlibCompileFlags\n#  define zlibVersion           z_zlibVersion\n\n/* all zlib typedefs in zlib.h and zconf.h */\n#  define Byte                  z_Byte\n#  define Bytef                 z_Bytef\n#  define alloc_func            z_alloc_func\n#  define charf                 z_charf\n#  define free_func             z_free_func\n#  define gzFile                z_gzFile\n#  define gz_header             z_gz_header\n#  define gz_headerp            z_gz_headerp\n#  define in_func               z_in_func\n#  define intf                  z_intf\n#  define out_func              z_out_func\n#  define uInt                  z_uInt\n#  define uIntf                 z_uIntf\n#  define uLong                 z_uLong\n#  define uLongf                z_uLongf\n#  define voidp                 z_voidp\n#  define voidpc                z_voidpc\n#  define voidpf                z_voidpf\n\n/* all zlib structs in zlib.h and zconf.h */\n#  define gz_header_s           z_gz_header_s\n#  define internal_state        z_internal_state\n\n#endif\n\n#if defined(__MSDOS__) && !defined(MSDOS)\n#  define MSDOS\n#endif\n#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)\n#  define OS2\n#endif\n#if defined(_WINDOWS) && !defined(WINDOWS)\n#  define WINDOWS\n#endif\n#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)\n#  ifndef WIN32\n#    define WIN32\n#  endif\n#endif\n#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)\n#  if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)\n#    ifndef SYS16BIT\n#      define SYS16BIT\n#    endif\n#  endif\n#endif\n\n/*\n * Compile with -DMAXSEG_64K if the alloc function cannot allocate more\n * than 64k bytes at a time (needed on systems with 16-bit int).\n */\n#ifdef SYS16BIT\n#  define MAXSEG_64K\n#endif\n#ifdef MSDOS\n#  define UNALIGNED_OK\n#endif\n\n#ifdef __STDC_VERSION__\n#  ifndef STDC\n#    define STDC\n#  endif\n#  if __STDC_VERSION__ >= 199901L\n#    ifndef STDC99\n#      define STDC99\n#    endif\n#  endif\n#endif\n#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))\n#  define STDC\n#endif\n#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))\n#  define STDC\n#endif\n#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))\n#  define STDC\n#endif\n#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))\n#  define STDC\n#endif\n\n#if defined(__OS400__) && !defined(STDC)    /* iSeries (formerly AS/400). */\n#  define STDC\n#endif\n\n#ifndef STDC\n#  ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */\n#    define const       /* note: need a more gentle solution here */\n#  endif\n#endif\n\n/* Some Mac compilers merge all .h files incorrectly: */\n#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)\n#  define NO_DUMMY_DECL\n#endif\n\n/* Maximum value for memLevel in deflateInit2 */\n#ifndef MAX_MEM_LEVEL\n#  ifdef MAXSEG_64K\n#    define MAX_MEM_LEVEL 8\n#  else\n#    define MAX_MEM_LEVEL 9\n#  endif\n#endif\n\n/* Maximum value for windowBits in deflateInit2 and inflateInit2.\n * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files\n * created by gzip. (Files created by minigzip can still be extracted by\n * gzip.)\n */\n#ifndef MAX_WBITS\n#  define MAX_WBITS   15 /* 32K LZ77 window */\n#endif\n\n/* The memory requirements for deflate are (in bytes):\n            (1 << (windowBits+2)) +  (1 << (memLevel+9))\n that is: 128K for windowBits=15  +  128K for memLevel = 8  (default values)\n plus a few kilobytes for small objects. For example, if you want to reduce\n the default memory requirements from 256K to 128K, compile with\n     make CFLAGS=\"-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7\"\n Of course this will generally degrade compression (there's no free lunch).\n\n   The memory requirements for inflate are (in bytes) 1 << windowBits\n that is, 32K for windowBits=15 (default value) plus a few kilobytes\n for small objects.\n*/\n\n                        /* Type declarations */\n\n#ifndef OF /* function prototypes */\n#  ifdef STDC\n#    define OF(args)  args\n#  else\n#    define OF(args)  ()\n#  endif\n#endif\n\n/* The following definitions for FAR are needed only for MSDOS mixed\n * model programming (small or medium model with some far allocations).\n * This was tested only with MSC; for other MSDOS compilers you may have\n * to define NO_MEMCPY in zutil.h.  If you don't need the mixed model,\n * just define FAR to be empty.\n */\n#ifdef SYS16BIT\n#  if defined(M_I86SM) || defined(M_I86MM)\n     /* MSC small or medium model */\n#    define SMALL_MEDIUM\n#    ifdef _MSC_VER\n#      define FAR _far\n#    else\n#      define FAR far\n#    endif\n#  endif\n#  if (defined(__SMALL__) || defined(__MEDIUM__))\n     /* Turbo C small or medium model */\n#    define SMALL_MEDIUM\n#    ifdef __BORLANDC__\n#      define FAR _far\n#    else\n#      define FAR far\n#    endif\n#  endif\n#endif\n\n#if defined(WINDOWS) || defined(WIN32)\n   /* If building or using zlib as a DLL, define ZLIB_DLL.\n    * This is not mandatory, but it offers a little performance increase.\n    */\n#  ifdef ZLIB_DLL\n#    if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))\n#      ifdef ZLIB_INTERNAL\n#        define ZEXTERN extern __declspec(dllexport)\n#      else\n#        define ZEXTERN extern __declspec(dllimport)\n#      endif\n#    endif\n#  endif  /* ZLIB_DLL */\n   /* If building or using zlib with the WINAPI/WINAPIV calling convention,\n    * define ZLIB_WINAPI.\n    * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.\n    */\n#  ifdef ZLIB_WINAPI\n#    ifdef FAR\n#      undef FAR\n#    endif\n#    include <windows.h>\n     /* No need for _export, use ZLIB.DEF instead. */\n     /* For complete Windows compatibility, use WINAPI, not __stdcall. */\n#    define ZEXPORT WINAPI\n#    ifdef WIN32\n#      define ZEXPORTVA WINAPIV\n#    else\n#      define ZEXPORTVA FAR CDECL\n#    endif\n#  endif\n#endif\n\n#if defined (__BEOS__)\n#  ifdef ZLIB_DLL\n#    ifdef ZLIB_INTERNAL\n#      define ZEXPORT   __declspec(dllexport)\n#      define ZEXPORTVA __declspec(dllexport)\n#    else\n#      define ZEXPORT   __declspec(dllimport)\n#      define ZEXPORTVA __declspec(dllimport)\n#    endif\n#  endif\n#endif\n\n#ifndef ZEXTERN\n#  define ZEXTERN extern\n#endif\n#ifndef ZEXPORT\n#  define ZEXPORT\n#endif\n#ifndef ZEXPORTVA\n#  define ZEXPORTVA\n#endif\n\n#ifndef FAR\n#  define FAR\n#endif\n\n#if !defined(__MACTYPES__)\ntypedef unsigned char  Byte;  /* 8 bits */\n#endif\ntypedef unsigned int   uInt;  /* 16 bits or more */\ntypedef unsigned long  uLong; /* 32 bits or more */\n\n#ifdef SMALL_MEDIUM\n   /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */\n#  define Bytef Byte FAR\n#else\n   typedef Byte  FAR Bytef;\n#endif\ntypedef char  FAR charf;\ntypedef int   FAR intf;\ntypedef uInt  FAR uIntf;\ntypedef uLong FAR uLongf;\n\n#ifdef STDC\n   typedef void const *voidpc;\n   typedef void FAR   *voidpf;\n   typedef void       *voidp;\n#else\n   typedef Byte const *voidpc;\n   typedef Byte FAR   *voidpf;\n   typedef Byte       *voidp;\n#endif\n\n#ifdef HAVE_UNISTD_H    /* may be set to #if 1 by ./configure */\n#  define Z_HAVE_UNISTD_H\n#endif\n\n#ifdef STDC\n#  include <sys/types.h>    /* for off_t */\n#endif\n\n/* a little trick to accommodate both \"#define _LARGEFILE64_SOURCE\" and\n * \"#define _LARGEFILE64_SOURCE 1\" as requesting 64-bit operations, (even\n * though the former does not conform to the LFS document), but considering\n * both \"#undef _LARGEFILE64_SOURCE\" and \"#define _LARGEFILE64_SOURCE 0\" as\n * equivalently requesting no 64-bit operations\n */\n#if -_LARGEFILE64_SOURCE - -1 == 1\n#  undef _LARGEFILE64_SOURCE\n#endif\n\n#if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE)\n#  include <unistd.h>       /* for SEEK_* and off_t */\n#  ifdef VMS\n#    include <unixio.h>     /* for off_t */\n#  endif\n#  ifndef z_off_t\n#    define z_off_t off_t\n#  endif\n#endif\n\n#ifndef SEEK_SET\n#  define SEEK_SET        0       /* Seek from beginning of file.  */\n#  define SEEK_CUR        1       /* Seek from current position.  */\n#  define SEEK_END        2       /* Set file pointer to EOF plus \"offset\" */\n#endif\n\n#ifndef z_off_t\n#  define z_off_t long\n#endif\n\n#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0\n#  define z_off64_t off64_t\n#else\n#  define z_off64_t z_off_t\n#endif\n\n#if defined(__OS400__)\n#  define NO_vsnprintf\n#endif\n\n#if defined(__MVS__)\n#  define NO_vsnprintf\n#endif\n\n/* MVS linker does not support external names larger than 8 bytes */\n#if defined(__MVS__)\n  #pragma map(deflateInit_,\"DEIN\")\n  #pragma map(deflateInit2_,\"DEIN2\")\n  #pragma map(deflateEnd,\"DEEND\")\n  #pragma map(deflateBound,\"DEBND\")\n  #pragma map(inflateInit_,\"ININ\")\n  #pragma map(inflateInit2_,\"ININ2\")\n  #pragma map(inflateEnd,\"INEND\")\n  #pragma map(inflateSync,\"INSY\")\n  #pragma map(inflateSetDictionary,\"INSEDI\")\n  #pragma map(compressBound,\"CMBND\")\n  #pragma map(inflate_table,\"INTABL\")\n  #pragma map(inflate_fast,\"INFA\")\n  #pragma map(inflate_copyright,\"INCOPY\")\n#endif\n\n#endif /* ZCONF_H */\n"
  },
  {
    "path": "src/engine/external/zlib/zlib.h",
    "content": "/* zlib.h -- interface of the 'zlib' general purpose compression library\n  version 1.2.5, April 19th, 2010\n\n  Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler\n\n  This software is provided 'as-is', without any express or implied\n  warranty.  In no event will the authors be held liable for any damages\n  arising from the use of this software.\n\n  Permission is granted to anyone to use this software for any purpose,\n  including commercial applications, and to alter it and redistribute it\n  freely, subject to the following restrictions:\n\n  1. The origin of this software must not be misrepresented; you must not\n     claim that you wrote the original software. If you use this software\n     in a product, an acknowledgment in the product documentation would be\n     appreciated but is not required.\n  2. Altered source versions must be plainly marked as such, and must not be\n     misrepresented as being the original software.\n  3. This notice may not be removed or altered from any source distribution.\n\n  Jean-loup Gailly        Mark Adler\n  jloup@gzip.org          madler@alumni.caltech.edu\n\n\n  The data format used by the zlib library is described by RFCs (Request for\n  Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt\n  (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).\n*/\n\n#ifndef ZLIB_H\n#define ZLIB_H\n\n#include \"zconf.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#define ZLIB_VERSION \"1.2.5\"\n#define ZLIB_VERNUM 0x1250\n#define ZLIB_VER_MAJOR 1\n#define ZLIB_VER_MINOR 2\n#define ZLIB_VER_REVISION 5\n#define ZLIB_VER_SUBREVISION 0\n\n/*\n    The 'zlib' compression library provides in-memory compression and\n  decompression functions, including integrity checks of the uncompressed data.\n  This version of the library supports only one compression method (deflation)\n  but other algorithms will be added later and will have the same stream\n  interface.\n\n    Compression can be done in a single step if the buffers are large enough,\n  or can be done by repeated calls of the compression function.  In the latter\n  case, the application must provide more input and/or consume the output\n  (providing more output space) before each call.\n\n    The compressed data format used by default by the in-memory functions is\n  the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped\n  around a deflate stream, which is itself documented in RFC 1951.\n\n    The library also supports reading and writing files in gzip (.gz) format\n  with an interface similar to that of stdio using the functions that start\n  with \"gz\".  The gzip format is different from the zlib format.  gzip is a\n  gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.\n\n    This library can optionally read and write gzip streams in memory as well.\n\n    The zlib format was designed to be compact and fast for use in memory\n  and on communications channels.  The gzip format was designed for single-\n  file compression on file systems, has a larger header than zlib to maintain\n  directory information, and uses a different, slower check method than zlib.\n\n    The library does not install any signal handler.  The decoder checks\n  the consistency of the compressed data, so the library should never crash\n  even in case of corrupted input.\n*/\n\ntypedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));\ntypedef void   (*free_func)  OF((voidpf opaque, voidpf address));\n\nstruct internal_state;\n\ntypedef struct z_stream_s {\n    Bytef    *next_in;  /* next input byte */\n    uInt     avail_in;  /* number of bytes available at next_in */\n    uLong    total_in;  /* total nb of input bytes read so far */\n\n    Bytef    *next_out; /* next output byte should be put there */\n    uInt     avail_out; /* remaining free space at next_out */\n    uLong    total_out; /* total nb of bytes output so far */\n\n    char     *msg;      /* last error message, NULL if no error */\n    struct internal_state FAR *state; /* not visible by applications */\n\n    alloc_func zalloc;  /* used to allocate the internal state */\n    free_func  zfree;   /* used to free the internal state */\n    voidpf     opaque;  /* private data object passed to zalloc and zfree */\n\n    int     data_type;  /* best guess about the data type: binary or text */\n    uLong   adler;      /* adler32 value of the uncompressed data */\n    uLong   reserved;   /* reserved for future use */\n} z_stream;\n\ntypedef z_stream FAR *z_streamp;\n\n/*\n     gzip header information passed to and from zlib routines.  See RFC 1952\n  for more details on the meanings of these fields.\n*/\ntypedef struct gz_header_s {\n    int     text;       /* true if compressed data believed to be text */\n    uLong   time;       /* modification time */\n    int     xflags;     /* extra flags (not used when writing a gzip file) */\n    int     os;         /* operating system */\n    Bytef   *extra;     /* pointer to extra field or Z_NULL if none */\n    uInt    extra_len;  /* extra field length (valid if extra != Z_NULL) */\n    uInt    extra_max;  /* space at extra (only when reading header) */\n    Bytef   *name;      /* pointer to zero-terminated file name or Z_NULL */\n    uInt    name_max;   /* space at name (only when reading header) */\n    Bytef   *comment;   /* pointer to zero-terminated comment or Z_NULL */\n    uInt    comm_max;   /* space at comment (only when reading header) */\n    int     hcrc;       /* true if there was or will be a header crc */\n    int     done;       /* true when done reading gzip header (not used\n                           when writing a gzip file) */\n} gz_header;\n\ntypedef gz_header FAR *gz_headerp;\n\n/*\n     The application must update next_in and avail_in when avail_in has dropped\n   to zero.  It must update next_out and avail_out when avail_out has dropped\n   to zero.  The application must initialize zalloc, zfree and opaque before\n   calling the init function.  All other fields are set by the compression\n   library and must not be updated by the application.\n\n     The opaque value provided by the application will be passed as the first\n   parameter for calls of zalloc and zfree.  This can be useful for custom\n   memory management.  The compression library attaches no meaning to the\n   opaque value.\n\n     zalloc must return Z_NULL if there is not enough memory for the object.\n   If zlib is used in a multi-threaded application, zalloc and zfree must be\n   thread safe.\n\n     On 16-bit systems, the functions zalloc and zfree must be able to allocate\n   exactly 65536 bytes, but will not be required to allocate more than this if\n   the symbol MAXSEG_64K is defined (see zconf.h).  WARNING: On MSDOS, pointers\n   returned by zalloc for objects of exactly 65536 bytes *must* have their\n   offset normalized to zero.  The default allocation function provided by this\n   library ensures this (see zutil.c).  To reduce memory requirements and avoid\n   any allocation of 64K objects, at the expense of compression ratio, compile\n   the library with -DMAX_WBITS=14 (see zconf.h).\n\n     The fields total_in and total_out can be used for statistics or progress\n   reports.  After compression, total_in holds the total size of the\n   uncompressed data and may be saved for use in the decompressor (particularly\n   if the decompressor wants to decompress everything in a single step).\n*/\n\n                        /* constants */\n\n#define Z_NO_FLUSH      0\n#define Z_PARTIAL_FLUSH 1\n#define Z_SYNC_FLUSH    2\n#define Z_FULL_FLUSH    3\n#define Z_FINISH        4\n#define Z_BLOCK         5\n#define Z_TREES         6\n/* Allowed flush values; see deflate() and inflate() below for details */\n\n#define Z_OK            0\n#define Z_STREAM_END    1\n#define Z_NEED_DICT     2\n#define Z_ERRNO        (-1)\n#define Z_STREAM_ERROR (-2)\n#define Z_DATA_ERROR   (-3)\n#define Z_MEM_ERROR    (-4)\n#define Z_BUF_ERROR    (-5)\n#define Z_VERSION_ERROR (-6)\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n\n#define Z_NO_COMPRESSION         0\n#define Z_BEST_SPEED             1\n#define Z_BEST_COMPRESSION       9\n#define Z_DEFAULT_COMPRESSION  (-1)\n/* compression levels */\n\n#define Z_FILTERED            1\n#define Z_HUFFMAN_ONLY        2\n#define Z_RLE                 3\n#define Z_FIXED               4\n#define Z_DEFAULT_STRATEGY    0\n/* compression strategy; see deflateInit2() below for details */\n\n#define Z_BINARY   0\n#define Z_TEXT     1\n#define Z_ASCII    Z_TEXT   /* for compatibility with 1.2.2 and earlier */\n#define Z_UNKNOWN  2\n/* Possible values of the data_type field (though see inflate()) */\n\n#define Z_DEFLATED   8\n/* The deflate compression method (the only one supported in this version) */\n\n#define Z_NULL  0  /* for initializing zalloc, zfree, opaque */\n\n#define zlib_version zlibVersion()\n/* for compatibility with versions < 1.0.2 */\n\n\n                        /* basic functions */\n\nZEXTERN const char * ZEXPORT zlibVersion OF((void));\n/* The application can compare zlibVersion and ZLIB_VERSION for consistency.\n   If the first character differs, the library code actually used is not\n   compatible with the zlib.h header file used by the application.  This check\n   is automatically made by deflateInit and inflateInit.\n */\n\n/*\nZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));\n\n     Initializes the internal stream state for compression.  The fields\n   zalloc, zfree and opaque must be initialized before by the caller.  If\n   zalloc and zfree are set to Z_NULL, deflateInit updates them to use default\n   allocation functions.\n\n     The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:\n   1 gives best speed, 9 gives best compression, 0 gives no compression at all\n   (the input data is simply copied a block at a time).  Z_DEFAULT_COMPRESSION\n   requests a default compromise between speed and compression (currently\n   equivalent to level 6).\n\n     deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough\n   memory, Z_STREAM_ERROR if level is not a valid compression level, or\n   Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible\n   with the version assumed by the caller (ZLIB_VERSION).  msg is set to null\n   if there is no error message.  deflateInit does not perform any compression:\n   this will be done by deflate().\n*/\n\n\nZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));\n/*\n    deflate compresses as much data as possible, and stops when the input\n  buffer becomes empty or the output buffer becomes full.  It may introduce\n  some output latency (reading input without producing any output) except when\n  forced to flush.\n\n    The detailed semantics are as follows.  deflate performs one or both of the\n  following actions:\n\n  - Compress more input starting at next_in and update next_in and avail_in\n    accordingly.  If not all input can be processed (because there is not\n    enough room in the output buffer), next_in and avail_in are updated and\n    processing will resume at this point for the next call of deflate().\n\n  - Provide more output starting at next_out and update next_out and avail_out\n    accordingly.  This action is forced if the parameter flush is non zero.\n    Forcing flush frequently degrades the compression ratio, so this parameter\n    should be set only when necessary (in interactive applications).  Some\n    output may be provided even if flush is not set.\n\n    Before the call of deflate(), the application should ensure that at least\n  one of the actions is possible, by providing more input and/or consuming more\n  output, and updating avail_in or avail_out accordingly; avail_out should\n  never be zero before the call.  The application can consume the compressed\n  output when it wants, for example when the output buffer is full (avail_out\n  == 0), or after each call of deflate().  If deflate returns Z_OK and with\n  zero avail_out, it must be called again after making room in the output\n  buffer because there might be more output pending.\n\n    Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to\n  decide how much data to accumulate before producing output, in order to\n  maximize compression.\n\n    If the parameter flush is set to Z_SYNC_FLUSH, all pending output is\n  flushed to the output buffer and the output is aligned on a byte boundary, so\n  that the decompressor can get all input data available so far.  (In\n  particular avail_in is zero after the call if enough output space has been\n  provided before the call.) Flushing may degrade compression for some\n  compression algorithms and so it should be used only when necessary.  This\n  completes the current deflate block and follows it with an empty stored block\n  that is three bits plus filler bits to the next byte, followed by four bytes\n  (00 00 ff ff).\n\n    If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the\n  output buffer, but the output is not aligned to a byte boundary.  All of the\n  input data so far will be available to the decompressor, as for Z_SYNC_FLUSH.\n  This completes the current deflate block and follows it with an empty fixed\n  codes block that is 10 bits long.  This assures that enough bytes are output\n  in order for the decompressor to finish the block before the empty fixed code\n  block.\n\n    If flush is set to Z_BLOCK, a deflate block is completed and emitted, as\n  for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to\n  seven bits of the current block are held to be written as the next byte after\n  the next deflate block is completed.  In this case, the decompressor may not\n  be provided enough bits at this point in order to complete decompression of\n  the data provided so far to the compressor.  It may need to wait for the next\n  block to be emitted.  This is for advanced applications that need to control\n  the emission of deflate blocks.\n\n    If flush is set to Z_FULL_FLUSH, all output is flushed as with\n  Z_SYNC_FLUSH, and the compression state is reset so that decompression can\n  restart from this point if previous compressed data has been damaged or if\n  random access is desired.  Using Z_FULL_FLUSH too often can seriously degrade\n  compression.\n\n    If deflate returns with avail_out == 0, this function must be called again\n  with the same value of the flush parameter and more output space (updated\n  avail_out), until the flush is complete (deflate returns with non-zero\n  avail_out).  In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that\n  avail_out is greater than six to avoid repeated flush markers due to\n  avail_out == 0 on return.\n\n    If the parameter flush is set to Z_FINISH, pending input is processed,\n  pending output is flushed and deflate returns with Z_STREAM_END if there was\n  enough output space; if deflate returns with Z_OK, this function must be\n  called again with Z_FINISH and more output space (updated avail_out) but no\n  more input data, until it returns with Z_STREAM_END or an error.  After\n  deflate has returned Z_STREAM_END, the only possible operations on the stream\n  are deflateReset or deflateEnd.\n\n    Z_FINISH can be used immediately after deflateInit if all the compression\n  is to be done in a single step.  In this case, avail_out must be at least the\n  value returned by deflateBound (see below).  If deflate does not return\n  Z_STREAM_END, then it must be called again as described above.\n\n    deflate() sets strm->adler to the adler32 checksum of all input read\n  so far (that is, total_in bytes).\n\n    deflate() may update strm->data_type if it can make a good guess about\n  the input data type (Z_BINARY or Z_TEXT).  In doubt, the data is considered\n  binary.  This field is only for information purposes and does not affect the\n  compression algorithm in any manner.\n\n    deflate() returns Z_OK if some progress has been made (more input\n  processed or more output produced), Z_STREAM_END if all input has been\n  consumed and all output has been produced (only when flush is set to\n  Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example\n  if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress is possible\n  (for example avail_in or avail_out was zero).  Note that Z_BUF_ERROR is not\n  fatal, and deflate() can be called again with more input and more output\n  space to continue compressing.\n*/\n\n\nZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));\n/*\n     All dynamically allocated data structures for this stream are freed.\n   This function discards any unprocessed input and does not flush any pending\n   output.\n\n     deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the\n   stream state was inconsistent, Z_DATA_ERROR if the stream was freed\n   prematurely (some input or output was discarded).  In the error case, msg\n   may be set but then points to a static string (which must not be\n   deallocated).\n*/\n\n\n/*\nZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));\n\n     Initializes the internal stream state for decompression.  The fields\n   next_in, avail_in, zalloc, zfree and opaque must be initialized before by\n   the caller.  If next_in is not Z_NULL and avail_in is large enough (the\n   exact value depends on the compression method), inflateInit determines the\n   compression method from the zlib header and allocates all data structures\n   accordingly; otherwise the allocation will be deferred to the first call of\n   inflate.  If zalloc and zfree are set to Z_NULL, inflateInit updates them to\n   use default allocation functions.\n\n     inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough\n   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the\n   version assumed by the caller, or Z_STREAM_ERROR if the parameters are\n   invalid, such as a null pointer to the structure.  msg is set to null if\n   there is no error message.  inflateInit does not perform any decompression\n   apart from possibly reading the zlib header if present: actual decompression\n   will be done by inflate().  (So next_in and avail_in may be modified, but\n   next_out and avail_out are unused and unchanged.) The current implementation\n   of inflateInit() does not process any header information -- that is deferred\n   until inflate() is called.\n*/\n\n\nZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));\n/*\n    inflate decompresses as much data as possible, and stops when the input\n  buffer becomes empty or the output buffer becomes full.  It may introduce\n  some output latency (reading input without producing any output) except when\n  forced to flush.\n\n  The detailed semantics are as follows.  inflate performs one or both of the\n  following actions:\n\n  - Decompress more input starting at next_in and update next_in and avail_in\n    accordingly.  If not all input can be processed (because there is not\n    enough room in the output buffer), next_in is updated and processing will\n    resume at this point for the next call of inflate().\n\n  - Provide more output starting at next_out and update next_out and avail_out\n    accordingly.  inflate() provides as much output as possible, until there is\n    no more input data or no more space in the output buffer (see below about\n    the flush parameter).\n\n    Before the call of inflate(), the application should ensure that at least\n  one of the actions is possible, by providing more input and/or consuming more\n  output, and updating the next_* and avail_* values accordingly.  The\n  application can consume the uncompressed output when it wants, for example\n  when the output buffer is full (avail_out == 0), or after each call of\n  inflate().  If inflate returns Z_OK and with zero avail_out, it must be\n  called again after making room in the output buffer because there might be\n  more output pending.\n\n    The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH,\n  Z_BLOCK, or Z_TREES.  Z_SYNC_FLUSH requests that inflate() flush as much\n  output as possible to the output buffer.  Z_BLOCK requests that inflate()\n  stop if and when it gets to the next deflate block boundary.  When decoding\n  the zlib or gzip format, this will cause inflate() to return immediately\n  after the header and before the first block.  When doing a raw inflate,\n  inflate() will go ahead and process the first block, and will return when it\n  gets to the end of that block, or when it runs out of data.\n\n    The Z_BLOCK option assists in appending to or combining deflate streams.\n  Also to assist in this, on return inflate() will set strm->data_type to the\n  number of unused bits in the last byte taken from strm->next_in, plus 64 if\n  inflate() is currently decoding the last block in the deflate stream, plus\n  128 if inflate() returned immediately after decoding an end-of-block code or\n  decoding the complete header up to just before the first byte of the deflate\n  stream.  The end-of-block will not be indicated until all of the uncompressed\n  data from that block has been written to strm->next_out.  The number of\n  unused bits may in general be greater than seven, except when bit 7 of\n  data_type is set, in which case the number of unused bits will be less than\n  eight.  data_type is set as noted here every time inflate() returns for all\n  flush options, and so can be used to determine the amount of currently\n  consumed input in bits.\n\n    The Z_TREES option behaves as Z_BLOCK does, but it also returns when the\n  end of each deflate block header is reached, before any actual data in that\n  block is decoded.  This allows the caller to determine the length of the\n  deflate block header for later use in random access within a deflate block.\n  256 is added to the value of strm->data_type when inflate() returns\n  immediately after reaching the end of the deflate block header.\n\n    inflate() should normally be called until it returns Z_STREAM_END or an\n  error.  However if all decompression is to be performed in a single step (a\n  single call of inflate), the parameter flush should be set to Z_FINISH.  In\n  this case all pending input is processed and all pending output is flushed;\n  avail_out must be large enough to hold all the uncompressed data.  (The size\n  of the uncompressed data may have been saved by the compressor for this\n  purpose.) The next operation on this stream must be inflateEnd to deallocate\n  the decompression state.  The use of Z_FINISH is never required, but can be\n  used to inform inflate that a faster approach may be used for the single\n  inflate() call.\n\n     In this implementation, inflate() always flushes as much output as\n  possible to the output buffer, and always uses the faster approach on the\n  first call.  So the only effect of the flush parameter in this implementation\n  is on the return value of inflate(), as noted below, or when it returns early\n  because Z_BLOCK or Z_TREES is used.\n\n     If a preset dictionary is needed after this call (see inflateSetDictionary\n  below), inflate sets strm->adler to the adler32 checksum of the dictionary\n  chosen by the compressor and returns Z_NEED_DICT; otherwise it sets\n  strm->adler to the adler32 checksum of all output produced so far (that is,\n  total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described\n  below.  At the end of the stream, inflate() checks that its computed adler32\n  checksum is equal to that saved by the compressor and returns Z_STREAM_END\n  only if the checksum is correct.\n\n    inflate() can decompress and check either zlib-wrapped or gzip-wrapped\n  deflate data.  The header type is detected automatically, if requested when\n  initializing with inflateInit2().  Any information contained in the gzip\n  header is not retained, so applications that need that information should\n  instead use raw inflate, see inflateInit2() below, or inflateBack() and\n  perform their own processing of the gzip header and trailer.\n\n    inflate() returns Z_OK if some progress has been made (more input processed\n  or more output produced), Z_STREAM_END if the end of the compressed data has\n  been reached and all uncompressed output has been produced, Z_NEED_DICT if a\n  preset dictionary is needed at this point, Z_DATA_ERROR if the input data was\n  corrupted (input stream not conforming to the zlib format or incorrect check\n  value), Z_STREAM_ERROR if the stream structure was inconsistent (for example\n  next_in or next_out was Z_NULL), Z_MEM_ERROR if there was not enough memory,\n  Z_BUF_ERROR if no progress is possible or if there was not enough room in the\n  output buffer when Z_FINISH is used.  Note that Z_BUF_ERROR is not fatal, and\n  inflate() can be called again with more input and more output space to\n  continue decompressing.  If Z_DATA_ERROR is returned, the application may\n  then call inflateSync() to look for a good compression block if a partial\n  recovery of the data is desired.\n*/\n\n\nZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));\n/*\n     All dynamically allocated data structures for this stream are freed.\n   This function discards any unprocessed input and does not flush any pending\n   output.\n\n     inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state\n   was inconsistent.  In the error case, msg may be set but then points to a\n   static string (which must not be deallocated).\n*/\n\n\n                        /* Advanced functions */\n\n/*\n    The following functions are needed only in some special applications.\n*/\n\n/*\nZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,\n                                     int  level,\n                                     int  method,\n                                     int  windowBits,\n                                     int  memLevel,\n                                     int  strategy));\n\n     This is another version of deflateInit with more compression options.  The\n   fields next_in, zalloc, zfree and opaque must be initialized before by the\n   caller.\n\n     The method parameter is the compression method.  It must be Z_DEFLATED in\n   this version of the library.\n\n     The windowBits parameter is the base two logarithm of the window size\n   (the size of the history buffer).  It should be in the range 8..15 for this\n   version of the library.  Larger values of this parameter result in better\n   compression at the expense of memory usage.  The default value is 15 if\n   deflateInit is used instead.\n\n     windowBits can also be -8..-15 for raw deflate.  In this case, -windowBits\n   determines the window size.  deflate() will then generate raw deflate data\n   with no zlib header or trailer, and will not compute an adler32 check value.\n\n     windowBits can also be greater than 15 for optional gzip encoding.  Add\n   16 to windowBits to write a simple gzip header and trailer around the\n   compressed data instead of a zlib wrapper.  The gzip header will have no\n   file name, no extra data, no comment, no modification time (set to zero), no\n   header crc, and the operating system will be set to 255 (unknown).  If a\n   gzip stream is being written, strm->adler is a crc32 instead of an adler32.\n\n     The memLevel parameter specifies how much memory should be allocated\n   for the internal compression state.  memLevel=1 uses minimum memory but is\n   slow and reduces compression ratio; memLevel=9 uses maximum memory for\n   optimal speed.  The default value is 8.  See zconf.h for total memory usage\n   as a function of windowBits and memLevel.\n\n     The strategy parameter is used to tune the compression algorithm.  Use the\n   value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a\n   filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no\n   string match), or Z_RLE to limit match distances to one (run-length\n   encoding).  Filtered data consists mostly of small values with a somewhat\n   random distribution.  In this case, the compression algorithm is tuned to\n   compress them better.  The effect of Z_FILTERED is to force more Huffman\n   coding and less string matching; it is somewhat intermediate between\n   Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY.  Z_RLE is designed to be almost as\n   fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data.  The\n   strategy parameter only affects the compression ratio but not the\n   correctness of the compressed output even if it is not set appropriately.\n   Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler\n   decoder for special applications.\n\n     deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough\n   memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid\n   method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is\n   incompatible with the version assumed by the caller (ZLIB_VERSION).  msg is\n   set to null if there is no error message.  deflateInit2 does not perform any\n   compression: this will be done by deflate().\n*/\n\nZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,\n                                             const Bytef *dictionary,\n                                             uInt  dictLength));\n/*\n     Initializes the compression dictionary from the given byte sequence\n   without producing any compressed output.  This function must be called\n   immediately after deflateInit, deflateInit2 or deflateReset, before any call\n   of deflate.  The compressor and decompressor must use exactly the same\n   dictionary (see inflateSetDictionary).\n\n     The dictionary should consist of strings (byte sequences) that are likely\n   to be encountered later in the data to be compressed, with the most commonly\n   used strings preferably put towards the end of the dictionary.  Using a\n   dictionary is most useful when the data to be compressed is short and can be\n   predicted with good accuracy; the data can then be compressed better than\n   with the default empty dictionary.\n\n     Depending on the size of the compression data structures selected by\n   deflateInit or deflateInit2, a part of the dictionary may in effect be\n   discarded, for example if the dictionary is larger than the window size\n   provided in deflateInit or deflateInit2.  Thus the strings most likely to be\n   useful should be put at the end of the dictionary, not at the front.  In\n   addition, the current implementation of deflate will use at most the window\n   size minus 262 bytes of the provided dictionary.\n\n     Upon return of this function, strm->adler is set to the adler32 value\n   of the dictionary; the decompressor may later use this value to determine\n   which dictionary has been used by the compressor.  (The adler32 value\n   applies to the whole dictionary even if only a subset of the dictionary is\n   actually used by the compressor.) If a raw deflate was requested, then the\n   adler32 value is not computed and strm->adler is not set.\n\n     deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a\n   parameter is invalid (e.g.  dictionary being Z_NULL) or the stream state is\n   inconsistent (for example if deflate has already been called for this stream\n   or if the compression method is bsort).  deflateSetDictionary does not\n   perform any compression: this will be done by deflate().\n*/\n\nZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,\n                                    z_streamp source));\n/*\n     Sets the destination stream as a complete copy of the source stream.\n\n     This function can be useful when several compression strategies will be\n   tried, for example when there are several ways of pre-processing the input\n   data with a filter.  The streams that will be discarded should then be freed\n   by calling deflateEnd.  Note that deflateCopy duplicates the internal\n   compression state which can be quite large, so this strategy is slow and can\n   consume lots of memory.\n\n     deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not\n   enough memory, Z_STREAM_ERROR if the source stream state was inconsistent\n   (such as zalloc being Z_NULL).  msg is left unchanged in both source and\n   destination.\n*/\n\nZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));\n/*\n     This function is equivalent to deflateEnd followed by deflateInit,\n   but does not free and reallocate all the internal compression state.  The\n   stream will keep the same compression level and any other attributes that\n   may have been set by deflateInit2.\n\n     deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source\n   stream state was inconsistent (such as zalloc or state being Z_NULL).\n*/\n\nZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,\n                                      int level,\n                                      int strategy));\n/*\n     Dynamically update the compression level and compression strategy.  The\n   interpretation of level and strategy is as in deflateInit2.  This can be\n   used to switch between compression and straight copy of the input data, or\n   to switch to a different kind of input data requiring a different strategy.\n   If the compression level is changed, the input available so far is\n   compressed with the old level (and may be flushed); the new level will take\n   effect only at the next call of deflate().\n\n     Before the call of deflateParams, the stream state must be set as for\n   a call of deflate(), since the currently available input may have to be\n   compressed and flushed.  In particular, strm->avail_out must be non-zero.\n\n     deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source\n   stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if\n   strm->avail_out was zero.\n*/\n\nZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,\n                                    int good_length,\n                                    int max_lazy,\n                                    int nice_length,\n                                    int max_chain));\n/*\n     Fine tune deflate's internal compression parameters.  This should only be\n   used by someone who understands the algorithm used by zlib's deflate for\n   searching for the best matching string, and even then only by the most\n   fanatic optimizer trying to squeeze out the last compressed bit for their\n   specific input data.  Read the deflate.c source code for the meaning of the\n   max_lazy, good_length, nice_length, and max_chain parameters.\n\n     deflateTune() can be called after deflateInit() or deflateInit2(), and\n   returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.\n */\n\nZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,\n                                       uLong sourceLen));\n/*\n     deflateBound() returns an upper bound on the compressed size after\n   deflation of sourceLen bytes.  It must be called after deflateInit() or\n   deflateInit2(), and after deflateSetHeader(), if used.  This would be used\n   to allocate an output buffer for deflation in a single pass, and so would be\n   called before deflate().\n*/\n\nZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,\n                                     int bits,\n                                     int value));\n/*\n     deflatePrime() inserts bits in the deflate output stream.  The intent\n   is that this function is used to start off the deflate output with the bits\n   leftover from a previous deflate stream when appending to it.  As such, this\n   function can only be used for raw deflate, and must be used before the first\n   deflate() call after a deflateInit2() or deflateReset().  bits must be less\n   than or equal to 16, and that many of the least significant bits of value\n   will be inserted in the output.\n\n     deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source\n   stream state was inconsistent.\n*/\n\nZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,\n                                         gz_headerp head));\n/*\n     deflateSetHeader() provides gzip header information for when a gzip\n   stream is requested by deflateInit2().  deflateSetHeader() may be called\n   after deflateInit2() or deflateReset() and before the first call of\n   deflate().  The text, time, os, extra field, name, and comment information\n   in the provided gz_header structure are written to the gzip header (xflag is\n   ignored -- the extra flags are set according to the compression level).  The\n   caller must assure that, if not Z_NULL, name and comment are terminated with\n   a zero byte, and that if extra is not Z_NULL, that extra_len bytes are\n   available there.  If hcrc is true, a gzip header crc is included.  Note that\n   the current versions of the command-line version of gzip (up through version\n   1.3.x) do not support header crc's, and will report that it is a \"multi-part\n   gzip file\" and give up.\n\n     If deflateSetHeader is not used, the default gzip header has text false,\n   the time set to zero, and os set to 255, with no extra, name, or comment\n   fields.  The gzip header is returned to the default state by deflateReset().\n\n     deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source\n   stream state was inconsistent.\n*/\n\n/*\nZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,\n                                     int  windowBits));\n\n     This is another version of inflateInit with an extra parameter.  The\n   fields next_in, avail_in, zalloc, zfree and opaque must be initialized\n   before by the caller.\n\n     The windowBits parameter is the base two logarithm of the maximum window\n   size (the size of the history buffer).  It should be in the range 8..15 for\n   this version of the library.  The default value is 15 if inflateInit is used\n   instead.  windowBits must be greater than or equal to the windowBits value\n   provided to deflateInit2() while compressing, or it must be equal to 15 if\n   deflateInit2() was not used.  If a compressed stream with a larger window\n   size is given as input, inflate() will return with the error code\n   Z_DATA_ERROR instead of trying to allocate a larger window.\n\n     windowBits can also be zero to request that inflate use the window size in\n   the zlib header of the compressed stream.\n\n     windowBits can also be -8..-15 for raw inflate.  In this case, -windowBits\n   determines the window size.  inflate() will then process raw deflate data,\n   not looking for a zlib or gzip header, not generating a check value, and not\n   looking for any check values for comparison at the end of the stream.  This\n   is for use with other formats that use the deflate compressed data format\n   such as zip.  Those formats provide their own check values.  If a custom\n   format is developed using the raw deflate format for compressed data, it is\n   recommended that a check value such as an adler32 or a crc32 be applied to\n   the uncompressed data as is done in the zlib, gzip, and zip formats.  For\n   most applications, the zlib format should be used as is.  Note that comments\n   above on the use in deflateInit2() applies to the magnitude of windowBits.\n\n     windowBits can also be greater than 15 for optional gzip decoding.  Add\n   32 to windowBits to enable zlib and gzip decoding with automatic header\n   detection, or add 16 to decode only the gzip format (the zlib format will\n   return a Z_DATA_ERROR).  If a gzip stream is being decoded, strm->adler is a\n   crc32 instead of an adler32.\n\n     inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough\n   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the\n   version assumed by the caller, or Z_STREAM_ERROR if the parameters are\n   invalid, such as a null pointer to the structure.  msg is set to null if\n   there is no error message.  inflateInit2 does not perform any decompression\n   apart from possibly reading the zlib header if present: actual decompression\n   will be done by inflate().  (So next_in and avail_in may be modified, but\n   next_out and avail_out are unused and unchanged.) The current implementation\n   of inflateInit2() does not process any header information -- that is\n   deferred until inflate() is called.\n*/\n\nZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,\n                                             const Bytef *dictionary,\n                                             uInt  dictLength));\n/*\n     Initializes the decompression dictionary from the given uncompressed byte\n   sequence.  This function must be called immediately after a call of inflate,\n   if that call returned Z_NEED_DICT.  The dictionary chosen by the compressor\n   can be determined from the adler32 value returned by that call of inflate.\n   The compressor and decompressor must use exactly the same dictionary (see\n   deflateSetDictionary).  For raw inflate, this function can be called\n   immediately after inflateInit2() or inflateReset() and before any call of\n   inflate() to set the dictionary.  The application must insure that the\n   dictionary that was used for compression is provided.\n\n     inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a\n   parameter is invalid (e.g.  dictionary being Z_NULL) or the stream state is\n   inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the\n   expected one (incorrect adler32 value).  inflateSetDictionary does not\n   perform any decompression: this will be done by subsequent calls of\n   inflate().\n*/\n\nZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));\n/*\n     Skips invalid compressed data until a full flush point (see above the\n   description of deflate with Z_FULL_FLUSH) can be found, or until all\n   available input is skipped.  No output is provided.\n\n     inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR\n   if no more input was provided, Z_DATA_ERROR if no flush point has been\n   found, or Z_STREAM_ERROR if the stream structure was inconsistent.  In the\n   success case, the application may save the current current value of total_in\n   which indicates where valid compressed data was found.  In the error case,\n   the application may repeatedly call inflateSync, providing more input each\n   time, until success or end of the input data.\n*/\n\nZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,\n                                    z_streamp source));\n/*\n     Sets the destination stream as a complete copy of the source stream.\n\n     This function can be useful when randomly accessing a large stream.  The\n   first pass through the stream can periodically record the inflate state,\n   allowing restarting inflate at those points when randomly accessing the\n   stream.\n\n     inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not\n   enough memory, Z_STREAM_ERROR if the source stream state was inconsistent\n   (such as zalloc being Z_NULL).  msg is left unchanged in both source and\n   destination.\n*/\n\nZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));\n/*\n     This function is equivalent to inflateEnd followed by inflateInit,\n   but does not free and reallocate all the internal decompression state.  The\n   stream will keep attributes that may have been set by inflateInit2.\n\n     inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source\n   stream state was inconsistent (such as zalloc or state being Z_NULL).\n*/\n\nZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm,\n                                      int windowBits));\n/*\n     This function is the same as inflateReset, but it also permits changing\n   the wrap and window size requests.  The windowBits parameter is interpreted\n   the same as it is for inflateInit2.\n\n     inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source\n   stream state was inconsistent (such as zalloc or state being Z_NULL), or if\n   the windowBits parameter is invalid.\n*/\n\nZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,\n                                     int bits,\n                                     int value));\n/*\n     This function inserts bits in the inflate input stream.  The intent is\n   that this function is used to start inflating at a bit position in the\n   middle of a byte.  The provided bits will be used before any bytes are used\n   from next_in.  This function should only be used with raw inflate, and\n   should be used before the first inflate() call after inflateInit2() or\n   inflateReset().  bits must be less than or equal to 16, and that many of the\n   least significant bits of value will be inserted in the input.\n\n     If bits is negative, then the input stream bit buffer is emptied.  Then\n   inflatePrime() can be called again to put bits in the buffer.  This is used\n   to clear out bits leftover after feeding inflate a block description prior\n   to feeding inflate codes.\n\n     inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source\n   stream state was inconsistent.\n*/\n\nZEXTERN long ZEXPORT inflateMark OF((z_streamp strm));\n/*\n     This function returns two values, one in the lower 16 bits of the return\n   value, and the other in the remaining upper bits, obtained by shifting the\n   return value down 16 bits.  If the upper value is -1 and the lower value is\n   zero, then inflate() is currently decoding information outside of a block.\n   If the upper value is -1 and the lower value is non-zero, then inflate is in\n   the middle of a stored block, with the lower value equaling the number of\n   bytes from the input remaining to copy.  If the upper value is not -1, then\n   it is the number of bits back from the current bit position in the input of\n   the code (literal or length/distance pair) currently being processed.  In\n   that case the lower value is the number of bytes already emitted for that\n   code.\n\n     A code is being processed if inflate is waiting for more input to complete\n   decoding of the code, or if it has completed decoding but is waiting for\n   more output space to write the literal or match data.\n\n     inflateMark() is used to mark locations in the input data for random\n   access, which may be at bit positions, and to note those cases where the\n   output of a code may span boundaries of random access blocks.  The current\n   location in the input stream can be determined from avail_in and data_type\n   as noted in the description for the Z_BLOCK flush parameter for inflate.\n\n     inflateMark returns the value noted above or -1 << 16 if the provided\n   source stream state was inconsistent.\n*/\n\nZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,\n                                         gz_headerp head));\n/*\n     inflateGetHeader() requests that gzip header information be stored in the\n   provided gz_header structure.  inflateGetHeader() may be called after\n   inflateInit2() or inflateReset(), and before the first call of inflate().\n   As inflate() processes the gzip stream, head->done is zero until the header\n   is completed, at which time head->done is set to one.  If a zlib stream is\n   being decoded, then head->done is set to -1 to indicate that there will be\n   no gzip header information forthcoming.  Note that Z_BLOCK or Z_TREES can be\n   used to force inflate() to return immediately after header processing is\n   complete and before any actual data is decompressed.\n\n     The text, time, xflags, and os fields are filled in with the gzip header\n   contents.  hcrc is set to true if there is a header CRC.  (The header CRC\n   was valid if done is set to one.) If extra is not Z_NULL, then extra_max\n   contains the maximum number of bytes to write to extra.  Once done is true,\n   extra_len contains the actual extra field length, and extra contains the\n   extra field, or that field truncated if extra_max is less than extra_len.\n   If name is not Z_NULL, then up to name_max characters are written there,\n   terminated with a zero unless the length is greater than name_max.  If\n   comment is not Z_NULL, then up to comm_max characters are written there,\n   terminated with a zero unless the length is greater than comm_max.  When any\n   of extra, name, or comment are not Z_NULL and the respective field is not\n   present in the header, then that field is set to Z_NULL to signal its\n   absence.  This allows the use of deflateSetHeader() with the returned\n   structure to duplicate the header.  However if those fields are set to\n   allocated memory, then the application will need to save those pointers\n   elsewhere so that they can be eventually freed.\n\n     If inflateGetHeader is not used, then the header information is simply\n   discarded.  The header is always checked for validity, including the header\n   CRC if present.  inflateReset() will reset the process to discard the header\n   information.  The application would need to call inflateGetHeader() again to\n   retrieve the header from the next gzip stream.\n\n     inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source\n   stream state was inconsistent.\n*/\n\n/*\nZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,\n                                        unsigned char FAR *window));\n\n     Initialize the internal stream state for decompression using inflateBack()\n   calls.  The fields zalloc, zfree and opaque in strm must be initialized\n   before the call.  If zalloc and zfree are Z_NULL, then the default library-\n   derived memory allocation routines are used.  windowBits is the base two\n   logarithm of the window size, in the range 8..15.  window is a caller\n   supplied buffer of that size.  Except for special applications where it is\n   assured that deflate was used with small window sizes, windowBits must be 15\n   and a 32K byte window must be supplied to be able to decompress general\n   deflate streams.\n\n     See inflateBack() for the usage of these routines.\n\n     inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of\n   the paramaters are invalid, Z_MEM_ERROR if the internal state could not be\n   allocated, or Z_VERSION_ERROR if the version of the library does not match\n   the version of the header file.\n*/\n\ntypedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));\ntypedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));\n\nZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,\n                                    in_func in, void FAR *in_desc,\n                                    out_func out, void FAR *out_desc));\n/*\n     inflateBack() does a raw inflate with a single call using a call-back\n   interface for input and output.  This is more efficient than inflate() for\n   file i/o applications in that it avoids copying between the output and the\n   sliding window by simply making the window itself the output buffer.  This\n   function trusts the application to not change the output buffer passed by\n   the output function, at least until inflateBack() returns.\n\n     inflateBackInit() must be called first to allocate the internal state\n   and to initialize the state with the user-provided window buffer.\n   inflateBack() may then be used multiple times to inflate a complete, raw\n   deflate stream with each call.  inflateBackEnd() is then called to free the\n   allocated state.\n\n     A raw deflate stream is one with no zlib or gzip header or trailer.\n   This routine would normally be used in a utility that reads zip or gzip\n   files and writes out uncompressed files.  The utility would decode the\n   header and process the trailer on its own, hence this routine expects only\n   the raw deflate stream to decompress.  This is different from the normal\n   behavior of inflate(), which expects either a zlib or gzip header and\n   trailer around the deflate stream.\n\n     inflateBack() uses two subroutines supplied by the caller that are then\n   called by inflateBack() for input and output.  inflateBack() calls those\n   routines until it reads a complete deflate stream and writes out all of the\n   uncompressed data, or until it encounters an error.  The function's\n   parameters and return types are defined above in the in_func and out_func\n   typedefs.  inflateBack() will call in(in_desc, &buf) which should return the\n   number of bytes of provided input, and a pointer to that input in buf.  If\n   there is no input available, in() must return zero--buf is ignored in that\n   case--and inflateBack() will return a buffer error.  inflateBack() will call\n   out(out_desc, buf, len) to write the uncompressed data buf[0..len-1].  out()\n   should return zero on success, or non-zero on failure.  If out() returns\n   non-zero, inflateBack() will return with an error.  Neither in() nor out()\n   are permitted to change the contents of the window provided to\n   inflateBackInit(), which is also the buffer that out() uses to write from.\n   The length written by out() will be at most the window size.  Any non-zero\n   amount of input may be provided by in().\n\n     For convenience, inflateBack() can be provided input on the first call by\n   setting strm->next_in and strm->avail_in.  If that input is exhausted, then\n   in() will be called.  Therefore strm->next_in must be initialized before\n   calling inflateBack().  If strm->next_in is Z_NULL, then in() will be called\n   immediately for input.  If strm->next_in is not Z_NULL, then strm->avail_in\n   must also be initialized, and then if strm->avail_in is not zero, input will\n   initially be taken from strm->next_in[0 ..  strm->avail_in - 1].\n\n     The in_desc and out_desc parameters of inflateBack() is passed as the\n   first parameter of in() and out() respectively when they are called.  These\n   descriptors can be optionally used to pass any information that the caller-\n   supplied in() and out() functions need to do their job.\n\n     On return, inflateBack() will set strm->next_in and strm->avail_in to\n   pass back any unused input that was provided by the last in() call.  The\n   return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR\n   if in() or out() returned an error, Z_DATA_ERROR if there was a format error\n   in the deflate stream (in which case strm->msg is set to indicate the nature\n   of the error), or Z_STREAM_ERROR if the stream was not properly initialized.\n   In the case of Z_BUF_ERROR, an input or output error can be distinguished\n   using strm->next_in which will be Z_NULL only if in() returned an error.  If\n   strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning\n   non-zero.  (in() will always be called before out(), so strm->next_in is\n   assured to be defined if out() returns non-zero.) Note that inflateBack()\n   cannot return Z_OK.\n*/\n\nZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));\n/*\n     All memory allocated by inflateBackInit() is freed.\n\n     inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream\n   state was inconsistent.\n*/\n\nZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));\n/* Return flags indicating compile-time options.\n\n    Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:\n     1.0: size of uInt\n     3.2: size of uLong\n     5.4: size of voidpf (pointer)\n     7.6: size of z_off_t\n\n    Compiler, assembler, and debug options:\n     8: DEBUG\n     9: ASMV or ASMINF -- use ASM code\n     10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention\n     11: 0 (reserved)\n\n    One-time table building (smaller code, but not thread-safe if true):\n     12: BUILDFIXED -- build static block decoding tables when needed\n     13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed\n     14,15: 0 (reserved)\n\n    Library content (indicates missing functionality):\n     16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking\n                          deflate code when not needed)\n     17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect\n                    and decode gzip streams (to avoid linking crc code)\n     18-19: 0 (reserved)\n\n    Operation variations (changes in library functionality):\n     20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate\n     21: FASTEST -- deflate algorithm with only one, lowest compression level\n     22,23: 0 (reserved)\n\n    The sprintf variant used by gzprintf (zero is best):\n     24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format\n     25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!\n     26: 0 = returns value, 1 = void -- 1 means inferred string length returned\n\n    Remainder:\n     27-31: 0 (reserved)\n */\n\n\n                        /* utility functions */\n\n/*\n     The following utility functions are implemented on top of the basic\n   stream-oriented functions.  To simplify the interface, some default options\n   are assumed (compression level and memory usage, standard memory allocation\n   functions).  The source code of these utility functions can be modified if\n   you need special options.\n*/\n\nZEXTERN int ZEXPORT compress OF((Bytef *dest,   uLongf *destLen,\n                                 const Bytef *source, uLong sourceLen));\n/*\n     Compresses the source buffer into the destination buffer.  sourceLen is\n   the byte length of the source buffer.  Upon entry, destLen is the total size\n   of the destination buffer, which must be at least the value returned by\n   compressBound(sourceLen).  Upon exit, destLen is the actual size of the\n   compressed buffer.\n\n     compress returns Z_OK if success, Z_MEM_ERROR if there was not\n   enough memory, Z_BUF_ERROR if there was not enough room in the output\n   buffer.\n*/\n\nZEXTERN int ZEXPORT compress2 OF((Bytef *dest,   uLongf *destLen,\n                                  const Bytef *source, uLong sourceLen,\n                                  int level));\n/*\n     Compresses the source buffer into the destination buffer.  The level\n   parameter has the same meaning as in deflateInit.  sourceLen is the byte\n   length of the source buffer.  Upon entry, destLen is the total size of the\n   destination buffer, which must be at least the value returned by\n   compressBound(sourceLen).  Upon exit, destLen is the actual size of the\n   compressed buffer.\n\n     compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough\n   memory, Z_BUF_ERROR if there was not enough room in the output buffer,\n   Z_STREAM_ERROR if the level parameter is invalid.\n*/\n\nZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));\n/*\n     compressBound() returns an upper bound on the compressed size after\n   compress() or compress2() on sourceLen bytes.  It would be used before a\n   compress() or compress2() call to allocate the destination buffer.\n*/\n\nZEXTERN int ZEXPORT uncompress OF((Bytef *dest,   uLongf *destLen,\n                                   const Bytef *source, uLong sourceLen));\n/*\n     Decompresses the source buffer into the destination buffer.  sourceLen is\n   the byte length of the source buffer.  Upon entry, destLen is the total size\n   of the destination buffer, which must be large enough to hold the entire\n   uncompressed data.  (The size of the uncompressed data must have been saved\n   previously by the compressor and transmitted to the decompressor by some\n   mechanism outside the scope of this compression library.) Upon exit, destLen\n   is the actual size of the uncompressed buffer.\n\n     uncompress returns Z_OK if success, Z_MEM_ERROR if there was not\n   enough memory, Z_BUF_ERROR if there was not enough room in the output\n   buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.\n*/\n\n\n                        /* gzip file access functions */\n\n/*\n     This library supports reading and writing files in gzip (.gz) format with\n   an interface similar to that of stdio, using the functions that start with\n   \"gz\".  The gzip format is different from the zlib format.  gzip is a gzip\n   wrapper, documented in RFC 1952, wrapped around a deflate stream.\n*/\n\ntypedef voidp gzFile;       /* opaque gzip file descriptor */\n\n/*\nZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));\n\n     Opens a gzip (.gz) file for reading or writing.  The mode parameter is as\n   in fopen (\"rb\" or \"wb\") but can also include a compression level (\"wb9\") or\n   a strategy: 'f' for filtered data as in \"wb6f\", 'h' for Huffman-only\n   compression as in \"wb1h\", 'R' for run-length encoding as in \"wb1R\", or 'F'\n   for fixed code compression as in \"wb9F\".  (See the description of\n   deflateInit2 for more information about the strategy parameter.) Also \"a\"\n   can be used instead of \"w\" to request that the gzip stream that will be\n   written be appended to the file.  \"+\" will result in an error, since reading\n   and writing to the same gzip file is not supported.\n\n     gzopen can be used to read a file which is not in gzip format; in this\n   case gzread will directly read from the file without decompression.\n\n     gzopen returns NULL if the file could not be opened, if there was\n   insufficient memory to allocate the gzFile state, or if an invalid mode was\n   specified (an 'r', 'w', or 'a' was not provided, or '+' was provided).\n   errno can be checked to determine if the reason gzopen failed was that the\n   file could not be opened.\n*/\n\nZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));\n/*\n     gzdopen associates a gzFile with the file descriptor fd.  File descriptors\n   are obtained from calls like open, dup, creat, pipe or fileno (if the file\n   has been previously opened with fopen).  The mode parameter is as in gzopen.\n\n     The next call of gzclose on the returned gzFile will also close the file\n   descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor\n   fd.  If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd,\n   mode);.  The duplicated descriptor should be saved to avoid a leak, since\n   gzdopen does not close fd if it fails.\n\n     gzdopen returns NULL if there was insufficient memory to allocate the\n   gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not\n   provided, or '+' was provided), or if fd is -1.  The file descriptor is not\n   used until the next gz* read, write, seek, or close operation, so gzdopen\n   will not detect if fd is invalid (unless fd is -1).\n*/\n\nZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size));\n/*\n     Set the internal buffer size used by this library's functions.  The\n   default buffer size is 8192 bytes.  This function must be called after\n   gzopen() or gzdopen(), and before any other calls that read or write the\n   file.  The buffer memory allocation is always deferred to the first read or\n   write.  Two buffers are allocated, either both of the specified size when\n   writing, or one of the specified size and the other twice that size when\n   reading.  A larger buffer size of, for example, 64K or 128K bytes will\n   noticeably increase the speed of decompression (reading).\n\n     The new buffer size also affects the maximum length for gzprintf().\n\n     gzbuffer() returns 0 on success, or -1 on failure, such as being called\n   too late.\n*/\n\nZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));\n/*\n     Dynamically update the compression level or strategy.  See the description\n   of deflateInit2 for the meaning of these parameters.\n\n     gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not\n   opened for writing.\n*/\n\nZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));\n/*\n     Reads the given number of uncompressed bytes from the compressed file.  If\n   the input file was not in gzip format, gzread copies the given number of\n   bytes into the buffer.\n\n     After reaching the end of a gzip stream in the input, gzread will continue\n   to read, looking for another gzip stream, or failing that, reading the rest\n   of the input file directly without decompression.  The entire input file\n   will be read if gzread is called until it returns less than the requested\n   len.\n\n     gzread returns the number of uncompressed bytes actually read, less than\n   len for end of file, or -1 for error.\n*/\n\nZEXTERN int ZEXPORT gzwrite OF((gzFile file,\n                                voidpc buf, unsigned len));\n/*\n     Writes the given number of uncompressed bytes into the compressed file.\n   gzwrite returns the number of uncompressed bytes written or 0 in case of\n   error.\n*/\n\nZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));\n/*\n     Converts, formats, and writes the arguments to the compressed file under\n   control of the format string, as in fprintf.  gzprintf returns the number of\n   uncompressed bytes actually written, or 0 in case of error.  The number of\n   uncompressed bytes written is limited to 8191, or one less than the buffer\n   size given to gzbuffer().  The caller should assure that this limit is not\n   exceeded.  If it is exceeded, then gzprintf() will return an error (0) with\n   nothing written.  In this case, there may also be a buffer overflow with\n   unpredictable consequences, which is possible only if zlib was compiled with\n   the insecure functions sprintf() or vsprintf() because the secure snprintf()\n   or vsnprintf() functions were not available.  This can be determined using\n   zlibCompileFlags().\n*/\n\nZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));\n/*\n     Writes the given null-terminated string to the compressed file, excluding\n   the terminating null character.\n\n     gzputs returns the number of characters written, or -1 in case of error.\n*/\n\nZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));\n/*\n     Reads bytes from the compressed file until len-1 characters are read, or a\n   newline character is read and transferred to buf, or an end-of-file\n   condition is encountered.  If any characters are read or if len == 1, the\n   string is terminated with a null character.  If no characters are read due\n   to an end-of-file or len < 1, then the buffer is left untouched.\n\n     gzgets returns buf which is a null-terminated string, or it returns NULL\n   for end-of-file or in case of error.  If there was an error, the contents at\n   buf are indeterminate.\n*/\n\nZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));\n/*\n     Writes c, converted to an unsigned char, into the compressed file.  gzputc\n   returns the value that was written, or -1 in case of error.\n*/\n\nZEXTERN int ZEXPORT gzgetc OF((gzFile file));\n/*\n     Reads one byte from the compressed file.  gzgetc returns this byte or -1\n   in case of end of file or error.\n*/\n\nZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));\n/*\n     Push one character back onto the stream to be read as the first character\n   on the next read.  At least one character of push-back is allowed.\n   gzungetc() returns the character pushed, or -1 on failure.  gzungetc() will\n   fail if c is -1, and may fail if a character has been pushed but not read\n   yet.  If gzungetc is used immediately after gzopen or gzdopen, at least the\n   output buffer size of pushed characters is allowed.  (See gzbuffer above.)\n   The pushed character will be discarded if the stream is repositioned with\n   gzseek() or gzrewind().\n*/\n\nZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));\n/*\n     Flushes all pending output into the compressed file.  The parameter flush\n   is as in the deflate() function.  The return value is the zlib error number\n   (see function gzerror below).  gzflush is only permitted when writing.\n\n     If the flush parameter is Z_FINISH, the remaining data is written and the\n   gzip stream is completed in the output.  If gzwrite() is called again, a new\n   gzip stream will be started in the output.  gzread() is able to read such\n   concatented gzip streams.\n\n     gzflush should be called only when strictly necessary because it will\n   degrade compression if called too often.\n*/\n\n/*\nZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,\n                                   z_off_t offset, int whence));\n\n     Sets the starting position for the next gzread or gzwrite on the given\n   compressed file.  The offset represents a number of bytes in the\n   uncompressed data stream.  The whence parameter is defined as in lseek(2);\n   the value SEEK_END is not supported.\n\n     If the file is opened for reading, this function is emulated but can be\n   extremely slow.  If the file is opened for writing, only forward seeks are\n   supported; gzseek then compresses a sequence of zeroes up to the new\n   starting position.\n\n     gzseek returns the resulting offset location as measured in bytes from\n   the beginning of the uncompressed stream, or -1 in case of error, in\n   particular if the file is opened for writing and the new starting position\n   would be before the current position.\n*/\n\nZEXTERN int ZEXPORT    gzrewind OF((gzFile file));\n/*\n     Rewinds the given file. This function is supported only for reading.\n\n     gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)\n*/\n\n/*\nZEXTERN z_off_t ZEXPORT    gztell OF((gzFile file));\n\n     Returns the starting position for the next gzread or gzwrite on the given\n   compressed file.  This position represents a number of bytes in the\n   uncompressed data stream, and is zero when starting, even if appending or\n   reading a gzip stream from the middle of a file using gzdopen().\n\n     gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)\n*/\n\n/*\nZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file));\n\n     Returns the current offset in the file being read or written.  This offset\n   includes the count of bytes that precede the gzip stream, for example when\n   appending or when using gzdopen() for reading.  When reading, the offset\n   does not include as yet unused buffered input.  This information can be used\n   for a progress indicator.  On error, gzoffset() returns -1.\n*/\n\nZEXTERN int ZEXPORT gzeof OF((gzFile file));\n/*\n     Returns true (1) if the end-of-file indicator has been set while reading,\n   false (0) otherwise.  Note that the end-of-file indicator is set only if the\n   read tried to go past the end of the input, but came up short.  Therefore,\n   just like feof(), gzeof() may return false even if there is no more data to\n   read, in the event that the last read request was for the exact number of\n   bytes remaining in the input file.  This will happen if the input file size\n   is an exact multiple of the buffer size.\n\n     If gzeof() returns true, then the read functions will return no more data,\n   unless the end-of-file indicator is reset by gzclearerr() and the input file\n   has grown since the previous end of file was detected.\n*/\n\nZEXTERN int ZEXPORT gzdirect OF((gzFile file));\n/*\n     Returns true (1) if file is being copied directly while reading, or false\n   (0) if file is a gzip stream being decompressed.  This state can change from\n   false to true while reading the input file if the end of a gzip stream is\n   reached, but is followed by data that is not another gzip stream.\n\n     If the input file is empty, gzdirect() will return true, since the input\n   does not contain a gzip stream.\n\n     If gzdirect() is used immediately after gzopen() or gzdopen() it will\n   cause buffers to be allocated to allow reading the file to determine if it\n   is a gzip file.  Therefore if gzbuffer() is used, it should be called before\n   gzdirect().\n*/\n\nZEXTERN int ZEXPORT    gzclose OF((gzFile file));\n/*\n     Flushes all pending output if necessary, closes the compressed file and\n   deallocates the (de)compression state.  Note that once file is closed, you\n   cannot call gzerror with file, since its structures have been deallocated.\n   gzclose must not be called more than once on the same file, just as free\n   must not be called more than once on the same allocation.\n\n     gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a\n   file operation error, or Z_OK on success.\n*/\n\nZEXTERN int ZEXPORT gzclose_r OF((gzFile file));\nZEXTERN int ZEXPORT gzclose_w OF((gzFile file));\n/*\n     Same as gzclose(), but gzclose_r() is only for use when reading, and\n   gzclose_w() is only for use when writing or appending.  The advantage to\n   using these instead of gzclose() is that they avoid linking in zlib\n   compression or decompression code that is not used when only reading or only\n   writing respectively.  If gzclose() is used, then both compression and\n   decompression code will be included the application when linking to a static\n   zlib library.\n*/\n\nZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));\n/*\n     Returns the error message for the last error which occurred on the given\n   compressed file.  errnum is set to zlib error number.  If an error occurred\n   in the file system and not in the compression library, errnum is set to\n   Z_ERRNO and the application may consult errno to get the exact error code.\n\n     The application must not modify the returned string.  Future calls to\n   this function may invalidate the previously returned string.  If file is\n   closed, then the string previously returned by gzerror will no longer be\n   available.\n\n     gzerror() should be used to distinguish errors from end-of-file for those\n   functions above that do not distinguish those cases in their return values.\n*/\n\nZEXTERN void ZEXPORT gzclearerr OF((gzFile file));\n/*\n     Clears the error and end-of-file flags for file.  This is analogous to the\n   clearerr() function in stdio.  This is useful for continuing to read a gzip\n   file that is being written concurrently.\n*/\n\n\n                        /* checksum functions */\n\n/*\n     These functions are not related to compression but are exported\n   anyway because they might be useful in applications using the compression\n   library.\n*/\n\nZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));\n/*\n     Update a running Adler-32 checksum with the bytes buf[0..len-1] and\n   return the updated checksum.  If buf is Z_NULL, this function returns the\n   required initial value for the checksum.\n\n     An Adler-32 checksum is almost as reliable as a CRC32 but can be computed\n   much faster.\n\n   Usage example:\n\n     uLong adler = adler32(0L, Z_NULL, 0);\n\n     while (read_buffer(buffer, length) != EOF) {\n       adler = adler32(adler, buffer, length);\n     }\n     if (adler != original_adler) error();\n*/\n\n/*\nZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,\n                                          z_off_t len2));\n\n     Combine two Adler-32 checksums into one.  For two sequences of bytes, seq1\n   and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for\n   each, adler1 and adler2.  adler32_combine() returns the Adler-32 checksum of\n   seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.\n*/\n\nZEXTERN uLong ZEXPORT crc32   OF((uLong crc, const Bytef *buf, uInt len));\n/*\n     Update a running CRC-32 with the bytes buf[0..len-1] and return the\n   updated CRC-32.  If buf is Z_NULL, this function returns the required\n   initial value for the for the crc.  Pre- and post-conditioning (one's\n   complement) is performed within this function so it shouldn't be done by the\n   application.\n\n   Usage example:\n\n     uLong crc = crc32(0L, Z_NULL, 0);\n\n     while (read_buffer(buffer, length) != EOF) {\n       crc = crc32(crc, buffer, length);\n     }\n     if (crc != original_crc) error();\n*/\n\n/*\nZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));\n\n     Combine two CRC-32 check values into one.  For two sequences of bytes,\n   seq1 and seq2 with lengths len1 and len2, CRC-32 check values were\n   calculated for each, crc1 and crc2.  crc32_combine() returns the CRC-32\n   check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and\n   len2.\n*/\n\n\n                        /* various hacks, don't look :) */\n\n/* deflateInit and inflateInit are macros to allow checking the zlib version\n * and the compiler's view of z_stream:\n */\nZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,\n                                     const char *version, int stream_size));\nZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,\n                                     const char *version, int stream_size));\nZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int  level, int  method,\n                                      int windowBits, int memLevel,\n                                      int strategy, const char *version,\n                                      int stream_size));\nZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int  windowBits,\n                                      const char *version, int stream_size));\nZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,\n                                         unsigned char FAR *window,\n                                         const char *version,\n                                         int stream_size));\n#define deflateInit(strm, level) \\\n        deflateInit_((strm), (level),       ZLIB_VERSION, sizeof(z_stream))\n#define inflateInit(strm) \\\n        inflateInit_((strm),                ZLIB_VERSION, sizeof(z_stream))\n#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \\\n        deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\\\n                      (strategy),           ZLIB_VERSION, sizeof(z_stream))\n#define inflateInit2(strm, windowBits) \\\n        inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))\n#define inflateBackInit(strm, windowBits, window) \\\n        inflateBackInit_((strm), (windowBits), (window), \\\n                                            ZLIB_VERSION, sizeof(z_stream))\n\n/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or\n * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if\n * both are true, the application gets the *64 functions, and the regular\n * functions are changed to 64 bits) -- in case these are set on systems\n * without large file support, _LFS64_LARGEFILE must also be true\n */\n#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0\n   ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));\n   ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\n   ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile));\n   ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile));\n   ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t));\n   ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t));\n#endif\n\n#if !defined(ZLIB_INTERNAL) && _FILE_OFFSET_BITS-0 == 64 && _LFS64_LARGEFILE-0\n#  define gzopen gzopen64\n#  define gzseek gzseek64\n#  define gztell gztell64\n#  define gzoffset gzoffset64\n#  define adler32_combine adler32_combine64\n#  define crc32_combine crc32_combine64\n#  ifdef _LARGEFILE64_SOURCE\n     ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));\n     ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int));\n     ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile));\n     ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile));\n     ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));\n     ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));\n#  endif\n#else\n   ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *));\n   ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int));\n   ZEXTERN z_off_t ZEXPORT gztell OF((gzFile));\n   ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile));\n   ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t));\n   ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t));\n#endif\n\n/* hack for buggy compilers */\n#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)\n    struct internal_state {int dummy;};\n#endif\n\n/* undocumented functions */\nZEXTERN const char   * ZEXPORT zError           OF((int));\nZEXTERN int            ZEXPORT inflateSyncPoint OF((z_streamp));\nZEXTERN const uLongf * ZEXPORT get_crc_table    OF((void));\nZEXTERN int            ZEXPORT inflateUndermine OF((z_streamp, int));\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* ZLIB_H */\n"
  },
  {
    "path": "src/engine/external/zlib/zutil.c",
    "content": "/* zutil.c -- target dependent utility functions for the compression library\n * Copyright (C) 1995-2005, 2010 Jean-loup Gailly.\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* @(#) $Id$ */\n\n#include \"zutil.h\"\n\n#ifndef NO_DUMMY_DECL\nstruct internal_state      {int dummy;}; /* for buggy compilers */\n#endif\n\nconst char * const z_errmsg[10] = {\n\"need dictionary\",     /* Z_NEED_DICT       2  */\n\"stream end\",          /* Z_STREAM_END      1  */\n\"\",                    /* Z_OK              0  */\n\"file error\",          /* Z_ERRNO         (-1) */\n\"stream error\",        /* Z_STREAM_ERROR  (-2) */\n\"data error\",          /* Z_DATA_ERROR    (-3) */\n\"insufficient memory\", /* Z_MEM_ERROR     (-4) */\n\"buffer error\",        /* Z_BUF_ERROR     (-5) */\n\"incompatible version\",/* Z_VERSION_ERROR (-6) */\n\"\"};\n\n\nconst char * ZEXPORT zlibVersion()\n{\n    return ZLIB_VERSION;\n}\n\nuLong ZEXPORT zlibCompileFlags()\n{\n    uLong flags;\n\n    flags = 0;\n    switch ((int)(sizeof(uInt))) {\n    case 2:     break;\n    case 4:     flags += 1;     break;\n    case 8:     flags += 2;     break;\n    default:    flags += 3;\n    }\n    switch ((int)(sizeof(uLong))) {\n    case 2:     break;\n    case 4:     flags += 1 << 2;        break;\n    case 8:     flags += 2 << 2;        break;\n    default:    flags += 3 << 2;\n    }\n    switch ((int)(sizeof(voidpf))) {\n    case 2:     break;\n    case 4:     flags += 1 << 4;        break;\n    case 8:     flags += 2 << 4;        break;\n    default:    flags += 3 << 4;\n    }\n    switch ((int)(sizeof(z_off_t))) {\n    case 2:     break;\n    case 4:     flags += 1 << 6;        break;\n    case 8:     flags += 2 << 6;        break;\n    default:    flags += 3 << 6;\n    }\n#ifdef DEBUG\n    flags += 1 << 8;\n#endif\n#if defined(ASMV) || defined(ASMINF)\n    flags += 1 << 9;\n#endif\n#ifdef ZLIB_WINAPI\n    flags += 1 << 10;\n#endif\n#ifdef BUILDFIXED\n    flags += 1 << 12;\n#endif\n#ifdef DYNAMIC_CRC_TABLE\n    flags += 1 << 13;\n#endif\n#ifdef NO_GZCOMPRESS\n    flags += 1L << 16;\n#endif\n#ifdef NO_GZIP\n    flags += 1L << 17;\n#endif\n#ifdef PKZIP_BUG_WORKAROUND\n    flags += 1L << 20;\n#endif\n#ifdef FASTEST\n    flags += 1L << 21;\n#endif\n#ifdef STDC\n#  ifdef NO_vsnprintf\n        flags += 1L << 25;\n#    ifdef HAS_vsprintf_void\n        flags += 1L << 26;\n#    endif\n#  else\n#    ifdef HAS_vsnprintf_void\n        flags += 1L << 26;\n#    endif\n#  endif\n#else\n        flags += 1L << 24;\n#  ifdef NO_snprintf\n        flags += 1L << 25;\n#    ifdef HAS_sprintf_void\n        flags += 1L << 26;\n#    endif\n#  else\n#    ifdef HAS_snprintf_void\n        flags += 1L << 26;\n#    endif\n#  endif\n#endif\n    return flags;\n}\n\n#ifdef DEBUG\n\n#  ifndef verbose\n#    define verbose 0\n#  endif\nint ZLIB_INTERNAL z_verbose = verbose;\n\nvoid ZLIB_INTERNAL z_error (m)\n    char *m;\n{\n    fprintf(stderr, \"%s\\n\", m);\n    exit(1);\n}\n#endif\n\n/* exported to allow conversion of error code to string for compress() and\n * uncompress()\n */\nconst char * ZEXPORT zError(err)\n    int err;\n{\n    return ERR_MSG(err);\n}\n\n#if defined(_WIN32_WCE)\n    /* The Microsoft C Run-Time Library for Windows CE doesn't have\n     * errno.  We define it as a global variable to simplify porting.\n     * Its value is always 0 and should not be used.\n     */\n    int errno = 0;\n#endif\n\n#ifndef HAVE_MEMCPY\n\nvoid ZLIB_INTERNAL zmemcpy(dest, source, len)\n    Bytef* dest;\n    const Bytef* source;\n    uInt  len;\n{\n    if (len == 0) return;\n    do {\n        *dest++ = *source++; /* ??? to be unrolled */\n    } while (--len != 0);\n}\n\nint ZLIB_INTERNAL zmemcmp(s1, s2, len)\n    const Bytef* s1;\n    const Bytef* s2;\n    uInt  len;\n{\n    uInt j;\n\n    for (j = 0; j < len; j++) {\n        if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;\n    }\n    return 0;\n}\n\nvoid ZLIB_INTERNAL zmemzero(dest, len)\n    Bytef* dest;\n    uInt  len;\n{\n    if (len == 0) return;\n    do {\n        *dest++ = 0;  /* ??? to be unrolled */\n    } while (--len != 0);\n}\n#endif\n\n\n#ifdef SYS16BIT\n\n#ifdef __TURBOC__\n/* Turbo C in 16-bit mode */\n\n#  define MY_ZCALLOC\n\n/* Turbo C malloc() does not allow dynamic allocation of 64K bytes\n * and farmalloc(64K) returns a pointer with an offset of 8, so we\n * must fix the pointer. Warning: the pointer must be put back to its\n * original form in order to free it, use zcfree().\n */\n\n#define MAX_PTR 10\n/* 10*64K = 640K */\n\nlocal int next_ptr = 0;\n\ntypedef struct ptr_table_s {\n    voidpf org_ptr;\n    voidpf new_ptr;\n} ptr_table;\n\nlocal ptr_table table[MAX_PTR];\n/* This table is used to remember the original form of pointers\n * to large buffers (64K). Such pointers are normalized with a zero offset.\n * Since MSDOS is not a preemptive multitasking OS, this table is not\n * protected from concurrent access. This hack doesn't work anyway on\n * a protected system like OS/2. Use Microsoft C instead.\n */\n\nvoidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size)\n{\n    voidpf buf = opaque; /* just to make some compilers happy */\n    ulg bsize = (ulg)items*size;\n\n    /* If we allocate less than 65520 bytes, we assume that farmalloc\n     * will return a usable pointer which doesn't have to be normalized.\n     */\n    if (bsize < 65520L) {\n        buf = farmalloc(bsize);\n        if (*(ush*)&buf != 0) return buf;\n    } else {\n        buf = farmalloc(bsize + 16L);\n    }\n    if (buf == NULL || next_ptr >= MAX_PTR) return NULL;\n    table[next_ptr].org_ptr = buf;\n\n    /* Normalize the pointer to seg:0 */\n    *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;\n    *(ush*)&buf = 0;\n    table[next_ptr++].new_ptr = buf;\n    return buf;\n}\n\nvoid ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr)\n{\n    int n;\n    if (*(ush*)&ptr != 0) { /* object < 64K */\n        farfree(ptr);\n        return;\n    }\n    /* Find the original pointer */\n    for (n = 0; n < next_ptr; n++) {\n        if (ptr != table[n].new_ptr) continue;\n\n        farfree(table[n].org_ptr);\n        while (++n < next_ptr) {\n            table[n-1] = table[n];\n        }\n        next_ptr--;\n        return;\n    }\n    ptr = opaque; /* just to make some compilers happy */\n    Assert(0, \"zcfree: ptr not found\");\n}\n\n#endif /* __TURBOC__ */\n\n\n#ifdef M_I86\n/* Microsoft C in 16-bit mode */\n\n#  define MY_ZCALLOC\n\n#if (!defined(_MSC_VER) || (_MSC_VER <= 600))\n#  define _halloc  halloc\n#  define _hfree   hfree\n#endif\n\nvoidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size)\n{\n    if (opaque) opaque = 0; /* to make compiler happy */\n    return _halloc((long)items, size);\n}\n\nvoid ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr)\n{\n    if (opaque) opaque = 0; /* to make compiler happy */\n    _hfree(ptr);\n}\n\n#endif /* M_I86 */\n\n#endif /* SYS16BIT */\n\n\n#ifndef MY_ZCALLOC /* Any system without a special alloc function */\n\n#ifndef STDC\nextern voidp  malloc OF((uInt size));\nextern voidp  calloc OF((uInt items, uInt size));\nextern void   free   OF((voidpf ptr));\n#endif\n\nvoidpf ZLIB_INTERNAL zcalloc (opaque, items, size)\n    voidpf opaque;\n    unsigned items;\n    unsigned size;\n{\n    if (opaque) items += size - size; /* make compiler happy */\n    return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :\n                              (voidpf)calloc(items, size);\n}\n\nvoid ZLIB_INTERNAL zcfree (opaque, ptr)\n    voidpf opaque;\n    voidpf ptr;\n{\n    free(ptr);\n    if (opaque) return; /* make compiler happy */\n}\n\n#endif /* MY_ZCALLOC */\n"
  },
  {
    "path": "src/engine/external/zlib/zutil.h",
    "content": "/* zutil.h -- internal interface and configuration of the compression library\n * Copyright (C) 1995-2010 Jean-loup Gailly.\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* WARNING: this file should *not* be used by applications. It is\n   part of the implementation of the compression library and is\n   subject to change. Applications should only use zlib.h.\n */\n\n/* @(#) $Id$ */\n\n#ifndef ZUTIL_H\n#define ZUTIL_H\n\n#if ((__GNUC__-0) * 10 + __GNUC_MINOR__-0 >= 33) && !defined(NO_VIZ)\n#  define ZLIB_INTERNAL __attribute__((visibility (\"hidden\")))\n#else\n#  define ZLIB_INTERNAL\n#endif\n\n#include \"zlib.h\"\n\n#ifdef STDC\n#  if !(defined(_WIN32_WCE) && defined(_MSC_VER))\n#    include <stddef.h>\n#  endif\n#  include <string.h>\n#  include <stdlib.h>\n#endif\n\n#ifndef local\n#  define local static\n#endif\n/* compile with -Dlocal if your debugger can't find static symbols */\n\ntypedef unsigned char  uch;\ntypedef uch FAR uchf;\ntypedef unsigned short ush;\ntypedef ush FAR ushf;\ntypedef unsigned long  ulg;\n\nextern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */\n/* (size given to avoid silly warnings with Visual C++) */\n\n#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]\n\n#define ERR_RETURN(strm,err) \\\n  return (strm->msg = (char*)ERR_MSG(err), (err))\n/* To be used only when the state is known to be valid */\n\n        /* common constants */\n\n#ifndef DEF_WBITS\n#  define DEF_WBITS MAX_WBITS\n#endif\n/* default windowBits for decompression. MAX_WBITS is for compression only */\n\n#if MAX_MEM_LEVEL >= 8\n#  define DEF_MEM_LEVEL 8\n#else\n#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL\n#endif\n/* default memLevel */\n\n#define STORED_BLOCK 0\n#define STATIC_TREES 1\n#define DYN_TREES    2\n/* The three kinds of block type */\n\n#define MIN_MATCH  3\n#define MAX_MATCH  258\n/* The minimum and maximum match lengths */\n\n#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */\n\n        /* target dependencies */\n\n#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))\n#  define OS_CODE  0x00\n#  if defined(__TURBOC__) || defined(__BORLANDC__)\n#    if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))\n       /* Allow compilation with ANSI keywords only enabled */\n       void _Cdecl farfree( void *block );\n       void *_Cdecl farmalloc( unsigned long nbytes );\n#    else\n#      include <alloc.h>\n#    endif\n#  else /* MSC or DJGPP */\n#    include <malloc.h>\n#  endif\n#endif\n\n#ifdef AMIGA\n#  define OS_CODE  0x01\n#endif\n\n#if defined(VAXC) || defined(VMS)\n#  define OS_CODE  0x02\n#  define F_OPEN(name, mode) \\\n     fopen((name), (mode), \"mbc=60\", \"ctx=stm\", \"rfm=fix\", \"mrs=512\")\n#endif\n\n#if defined(ATARI) || defined(atarist)\n#  define OS_CODE  0x05\n#endif\n\n#ifdef OS2\n#  define OS_CODE  0x06\n#  ifdef M_I86\n#    include <malloc.h>\n#  endif\n#endif\n\n#if defined(MACOS) || defined(TARGET_OS_MAC)\n#  define OS_CODE  0x07\n#  if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os\n#    include <unix.h> /* for fdopen */\n#  else\n#    ifndef fdopen\n#      define fdopen(fd,mode) NULL /* No fdopen() */\n#    endif\n#  endif\n#endif\n\n#ifdef TOPS20\n#  define OS_CODE  0x0a\n#endif\n\n#ifdef WIN32\n#  ifndef __CYGWIN__  /* Cygwin is Unix, not Win32 */\n#    define OS_CODE  0x0b\n#  endif\n#endif\n\n#ifdef __50SERIES /* Prime/PRIMOS */\n#  define OS_CODE  0x0f\n#endif\n\n#if defined(_BEOS_) || defined(RISCOS)\n#  define fdopen(fd,mode) NULL /* No fdopen() */\n#endif\n\n#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX\n#  if defined(_WIN32_WCE)\n#    define fdopen(fd,mode) NULL /* No fdopen() */\n#    ifndef _PTRDIFF_T_DEFINED\n       typedef int ptrdiff_t;\n#      define _PTRDIFF_T_DEFINED\n#    endif\n#  else\n#    define fdopen(fd,type)  _fdopen(fd,type)\n#  endif\n#endif\n\n#if defined(__BORLANDC__)\n  #pragma warn -8004\n  #pragma warn -8008\n  #pragma warn -8066\n#endif\n\n/* provide prototypes for these when building zlib without LFS */\n#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0\n    ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));\n    ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));\n#endif\n\n        /* common defaults */\n\n#ifndef OS_CODE\n#  define OS_CODE  0x03  /* assume Unix */\n#endif\n\n#ifndef F_OPEN\n#  define F_OPEN(name, mode) fopen((name), (mode))\n#endif\n\n         /* functions */\n\n#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)\n#  ifndef HAVE_VSNPRINTF\n#    define HAVE_VSNPRINTF\n#  endif\n#endif\n#if defined(__CYGWIN__)\n#  ifndef HAVE_VSNPRINTF\n#    define HAVE_VSNPRINTF\n#  endif\n#endif\n#ifndef HAVE_VSNPRINTF\n#  ifdef MSDOS\n     /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),\n        but for now we just assume it doesn't. */\n#    define NO_vsnprintf\n#  endif\n#  ifdef __TURBOC__\n#    define NO_vsnprintf\n#  endif\n#  ifdef WIN32\n     /* In Win32, vsnprintf is available as the \"non-ANSI\" _vsnprintf. */\n#    if !defined(vsnprintf) && !defined(NO_vsnprintf)\n#      if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 )\n#         define vsnprintf _vsnprintf\n#      endif\n#    endif\n#  endif\n#  ifdef __SASC\n#    define NO_vsnprintf\n#  endif\n#endif\n#ifdef VMS\n#  define NO_vsnprintf\n#endif\n\n#if defined(pyr)\n#  define NO_MEMCPY\n#endif\n#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)\n /* Use our own functions for small and medium model with MSC <= 5.0.\n  * You may have to use the same strategy for Borland C (untested).\n  * The __SC__ check is for Symantec.\n  */\n#  define NO_MEMCPY\n#endif\n#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)\n#  define HAVE_MEMCPY\n#endif\n#ifdef HAVE_MEMCPY\n#  ifdef SMALL_MEDIUM /* MSDOS small or medium model */\n#    define zmemcpy _fmemcpy\n#    define zmemcmp _fmemcmp\n#    define zmemzero(dest, len) _fmemset(dest, 0, len)\n#  else\n#    define zmemcpy memcpy\n#    define zmemcmp memcmp\n#    define zmemzero(dest, len) memset(dest, 0, len)\n#  endif\n#else\n   void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));\n   int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));\n   void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len));\n#endif\n\n/* Diagnostic functions */\n#ifdef DEBUG\n#  include <stdio.h>\n   extern int ZLIB_INTERNAL z_verbose;\n   extern void ZLIB_INTERNAL z_error OF((char *m));\n#  define Assert(cond,msg) {if(!(cond)) z_error(msg);}\n#  define Trace(x) {if (z_verbose>=0) fprintf x ;}\n#  define Tracev(x) {if (z_verbose>0) fprintf x ;}\n#  define Tracevv(x) {if (z_verbose>1) fprintf x ;}\n#  define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}\n#  define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}\n#else\n#  define Assert(cond,msg)\n#  define Trace(x)\n#  define Tracev(x)\n#  define Tracevv(x)\n#  define Tracec(c,x)\n#  define Tracecv(c,x)\n#endif\n\n\nvoidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items,\n                        unsigned size));\nvoid ZLIB_INTERNAL zcfree  OF((voidpf opaque, voidpf ptr));\n\n#define ZALLOC(strm, items, size) \\\n           (*((strm)->zalloc))((strm)->opaque, (items), (size))\n#define ZFREE(strm, addr)  (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))\n#define TRY_FREE(s, p) {if (p) ZFREE(s, p);}\n\n#endif /* ZUTIL_H */\n"
  },
  {
    "path": "src/engine/friends.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_FRIENDS_H\n#define ENGINE_FRIENDS_H\n\n#include <engine/shared/protocol.h>\n\n#include \"kernel.h\"\n\nstruct CFriendInfo\n{\n\tchar m_aName[MAX_NAME_LENGTH];\n\tchar m_aClan[MAX_CLAN_LENGTH];\n\tunsigned m_NameHash;\n\tunsigned m_ClanHash;\n};\n\nclass IFriends : public IInterface\n{\n\tMACRO_INTERFACE(\"friends\", 0)\npublic:\n\tenum\n\t{\n\t\tFRIEND_NO=0,\n\t\tFRIEND_CLAN,\n\t\tFRIEND_PLAYER,\n\n\t\tMAX_FRIENDS=128,\n\t};\n\n\tvirtual void Init() = 0;\n\n\tvirtual int NumFriends() const = 0;\n\tvirtual const CFriendInfo *GetFriend(int Index) const = 0;\n\tvirtual int GetFriendState(const char *pName, const char *pClan) const = 0;\n\tvirtual bool IsFriend(const char *pName, const char *pClan, bool PlayersOnly) const = 0;\n\n\tvirtual void AddFriend(const char *pName, const char *pClan) = 0;\n\tvirtual void RemoveFriend(const char *pName, const char *pClan) = 0;\n};\n\n#endif\n"
  },
  {
    "path": "src/engine/graphics.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_GRAPHICS_H\n#define ENGINE_GRAPHICS_H\n\n#include <base/vmath.h>\n\n#include \"kernel.h\"\n\n\nclass CImageInfo\n{\npublic:\n\tenum\n\t{\n\t\tFORMAT_AUTO=-1,\n\t\tFORMAT_RGB=0,\n\t\tFORMAT_RGBA=1,\n\t\tFORMAT_ALPHA=2,\n\t};\n\n\t/* Variable: width\n\t\tContains the width of the image */\n\tint m_Width;\n\n\t/* Variable: height\n\t\tContains the height of the image */\n\tint m_Height;\n\n\t/* Variable: format\n\t\tContains the format of the image. See <Image Formats> for more information. */\n\tint m_Format;\n\n\t/* Variable: data\n\t\tPointer to the image data. */\n\tvoid *m_pData;\n};\n\n/*\n\tStructure: CVideoMode\n*/\nclass CVideoMode\n{\npublic:\n\tint m_Width, m_Height;\n\tint m_Red, m_Green, m_Blue;\n\n\tbool operator<(const CVideoMode &Other) { return Other.m_Width < m_Width; }\n};\n\nclass IGraphics : public IInterface\n{\n\tMACRO_INTERFACE(\"graphics\", 0)\nprotected:\n\tint m_ScreenWidth;\n\tint m_ScreenHeight;\n\tint m_DesktopScreenWidth;\n\tint m_DesktopScreenHeight;\npublic:\n\t/* Constants: Texture Loading Flags\n\t\tTEXLOAD_NORESAMPLE - Prevents the texture from any resampling\n\t*/\n\tenum\n\t{\n\t\tTEXLOAD_NORESAMPLE = 1,\n\t\tTEXLOAD_NOMIPMAPS = 2,\n\t};\n\n\n\tclass CTextureHandle\n\t{\n\t\tfriend class IGraphics;\n\t\tint m_Id;\n\tpublic:\n\t\tCTextureHandle()\n\t\t: m_Id(-1)\n\t\t{}\n\n\t\tbool IsValid() const { return Id() >= 0; }\n\t\tint Id() const { return m_Id; }\n\t};\n\n\tint ScreenWidth() const { return m_ScreenWidth; }\n\tint ScreenHeight() const { return m_ScreenHeight; }\n\tfloat ScreenAspect() const { return (float)ScreenWidth()/(float)ScreenHeight(); }\n\n\tvirtual void Clear(float r, float g, float b) = 0;\n\n\tvirtual void ClipEnable(int x, int y, int w, int h) = 0;\n\tvirtual void ClipDisable() = 0;\n\n\tvirtual void MapScreen(float TopLeftX, float TopLeftY, float BottomRightX, float BottomRightY) = 0;\n\tvirtual void GetScreen(float *pTopLeftX, float *pTopLeftY, float *pBottomRightX, float *pBottomRightY) = 0;\n\n\t// TODO: These should perhaps not be virtuals\n\tvirtual void BlendNone() = 0;\n\tvirtual void BlendNormal() = 0;\n\tvirtual void BlendAdditive() = 0;\n\tvirtual void WrapNormal() = 0;\n\tvirtual void WrapClamp() = 0;\n\tvirtual int MemoryUsage() const = 0;\n\n\tvirtual int LoadPNG(CImageInfo *pImg, const char *pFilename, int StorageType) = 0;\n\n\tvirtual int UnloadTexture(CTextureHandle Index) = 0;\n\tvirtual CTextureHandle LoadTextureRaw(int Width, int Height, int Format, const void *pData, int StoreFormat, int Flags) = 0;\n\tvirtual int LoadTextureRawSub(CTextureHandle TextureID, int x, int y, int Width, int Height, int Format, const void *pData) = 0;\n\tvirtual CTextureHandle LoadTexture(const char *pFilename, int StorageType, int StoreFormat, int Flags) = 0;\n\tvirtual void TextureSet(CTextureHandle Texture) = 0;\n\tvoid TextureClear() { TextureSet(CTextureHandle()); }\n\n\tstruct CLineItem\n\t{\n\t\tfloat m_X0, m_Y0, m_X1, m_Y1;\n\t\tCLineItem() {}\n\t\tCLineItem(float x0, float y0, float x1, float y1) : m_X0(x0), m_Y0(y0), m_X1(x1), m_Y1(y1) {}\n\t};\n\tvirtual void LinesBegin() = 0;\n\tvirtual void LinesEnd() = 0;\n\tvirtual void LinesDraw(const CLineItem *pArray, int Num) = 0;\n\n\tvirtual void QuadsBegin() = 0;\n\tvirtual void QuadsEnd() = 0;\n\tvirtual void QuadsSetRotation(float Angle) = 0;\n\tvirtual void QuadsSetSubset(float TopLeftY, float TopLeftV, float BottomRightU, float BottomRightV) = 0;\n\tvirtual void QuadsSetSubsetFree(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) = 0;\n\n\tstruct CQuadItem\n\t{\n\t\tfloat m_X, m_Y, m_Width, m_Height;\n\t\tCQuadItem() {}\n\t\tCQuadItem(float x, float y, float w, float h) : m_X(x), m_Y(y), m_Width(w), m_Height(h) {}\n\t};\n\tvirtual void QuadsDraw(CQuadItem *pArray, int Num) = 0;\n\tvirtual void QuadsDrawTL(const CQuadItem *pArray, int Num) = 0;\n\n\tstruct CFreeformItem\n\t{\n\t\tfloat m_X0, m_Y0, m_X1, m_Y1, m_X2, m_Y2, m_X3, m_Y3;\n\t\tCFreeformItem() {}\n\t\tCFreeformItem(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3)\n\t\t\t: m_X0(x0), m_Y0(y0), m_X1(x1), m_Y1(y1), m_X2(x2), m_Y2(y2), m_X3(x3), m_Y3(y3) {}\n\t};\n\tvirtual void QuadsDrawFreeform(const CFreeformItem *pArray, int Num) = 0;\n\tvirtual void QuadsText(float x, float y, float Size, const char *pText) = 0;\n\n\tstruct CColorVertex\n\t{\n\t\tint m_Index;\n\t\tfloat m_R, m_G, m_B, m_A;\n\t\tCColorVertex() {}\n\t\tCColorVertex(int i, float r, float g, float b, float a) : m_Index(i), m_R(r), m_G(g), m_B(b), m_A(a) {}\n\t};\n\tvirtual void SetColorVertex(const CColorVertex *pArray, int Num) = 0;\n\tvirtual void SetColor(float r, float g, float b, float a) = 0;\n\tvirtual void SetColor4(vec4 TopLeft, vec4 TopRight, vec4 BottomLeft, vec4 BottomRight) = 0;\n\n\tvirtual void TakeScreenshot(const char *pFilename) = 0;\n\tvirtual int GetVideoModes(CVideoMode *pModes, int MaxModes) = 0;\n\n\tvirtual int GetDesktopScreenWidth() = 0;\n\tvirtual int GetDesktopScreenHeight() = 0;\n\n\tvirtual void Swap() = 0;\n\n\t// syncronization\n\tvirtual void InsertSignal(class semaphore *pSemaphore) = 0;\n\tvirtual bool IsIdle() = 0;\n\tvirtual void WaitForIdle() = 0;\n\nprotected:\n\tinline CTextureHandle CreateTextureHandle(int Index)\n\t{\n\t\tCTextureHandle Tex;\n\t\tTex.m_Id = Index;\n\t\treturn Tex;\n\t}\n};\n\nclass IEngineGraphics : public IGraphics\n{\n\tMACRO_INTERFACE(\"enginegraphics\", 0)\npublic:\n\tvirtual int Init() = 0;\n\tvirtual void Shutdown() = 0;\n\n\tvirtual void Minimize() = 0;\n\tvirtual void Maximize() = 0;\n\n\tvirtual int WindowActive() = 0;\n\tvirtual int WindowOpen() = 0;\n\n};\n\nextern IEngineGraphics *CreateEngineGraphics();\nextern IEngineGraphics *CreateEngineGraphicsThreaded();\n\n#endif\n"
  },
  {
    "path": "src/engine/input.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_INPUT_H\n#define ENGINE_INPUT_H\n\n#include \"kernel.h\"\n\nextern const char g_aaKeyStrings[512][16];\n\nclass IInput : public IInterface\n{\n\tMACRO_INTERFACE(\"input\", 0)\npublic:\n\tclass CEvent\n\t{\n\tpublic:\n\t\tint m_Flags;\n\t\tint m_Unicode;\n\t\tint m_Key;\n\t};\n\nprotected:\n\tenum\n\t{\n\t\tINPUT_BUFFER_SIZE=32\n\t};\n\n\t// quick access to events\n\tint m_NumEvents;\n\tIInput::CEvent m_aInputEvents[INPUT_BUFFER_SIZE];\n\n\t//quick access to input\n\tstruct\n\t{\n\t\tunsigned char m_Presses;\n\t\tunsigned char m_Releases;\n\t} m_aInputCount[2][1024];\n\n\tunsigned char m_aInputState[2][1024];\n\tint m_InputCurrent;\n\tbool m_InputDispatched;\n\n\tint KeyWasPressed(int Key) { return m_aInputState[m_InputCurrent^1][Key]; }\n\npublic:\n\tenum\n\t{\n\t\tFLAG_PRESS=1,\n\t\tFLAG_RELEASE=2,\n\t\tFLAG_REPEAT=4\n\t};\n\n\t// events\n\tint NumEvents() const { return m_NumEvents; }\n\tvoid ClearEvents() \n\t{ \n\t\tm_NumEvents = 0;\n\t\tm_InputDispatched = true;\n\t}\n\tCEvent GetEvent(int Index) const\n\t{\n\t\tif(Index < 0 || Index >= m_NumEvents)\n\t\t{\n\t\t\tIInput::CEvent e = {0,0};\n\t\t\treturn e;\n\t\t}\n\t\treturn m_aInputEvents[Index];\n\t}\n\n\t// keys\n\tint KeyPressed(int Key) { return m_aInputState[m_InputCurrent][Key]; }\n\tint KeyReleases(int Key) { return m_aInputCount[m_InputCurrent][Key].m_Releases; }\n\tint KeyPresses(int Key) { return m_aInputCount[m_InputCurrent][Key].m_Presses; }\n\tint KeyDown(int Key) { return KeyPressed(Key)&&!KeyWasPressed(Key); }\n\tconst char *KeyName(int Key) { return (Key >= 0 && Key < 512) ? g_aaKeyStrings[Key] : g_aaKeyStrings[0]; }\n\n\t//\n\tvirtual void MouseModeRelative() = 0;\n\tvirtual void MouseModeAbsolute() = 0;\n\tvirtual int MouseDoubleClick() = 0;\n\n\tvirtual void MouseRelative(float *x, float *y) = 0;\n};\n\n\nclass IEngineInput : public IInput\n{\n\tMACRO_INTERFACE(\"engineinput\", 0)\npublic:\n\tvirtual void Init() = 0;\n\tvirtual int Update() = 0;\n};\n\nextern IEngineInput *CreateEngineInput();\n\n#endif\n"
  },
  {
    "path": "src/engine/kernel.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_KERNEL_H\n#define ENGINE_KERNEL_H\n\n#include <base/system.h>\n\nclass IKernel;\nclass IInterface;\n\nclass IInterface\n{\n\t// friend with the kernel implementation\n\tfriend class CKernel;\n\tIKernel *m_pKernel;\nprotected:\n\tIKernel *Kernel() { return m_pKernel; }\npublic:\n\tIInterface() : m_pKernel(0) {}\n\tvirtual ~IInterface() {}\n\n\t//virtual unsigned InterfaceID() = 0;\n\t//virtual const char *InterfaceName() = 0;\n};\n\n#define MACRO_INTERFACE(Name, ver) \\\n\tpublic: \\\n\t\tstatic const char *InterfaceName() { return Name; } \\\n\tprivate:\n\n\t\t//virtual unsigned InterfaceID() { return INTERFACE_ID; }\n\t\t//virtual const char *InterfaceName() { return name; }\n\n\n// This kernel thingie makes the structure very flat and basiclly singletons.\n// I'm not sure if this is a good idea but it works for now.\nclass IKernel\n{\n\t// hide the implementation\n\tvirtual bool RegisterInterfaceImpl(const char *InterfaceName, IInterface *pInterface) = 0;\n\tvirtual bool ReregisterInterfaceImpl(const char *InterfaceName, IInterface *pInterface) = 0;\n\tvirtual IInterface *RequestInterfaceImpl(const char *InterfaceName) = 0;\npublic:\n\tstatic IKernel *Create();\n\tvirtual ~IKernel() {}\n\n\t// templated access to handle pointer convertions and interface names\n\ttemplate<class TINTERFACE>\n\tbool RegisterInterface(TINTERFACE *pInterface)\n\t{\n\t\treturn RegisterInterfaceImpl(TINTERFACE::InterfaceName(), pInterface);\n\t}\n\ttemplate<class TINTERFACE>\n\tbool ReregisterInterface(TINTERFACE *pInterface)\n\t{\n\t\treturn ReregisterInterfaceImpl(TINTERFACE::InterfaceName(), pInterface);\n\t}\n\n\t// Usage example:\n\t//\t\tIMyInterface *pMyHandle = Kernel()->RequestInterface<IMyInterface>()\n\ttemplate<class TINTERFACE>\n\tTINTERFACE *RequestInterface()\n\t{\n\t\treturn reinterpret_cast<TINTERFACE *>(RequestInterfaceImpl(TINTERFACE::InterfaceName()));\n\t}\n};\n\n#endif\n"
  },
  {
    "path": "src/engine/keys.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_KEYS_H\n#define ENGINE_KEYS_H\n/* AUTO GENERATED! DO NOT EDIT MANUALLY! */\nenum\n{\n\tKEY_UNKNOWN = 0,\n\tKEY_FIRST = 0,\n\tKEY_BACKSPACE = 8,\n\tKEY_TAB = 9,\n\tKEY_CLEAR = 12,\n\tKEY_RETURN = 13,\n\tKEY_PAUSE = 19,\n\tKEY_ESCAPE = 27,\n\tKEY_SPACE = 32,\n\tKEY_EXCLAIM = 33,\n\tKEY_QUOTEDBL = 34,\n\tKEY_HASH = 35,\n\tKEY_DOLLAR = 36,\n\tKEY_AMPERSAND = 38,\n\tKEY_QUOTE = 39,\n\tKEY_LEFTPAREN = 40,\n\tKEY_RIGHTPAREN = 41,\n\tKEY_ASTERISK = 42,\n\tKEY_PLUS = 43,\n\tKEY_COMMA = 44,\n\tKEY_MINUS = 45,\n\tKEY_PERIOD = 46,\n\tKEY_SLASH = 47,\n\tKEY_0 = 48,\n\tKEY_1 = 49,\n\tKEY_2 = 50,\n\tKEY_3 = 51,\n\tKEY_4 = 52,\n\tKEY_5 = 53,\n\tKEY_6 = 54,\n\tKEY_7 = 55,\n\tKEY_8 = 56,\n\tKEY_9 = 57,\n\tKEY_COLON = 58,\n\tKEY_SEMICOLON = 59,\n\tKEY_LESS = 60,\n\tKEY_EQUALS = 61,\n\tKEY_GREATER = 62,\n\tKEY_QUESTION = 63,\n\tKEY_AT = 64,\n\tKEY_LEFTBRACKET = 91,\n\tKEY_BACKSLASH = 92,\n\tKEY_RIGHTBRACKET = 93,\n\tKEY_CARET = 94,\n\tKEY_UNDERSCORE = 95,\n\tKEY_BACKQUOTE = 96,\n\tKEY_a = 97,\n\tKEY_b = 98,\n\tKEY_c = 99,\n\tKEY_d = 100,\n\tKEY_e = 101,\n\tKEY_f = 102,\n\tKEY_g = 103,\n\tKEY_h = 104,\n\tKEY_i = 105,\n\tKEY_j = 106,\n\tKEY_k = 107,\n\tKEY_l = 108,\n\tKEY_m = 109,\n\tKEY_n = 110,\n\tKEY_o = 111,\n\tKEY_p = 112,\n\tKEY_q = 113,\n\tKEY_r = 114,\n\tKEY_s = 115,\n\tKEY_t = 116,\n\tKEY_u = 117,\n\tKEY_v = 118,\n\tKEY_w = 119,\n\tKEY_x = 120,\n\tKEY_y = 121,\n\tKEY_z = 122,\n\tKEY_DELETE = 127,\n\tKEY_WORLD_0 = 160,\n\tKEY_WORLD_1 = 161,\n\tKEY_WORLD_2 = 162,\n\tKEY_WORLD_3 = 163,\n\tKEY_WORLD_4 = 164,\n\tKEY_WORLD_5 = 165,\n\tKEY_WORLD_6 = 166,\n\tKEY_WORLD_7 = 167,\n\tKEY_WORLD_8 = 168,\n\tKEY_WORLD_9 = 169,\n\tKEY_WORLD_10 = 170,\n\tKEY_WORLD_11 = 171,\n\tKEY_WORLD_12 = 172,\n\tKEY_WORLD_13 = 173,\n\tKEY_WORLD_14 = 174,\n\tKEY_WORLD_15 = 175,\n\tKEY_WORLD_16 = 176,\n\tKEY_WORLD_17 = 177,\n\tKEY_WORLD_18 = 178,\n\tKEY_WORLD_19 = 179,\n\tKEY_WORLD_20 = 180,\n\tKEY_WORLD_21 = 181,\n\tKEY_WORLD_22 = 182,\n\tKEY_WORLD_23 = 183,\n\tKEY_WORLD_24 = 184,\n\tKEY_WORLD_25 = 185,\n\tKEY_WORLD_26 = 186,\n\tKEY_WORLD_27 = 187,\n\tKEY_WORLD_28 = 188,\n\tKEY_WORLD_29 = 189,\n\tKEY_WORLD_30 = 190,\n\tKEY_WORLD_31 = 191,\n\tKEY_WORLD_32 = 192,\n\tKEY_WORLD_33 = 193,\n\tKEY_WORLD_34 = 194,\n\tKEY_WORLD_35 = 195,\n\tKEY_WORLD_36 = 196,\n\tKEY_WORLD_37 = 197,\n\tKEY_WORLD_38 = 198,\n\tKEY_WORLD_39 = 199,\n\tKEY_WORLD_40 = 200,\n\tKEY_WORLD_41 = 201,\n\tKEY_WORLD_42 = 202,\n\tKEY_WORLD_43 = 203,\n\tKEY_WORLD_44 = 204,\n\tKEY_WORLD_45 = 205,\n\tKEY_WORLD_46 = 206,\n\tKEY_WORLD_47 = 207,\n\tKEY_WORLD_48 = 208,\n\tKEY_WORLD_49 = 209,\n\tKEY_WORLD_50 = 210,\n\tKEY_WORLD_51 = 211,\n\tKEY_WORLD_52 = 212,\n\tKEY_WORLD_53 = 213,\n\tKEY_WORLD_54 = 214,\n\tKEY_WORLD_55 = 215,\n\tKEY_WORLD_56 = 216,\n\tKEY_WORLD_57 = 217,\n\tKEY_WORLD_58 = 218,\n\tKEY_WORLD_59 = 219,\n\tKEY_WORLD_60 = 220,\n\tKEY_WORLD_61 = 221,\n\tKEY_WORLD_62 = 222,\n\tKEY_WORLD_63 = 223,\n\tKEY_WORLD_64 = 224,\n\tKEY_WORLD_65 = 225,\n\tKEY_WORLD_66 = 226,\n\tKEY_WORLD_67 = 227,\n\tKEY_WORLD_68 = 228,\n\tKEY_WORLD_69 = 229,\n\tKEY_WORLD_70 = 230,\n\tKEY_WORLD_71 = 231,\n\tKEY_WORLD_72 = 232,\n\tKEY_WORLD_73 = 233,\n\tKEY_WORLD_74 = 234,\n\tKEY_WORLD_75 = 235,\n\tKEY_WORLD_76 = 236,\n\tKEY_WORLD_77 = 237,\n\tKEY_WORLD_78 = 238,\n\tKEY_WORLD_79 = 239,\n\tKEY_WORLD_80 = 240,\n\tKEY_WORLD_81 = 241,\n\tKEY_WORLD_82 = 242,\n\tKEY_WORLD_83 = 243,\n\tKEY_WORLD_84 = 244,\n\tKEY_WORLD_85 = 245,\n\tKEY_WORLD_86 = 246,\n\tKEY_WORLD_87 = 247,\n\tKEY_WORLD_88 = 248,\n\tKEY_WORLD_89 = 249,\n\tKEY_WORLD_90 = 250,\n\tKEY_WORLD_91 = 251,\n\tKEY_WORLD_92 = 252,\n\tKEY_WORLD_93 = 253,\n\tKEY_WORLD_94 = 254,\n\tKEY_WORLD_95 = 255,\n\tKEY_KP0 = 256,\n\tKEY_KP1 = 257,\n\tKEY_KP2 = 258,\n\tKEY_KP3 = 259,\n\tKEY_KP4 = 260,\n\tKEY_KP5 = 261,\n\tKEY_KP6 = 262,\n\tKEY_KP7 = 263,\n\tKEY_KP8 = 264,\n\tKEY_KP9 = 265,\n\tKEY_KP_PERIOD = 266,\n\tKEY_KP_DIVIDE = 267,\n\tKEY_KP_MULTIPLY = 268,\n\tKEY_KP_MINUS = 269,\n\tKEY_KP_PLUS = 270,\n\tKEY_KP_ENTER = 271,\n\tKEY_KP_EQUALS = 272,\n\tKEY_UP = 273,\n\tKEY_DOWN = 274,\n\tKEY_RIGHT = 275,\n\tKEY_LEFT = 276,\n\tKEY_INSERT = 277,\n\tKEY_HOME = 278,\n\tKEY_END = 279,\n\tKEY_PAGEUP = 280,\n\tKEY_PAGEDOWN = 281,\n\tKEY_F1 = 282,\n\tKEY_F2 = 283,\n\tKEY_F3 = 284,\n\tKEY_F4 = 285,\n\tKEY_F5 = 286,\n\tKEY_F6 = 287,\n\tKEY_F7 = 288,\n\tKEY_F8 = 289,\n\tKEY_F9 = 290,\n\tKEY_F10 = 291,\n\tKEY_F11 = 292,\n\tKEY_F12 = 293,\n\tKEY_F13 = 294,\n\tKEY_F14 = 295,\n\tKEY_F15 = 296,\n\tKEY_NUMLOCK = 300,\n\tKEY_CAPSLOCK = 301,\n\tKEY_SCROLLOCK = 302,\n\tKEY_RSHIFT = 303,\n\tKEY_LSHIFT = 304,\n\tKEY_RCTRL = 305,\n\tKEY_LCTRL = 306,\n\tKEY_RALT = 307,\n\tKEY_LALT = 308,\n\tKEY_RMETA = 309,\n\tKEY_LMETA = 310,\n\tKEY_LSUPER = 311,\n\tKEY_RSUPER = 312,\n\tKEY_MODE = 313,\n\tKEY_COMPOSE = 314,\n\tKEY_HELP = 315,\n\tKEY_PRINT = 316,\n\tKEY_SYSREQ = 317,\n\tKEY_BREAK = 318,\n\tKEY_MENU = 319,\n\tKEY_POWER = 320,\n\tKEY_EURO = 321,\n\tKEY_UNDO = 322,\n\tKEY_MOUSE_1 = 323,\n\tKEY_MOUSE_2 = 324,\n\tKEY_MOUSE_3 = 325,\n\tKEY_MOUSE_4 = 326,\n\tKEY_MOUSE_5 = 327,\n\tKEY_MOUSE_6 = 328,\n\tKEY_MOUSE_7 = 329,\n\tKEY_MOUSE_8 = 330,\n\tKEY_MOUSE_WHEEL_UP = 331,\n\tKEY_MOUSE_WHEEL_DOWN = 332,\n\tKEY_LAST,\n};\n\n#endif\n"
  },
  {
    "path": "src/engine/map.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_MAP_H\n#define ENGINE_MAP_H\n\n#include \"kernel.h\"\n\nclass IMap : public IInterface\n{\n\tMACRO_INTERFACE(\"map\", 0)\npublic:\n\tvirtual void *GetData(int Index) = 0;\n\tvirtual void *GetDataSwapped(int Index) = 0;\n\tvirtual void UnloadData(int Index) = 0;\n\tvirtual void *GetItem(int Index, int *Type, int *pID) = 0;\n\tvirtual void GetType(int Type, int *pStart, int *pNum) = 0;\n\tvirtual void *FindItem(int Type, int ID) = 0;\n\tvirtual int NumItems() = 0;\n};\n\n\nclass IEngineMap : public IMap\n{\n\tMACRO_INTERFACE(\"enginemap\", 0)\npublic:\n\tvirtual bool Load(const char *pMapName, class IStorage *pStorage=0) = 0;\n\tvirtual bool IsLoaded() = 0;\n\tvirtual void Unload() = 0;\n\tvirtual unsigned Crc() = 0;\n};\n\nextern IEngineMap *CreateEngineMap();\n\n#endif\n"
  },
  {
    "path": "src/engine/masterserver.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_MASTERSERVER_H\n#define ENGINE_MASTERSERVER_H\n\n#include \"kernel.h\"\n\nclass IMasterServer : public IInterface\n{\n\tMACRO_INTERFACE(\"masterserver\", 0)\npublic:\n\n\tenum\n\t{\n\t\tMAX_MASTERSERVERS=4\n\t};\n\n\tvirtual void Init() = 0;\n\tvirtual void SetDefault() = 0;\n\tvirtual int Load() = 0;\n\tvirtual int Save() = 0;\n\n\tvirtual int RefreshAddresses(int Nettype) = 0;\n\tvirtual void Update() = 0;\n\tvirtual int IsRefreshing() = 0;\n\tvirtual NETADDR GetAddr(int Index) = 0;\n\tvirtual const char *GetName(int Index) = 0;\n\tvirtual bool IsValid(int Index) = 0;\n};\n\nclass IEngineMasterServer : public IMasterServer\n{\n\tMACRO_INTERFACE(\"enginemasterserver\", 0)\npublic:\n};\n\nextern IEngineMasterServer *CreateEngineMasterServer();\n\n#endif\n\n\n\n"
  },
  {
    "path": "src/engine/message.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_MESSAGE_H\n#define ENGINE_MESSAGE_H\n\n#include <engine/shared/packer.h>\n\nclass CMsgPacker : public CPacker\n{\npublic:\n\tCMsgPacker(int Type, bool System=false)\n\t{\n\t\tReset();\n\t\tAddInt((Type<<1)|(System?1:0));\n\t}\n};\n\n#endif\n"
  },
  {
    "path": "src/engine/server/register.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n#include <engine/shared/network.h>\n#include <engine/shared/config.h>\n#include <engine/console.h>\n#include <engine/masterserver.h>\n\n#include <mastersrv/mastersrv.h>\n\n#include \"register.h\"\n\nCRegister::CRegister()\n{\n\tm_pNetServer = 0;\n\tm_pMasterServer = 0;\n\tm_pConsole = 0;\n\n\tm_RegisterState = REGISTERSTATE_START;\n\tm_RegisterStateStart = 0;\n\tm_RegisterFirst = 1;\n\tm_RegisterCount = 0;\n\n\tmem_zero(m_aMasterserverInfo, sizeof(m_aMasterserverInfo));\n\tm_RegisterRegisteredServer = -1;\n}\n\nvoid CRegister::RegisterNewState(int State)\n{\n\tm_RegisterState = State;\n\tm_RegisterStateStart = time_get();\n}\n\nvoid CRegister::RegisterSendFwcheckresponse(NETADDR *pAddr)\n{\n\tCNetChunk Packet;\n\tPacket.m_ClientID = -1;\n\tPacket.m_Address = *pAddr;\n\tPacket.m_Flags = NETSENDFLAG_CONNLESS;\n\tPacket.m_DataSize = sizeof(SERVERBROWSE_FWRESPONSE);\n\tPacket.m_pData = SERVERBROWSE_FWRESPONSE;\n\tm_pNetServer->Send(&Packet);\n}\n\nvoid CRegister::RegisterSendHeartbeat(NETADDR Addr)\n{\n\tstatic unsigned char aData[sizeof(SERVERBROWSE_HEARTBEAT) + 2];\n\tunsigned short Port = g_Config.m_SvPort;\n\tCNetChunk Packet;\n\n\tmem_copy(aData, SERVERBROWSE_HEARTBEAT, sizeof(SERVERBROWSE_HEARTBEAT));\n\n\tPacket.m_ClientID = -1;\n\tPacket.m_Address = Addr;\n\tPacket.m_Flags = NETSENDFLAG_CONNLESS;\n\tPacket.m_DataSize = sizeof(SERVERBROWSE_HEARTBEAT) + 2;\n\tPacket.m_pData = &aData;\n\n\t// supply the set port that the master can use if it has problems\n\tif(g_Config.m_SvExternalPort)\n\t\tPort = g_Config.m_SvExternalPort;\n\taData[sizeof(SERVERBROWSE_HEARTBEAT)] = Port >> 8;\n\taData[sizeof(SERVERBROWSE_HEARTBEAT)+1] = Port&0xff;\n\tm_pNetServer->Send(&Packet);\n}\n\nvoid CRegister::RegisterSendCountRequest(NETADDR Addr)\n{\n\tCNetChunk Packet;\n\tPacket.m_ClientID = -1;\n\tPacket.m_Address = Addr;\n\tPacket.m_Flags = NETSENDFLAG_CONNLESS;\n\tPacket.m_DataSize = sizeof(SERVERBROWSE_GETCOUNT);\n\tPacket.m_pData = SERVERBROWSE_GETCOUNT;\n\tm_pNetServer->Send(&Packet);\n}\n\nvoid CRegister::RegisterGotCount(CNetChunk *pChunk)\n{\n\tunsigned char *pData = (unsigned char *)pChunk->m_pData;\n\tint Count = (pData[sizeof(SERVERBROWSE_COUNT)]<<8) | pData[sizeof(SERVERBROWSE_COUNT)+1];\n\n\tfor(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++)\n\t{\n\t\tif(net_addr_comp(&m_aMasterserverInfo[i].m_Addr, &pChunk->m_Address) == 0)\n\t\t{\n\t\t\tm_aMasterserverInfo[i].m_Count = Count;\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid CRegister::Init(CNetServer *pNetServer, IEngineMasterServer *pMasterServer, IConsole *pConsole)\n{\n\tm_pNetServer = pNetServer;\n\tm_pMasterServer = pMasterServer;\n\tm_pConsole = pConsole;\n}\n\nvoid CRegister::RegisterUpdate(int Nettype)\n{\n\tint64 Now = time_get();\n\tint64 Freq = time_freq();\n\n\tif(!g_Config.m_SvRegister)\n\t\treturn;\n\n\tm_pMasterServer->Update();\n\n\tif(m_RegisterState == REGISTERSTATE_START)\n\t{\n\t\tm_RegisterCount = 0;\n\t\tm_RegisterFirst = 1;\n\t\tRegisterNewState(REGISTERSTATE_UPDATE_ADDRS);\n\t\tm_pMasterServer->RefreshAddresses(Nettype);\n\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"register\", \"refreshing ip addresses\");\n\t}\n\telse if(m_RegisterState == REGISTERSTATE_UPDATE_ADDRS)\n\t{\n\t\tm_RegisterRegisteredServer = -1;\n\n\t\tif(!m_pMasterServer->IsRefreshing())\n\t\t{\n\t\t\tint i;\n\t\t\tfor(i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++)\n\t\t\t{\n\t\t\t\tif(!m_pMasterServer->IsValid(i))\n\t\t\t\t{\n\t\t\t\t\tm_aMasterserverInfo[i].m_Valid = 0;\n\t\t\t\t\tm_aMasterserverInfo[i].m_Count = 0;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tNETADDR Addr = m_pMasterServer->GetAddr(i);\n\t\t\t\tm_aMasterserverInfo[i].m_Addr = Addr;\n\t\t\t\tm_aMasterserverInfo[i].m_Valid = 1;\n\t\t\t\tm_aMasterserverInfo[i].m_Count = -1;\n\t\t\t\tm_aMasterserverInfo[i].m_LastSend = 0;\n\t\t\t}\n\n\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"register\", \"fetching server counts\");\n\t\t\tRegisterNewState(REGISTERSTATE_QUERY_COUNT);\n\t\t}\n\t}\n\telse if(m_RegisterState == REGISTERSTATE_QUERY_COUNT)\n\t{\n\t\tint Left = 0;\n\t\tfor(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++)\n\t\t{\n\t\t\tif(!m_aMasterserverInfo[i].m_Valid)\n\t\t\t\tcontinue;\n\n\t\t\tif(m_aMasterserverInfo[i].m_Count == -1)\n\t\t\t{\n\t\t\t\tLeft++;\n\t\t\t\tif(m_aMasterserverInfo[i].m_LastSend+Freq < Now)\n\t\t\t\t{\n\t\t\t\t\tm_aMasterserverInfo[i].m_LastSend = Now;\n\t\t\t\t\tRegisterSendCountRequest(m_aMasterserverInfo[i].m_Addr);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// check if we are done or timed out\n\t\tif(Left == 0 || Now > m_RegisterStateStart+Freq*3)\n\t\t{\n\t\t\t// choose server\n\t\t\tint Best = -1;\n\t\t\tint i;\n\t\t\tfor(i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++)\n\t\t\t{\n\t\t\t\tif(!m_aMasterserverInfo[i].m_Valid || m_aMasterserverInfo[i].m_Count == -1)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif(Best == -1 || m_aMasterserverInfo[i].m_Count < m_aMasterserverInfo[Best].m_Count)\n\t\t\t\t\tBest = i;\n\t\t\t}\n\n\t\t\t// server chosen\n\t\t\tm_RegisterRegisteredServer = Best;\n\t\t\tif(m_RegisterRegisteredServer == -1)\n\t\t\t{\n\t\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"register\", \"WARNING: No master servers. Retrying in 60 seconds\");\n\t\t\t\tRegisterNewState(REGISTERSTATE_ERROR);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tchar aBuf[256];\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"chose '%s' as master, sending heartbeats\", m_pMasterServer->GetName(m_RegisterRegisteredServer));\n\t\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"register\", aBuf);\n\t\t\t\tm_aMasterserverInfo[m_RegisterRegisteredServer].m_LastSend = 0;\n\t\t\t\tRegisterNewState(REGISTERSTATE_HEARTBEAT);\n\t\t\t}\n\t\t}\n\t}\n\telse if(m_RegisterState == REGISTERSTATE_HEARTBEAT)\n\t{\n\t\t// check if we should send heartbeat\n\t\tif(Now > m_aMasterserverInfo[m_RegisterRegisteredServer].m_LastSend+Freq*15)\n\t\t{\n\t\t\tm_aMasterserverInfo[m_RegisterRegisteredServer].m_LastSend = Now;\n\t\t\tRegisterSendHeartbeat(m_aMasterserverInfo[m_RegisterRegisteredServer].m_Addr);\n\t\t}\n\n\t\tif(Now > m_RegisterStateStart+Freq*60)\n\t\t{\n\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"register\", \"WARNING: Master server is not responding, switching master\");\n\t\t\tRegisterNewState(REGISTERSTATE_START);\n\t\t}\n\t}\n\telse if(m_RegisterState == REGISTERSTATE_REGISTERED)\n\t{\n\t\tif(m_RegisterFirst)\n\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"register\", \"server registered\");\n\n\t\tm_RegisterFirst = 0;\n\n\t\t// check if we should send new heartbeat again\n\t\tif(Now > m_RegisterStateStart+Freq)\n\t\t{\n\t\t\tif(m_RegisterCount == 120) // redo the whole process after 60 minutes to balance out the master servers\n\t\t\t\tRegisterNewState(REGISTERSTATE_START);\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_RegisterCount++;\n\t\t\t\tRegisterNewState(REGISTERSTATE_HEARTBEAT);\n\t\t\t}\n\t\t}\n\t}\n\telse if(m_RegisterState == REGISTERSTATE_ERROR)\n\t{\n\t\t// check for restart\n\t\tif(Now > m_RegisterStateStart+Freq*60)\n\t\t\tRegisterNewState(REGISTERSTATE_START);\n\t}\n}\n\nint CRegister::RegisterProcessPacket(CNetChunk *pPacket)\n{\n\t// check for masterserver address\n\tbool Valid = false;\n\tNETADDR Addr1 = pPacket->m_Address;\n\tAddr1.port = 0;\n\tfor(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++)\n\t{\n\t\tNETADDR Addr2 = m_aMasterserverInfo[i].m_Addr;\n\t\tAddr2.port = 0;\n\t\tif(net_addr_comp(&Addr1, &Addr2) == 0)\n\t\t{\n\t\t\tValid = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(!Valid)\n\t\treturn 0;\n\n\tif(pPacket->m_DataSize == sizeof(SERVERBROWSE_FWCHECK) &&\n\t\tmem_comp(pPacket->m_pData, SERVERBROWSE_FWCHECK, sizeof(SERVERBROWSE_FWCHECK)) == 0)\n\t{\n\t\tRegisterSendFwcheckresponse(&pPacket->m_Address);\n\t\treturn 1;\n\t}\n\telse if(pPacket->m_DataSize == sizeof(SERVERBROWSE_FWOK) &&\n\t\tmem_comp(pPacket->m_pData, SERVERBROWSE_FWOK, sizeof(SERVERBROWSE_FWOK)) == 0)\n\t{\n\t\tif(m_RegisterFirst && m_RegisterState != REGISTERSTATE_REGISTERED)\n\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"register\", \"no firewall/nat problems detected\");\n\t\tRegisterNewState(REGISTERSTATE_REGISTERED);\n\t\treturn 1;\n\t}\n\telse if(pPacket->m_DataSize == sizeof(SERVERBROWSE_FWERROR) &&\n\t\tmem_comp(pPacket->m_pData, SERVERBROWSE_FWERROR, sizeof(SERVERBROWSE_FWERROR)) == 0)\n\t{\n\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"register\", \"ERROR: the master server reports that clients can not connect to this server.\");\n\t\tchar aBuf[256];\n\t\tstr_format(aBuf, sizeof(aBuf), \"ERROR: configure your firewall/nat to let through udp on port %d.\", g_Config.m_SvPort);\n\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"register\", aBuf);\n\t\tRegisterNewState(REGISTERSTATE_ERROR);\n\t\treturn 1;\n\t}\n\telse if(pPacket->m_DataSize == sizeof(SERVERBROWSE_COUNT)+2 &&\n\t\tmem_comp(pPacket->m_pData, SERVERBROWSE_COUNT, sizeof(SERVERBROWSE_COUNT)) == 0)\n\t{\n\t\tRegisterGotCount(pPacket);\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "src/engine/server/register.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SERVER_REGISTER_H\n#define ENGINE_SERVER_REGISTER_H\n\nclass CRegister\n{\n\tenum\n\t{\n\t\tREGISTERSTATE_START=0,\n\t\tREGISTERSTATE_UPDATE_ADDRS,\n\t\tREGISTERSTATE_QUERY_COUNT,\n\t\tREGISTERSTATE_HEARTBEAT,\n\t\tREGISTERSTATE_REGISTERED,\n\t\tREGISTERSTATE_ERROR\n\t};\n\n\tstruct CMasterserverInfo\n\t{\n\t\tNETADDR m_Addr;\n\t\tint m_Count;\n\t\tint m_Valid;\n\t\tint64 m_LastSend;\n\t};\n\n\tclass CNetServer *m_pNetServer;\n\tclass IEngineMasterServer *m_pMasterServer;\n\tclass IConsole *m_pConsole;\n\n\tint m_RegisterState;\n\tint64 m_RegisterStateStart;\n\tint m_RegisterFirst;\n\tint m_RegisterCount;\n\n\tCMasterserverInfo m_aMasterserverInfo[IMasterServer::MAX_MASTERSERVERS];\n\tint m_RegisterRegisteredServer;\n\n\tvoid RegisterNewState(int State);\n\tvoid RegisterSendFwcheckresponse(NETADDR *pAddr);\n\tvoid RegisterSendHeartbeat(NETADDR Addr);\n\tvoid RegisterSendCountRequest(NETADDR Addr);\n\tvoid RegisterGotCount(struct CNetChunk *pChunk);\n\npublic:\n\tCRegister();\n\tvoid Init(class CNetServer *pNetServer, class IEngineMasterServer *pMasterServer, class IConsole *pConsole);\n\tvoid RegisterUpdate(int Nettype);\n\tint RegisterProcessPacket(struct CNetChunk *pPacket);\n};\n\n#endif\n"
  },
  {
    "path": "src/engine/server/server.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n\n#include <base/math.h>\n#include <base/system.h>\n\n#include <engine/config.h>\n#include <engine/console.h>\n#include <engine/engine.h>\n#include <engine/map.h>\n#include <engine/masterserver.h>\n#include <engine/server.h>\n#include <engine/storage.h>\n\n#include <engine/shared/compression.h>\n#include <engine/shared/config.h>\n#include <engine/shared/datafile.h>\n#include <engine/shared/demo.h>\n#include <engine/shared/econ.h>\n#include <engine/shared/filecollection.h>\n#include <engine/shared/mapchecker.h>\n#include <engine/shared/netban.h>\n#include <engine/shared/network.h>\n#include <engine/shared/packer.h>\n#include <engine/shared/protocol.h>\n#include <engine/shared/snapshot.h>\n\n#include <mastersrv/mastersrv.h>\n\n#include \"register.h\"\n#include \"server.h\"\n\n#if defined(CONF_FAMILY_WINDOWS)\n\t#define _WIN32_WINNT 0x0501\n\t#define WIN32_LEAN_AND_MEAN\n\t#include <windows.h>\n#endif\n\nstatic const char *StrLtrim(const char *pStr)\n{\n\twhile(*pStr && *pStr >= 0 && *pStr <= 32)\n\t\tpStr++;\n\treturn pStr;\n}\n\nstatic void StrRtrim(char *pStr)\n{\n\tint i = str_length(pStr);\n\twhile(i >= 0)\n\t{\n\t\tif(pStr[i] < 0 || pStr[i] > 32)\n\t\t\tbreak;\n\t\tpStr[i] = 0;\n\t\ti--;\n\t}\n}\n\n\nCSnapIDPool::CSnapIDPool()\n{\n\tReset();\n}\n\nvoid CSnapIDPool::Reset()\n{\n\tfor(int i = 0; i < MAX_IDS; i++)\n\t{\n\t\tm_aIDs[i].m_Next = i+1;\n\t\tm_aIDs[i].m_State = 0;\n\t}\n\n\tm_aIDs[MAX_IDS-1].m_Next = -1;\n\tm_FirstFree = 0;\n\tm_FirstTimed = -1;\n\tm_LastTimed = -1;\n\tm_Usage = 0;\n\tm_InUsage = 0;\n}\n\n\nvoid CSnapIDPool::RemoveFirstTimeout()\n{\n\tint NextTimed = m_aIDs[m_FirstTimed].m_Next;\n\n\t// add it to the free list\n\tm_aIDs[m_FirstTimed].m_Next = m_FirstFree;\n\tm_aIDs[m_FirstTimed].m_State = 0;\n\tm_FirstFree = m_FirstTimed;\n\n\t// remove it from the timed list\n\tm_FirstTimed = NextTimed;\n\tif(m_FirstTimed == -1)\n\t\tm_LastTimed = -1;\n\n\tm_Usage--;\n}\n\nint CSnapIDPool::NewID()\n{\n\tint64 Now = time_get();\n\n\t// process timed ids\n\twhile(m_FirstTimed != -1 && m_aIDs[m_FirstTimed].m_Timeout < Now)\n\t\tRemoveFirstTimeout();\n\n\tint ID = m_FirstFree;\n\tdbg_assert(ID != -1, \"id error\");\n\tif(ID == -1)\n\t\treturn ID;\n\tm_FirstFree = m_aIDs[m_FirstFree].m_Next;\n\tm_aIDs[ID].m_State = 1;\n\tm_Usage++;\n\tm_InUsage++;\n\treturn ID;\n}\n\nvoid CSnapIDPool::TimeoutIDs()\n{\n\t// process timed ids\n\twhile(m_FirstTimed != -1)\n\t\tRemoveFirstTimeout();\n}\n\nvoid CSnapIDPool::FreeID(int ID)\n{\n\tif(ID < 0)\n\t\treturn;\n\tdbg_assert(m_aIDs[ID].m_State == 1, \"id is not alloced\");\n\n\tm_InUsage--;\n\tm_aIDs[ID].m_State = 2;\n\tm_aIDs[ID].m_Timeout = time_get()+time_freq()*5;\n\tm_aIDs[ID].m_Next = -1;\n\n\tif(m_LastTimed != -1)\n\t{\n\t\tm_aIDs[m_LastTimed].m_Next = ID;\n\t\tm_LastTimed = ID;\n\t}\n\telse\n\t{\n\t\tm_FirstTimed = ID;\n\t\tm_LastTimed = ID;\n\t}\n}\n\n\nvoid CServerBan::InitServerBan(IConsole *pConsole, IStorage *pStorage, CServer* pServer)\n{\n\tCNetBan::Init(pConsole, pStorage);\n\n\tm_pServer = pServer;\n\n\t// overwrites base command, todo: improve this\n\tConsole()->Register(\"ban\", \"s?ir\", CFGFLAG_SERVER|CFGFLAG_STORE, ConBanExt, this, \"Ban player with ip/client id for x minutes for any reason\");\n}\n\ntemplate<class T>\nint CServerBan::BanExt(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason)\n{\n\t// validate address\n\tif(Server()->m_RconClientID >= 0 && Server()->m_RconClientID < MAX_CLIENTS &&\n\t\tServer()->m_aClients[Server()->m_RconClientID].m_State != CServer::CClient::STATE_EMPTY)\n\t{\n\t\tif(NetMatch(pData, Server()->m_NetServer.ClientAddr(Server()->m_RconClientID)))\n\t\t{\n\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", \"ban error (you can't ban yourself)\");\n\t\t\treturn -1;\n\t\t}\n\n\t\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t\t{\n\t\t\tif(i == Server()->m_RconClientID || Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY)\n\t\t\t\tcontinue;\n\n\t\t\tif(Server()->m_aClients[i].m_Authed >= Server()->m_RconAuthLevel && NetMatch(pData, Server()->m_NetServer.ClientAddr(i)))\n\t\t\t{\n\t\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", \"ban error (command denied)\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t}\n\telse if(Server()->m_RconClientID == IServer::RCON_CID_VOTE)\n\t{\n\t\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t\t{\n\t\t\tif(Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY)\n\t\t\t\tcontinue;\n\n\t\t\tif(Server()->m_aClients[i].m_Authed != CServer::AUTHED_NO && NetMatch(pData, Server()->m_NetServer.ClientAddr(i)))\n\t\t\t{\n\t\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", \"ban error (command denied)\");\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t}\n\n\tint Result = Ban(pBanPool, pData, Seconds, pReason);\n\tif(Result != 0)\n\t\treturn Result;\n\n\t// drop banned clients\n\ttypename T::CDataType Data = *pData;\n\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t{\n\t\tif(Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY)\n\t\t\tcontinue;\n\n\t\tif(NetMatch(&Data, Server()->m_NetServer.ClientAddr(i)))\n\t\t{\n\t\t\tCNetHash NetHash(&Data);\n\t\t\tchar aBuf[256];\n\t\t\tMakeBanInfo(pBanPool->Find(&Data, &NetHash), aBuf, sizeof(aBuf), MSGTYPE_PLAYER);\n\t\t\tServer()->m_NetServer.Drop(i, aBuf);\n\t\t}\n\t}\n\n\treturn Result;\n}\n\nint CServerBan::BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason)\n{\n\treturn BanExt(&m_BanAddrPool, pAddr, Seconds, pReason);\n}\n\nint CServerBan::BanRange(const CNetRange *pRange, int Seconds, const char *pReason)\n{\n\tif(pRange->IsValid())\n\t\treturn BanExt(&m_BanRangePool, pRange, Seconds, pReason);\n\n\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", \"ban failed (invalid range)\");\n\treturn -1;\n}\n\nvoid CServerBan::ConBanExt(IConsole::IResult *pResult, void *pUser)\n{\n\tCServerBan *pThis = static_cast<CServerBan *>(pUser);\n\n\tconst char *pStr = pResult->GetString(0);\n\tint Minutes = pResult->NumArguments()>1 ? clamp(pResult->GetInteger(1), 0, 44640) : 30;\n\tconst char *pReason = pResult->NumArguments()>2 ? pResult->GetString(2) : \"No reason given\";\n\n\tif(StrAllnum(pStr))\n\t{\n\t\tint ClientID = str_toint(pStr);\n\t\tif(ClientID < 0 || ClientID >= MAX_CLIENTS || pThis->Server()->m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY)\n\t\t\tpThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", \"ban error (invalid client id)\");\n\t\telse\n\t\t\tpThis->BanAddr(pThis->Server()->m_NetServer.ClientAddr(ClientID), Minutes*60, pReason);\n\t}\n\telse\n\t\tConBan(pResult, pUser);\n}\n\n\nvoid CServer::CClient::Reset()\n{\n\t// reset input\n\tfor(int i = 0; i < 200; i++)\n\t\tm_aInputs[i].m_GameTick = -1;\n\tm_CurrentInput = 0;\n\tmem_zero(&m_LatestInput, sizeof(m_LatestInput));\n\n\tm_Snapshots.PurgeAll();\n\tm_LastAckedSnapshot = -1;\n\tm_LastInputTick = -1;\n\tm_SnapRate = CClient::SNAPRATE_INIT;\n\tm_Score = 0;\n\tm_MapChunk = 0;\n}\n\nCServer::CServer() : m_DemoRecorder(&m_SnapshotDelta)\n{\n\tm_TickSpeed = SERVER_TICK_SPEED;\n\n\tm_pGameServer = 0;\n\n\tm_CurrentGameTick = 0;\n\tm_RunServer = 1;\n\n\tm_pCurrentMapData = 0;\n\tm_CurrentMapSize = 0;\n\n\tm_MapReload = 0;\n\n\tm_RconClientID = IServer::RCON_CID_SERV;\n\tm_RconAuthLevel = AUTHED_ADMIN;\n\n\tInit();\n}\n\n\nint CServer::TrySetClientName(int ClientID, const char *pName)\n{\n\tchar aTrimmedName[64];\n\n\t// trim the name\n\tstr_copy(aTrimmedName, StrLtrim(pName), sizeof(aTrimmedName));\n\tStrRtrim(aTrimmedName);\n\n\t// check for empty names\n\tif(!aTrimmedName[0])\n\t\treturn -1;\n\n\t// check if new and old name are the same\n\tif(m_aClients[ClientID].m_aName[0] && str_comp(m_aClients[ClientID].m_aName, aTrimmedName) == 0)\n\t\treturn 0;\n\n\tchar aBuf[256];\n\tstr_format(aBuf, sizeof(aBuf), \"'%s' -> '%s'\", pName, aTrimmedName);\n\tConsole()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"server\", aBuf);\n\tpName = aTrimmedName;\n\n\t// make sure that two clients doesn't have the same name\n\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t\tif(i != ClientID && m_aClients[i].m_State >= CClient::STATE_READY)\n\t\t{\n\t\t\tif(str_comp(pName, m_aClients[i].m_aName) == 0)\n\t\t\t\treturn -1;\n\t\t}\n\n\t// set the client name\n\tstr_copy(m_aClients[ClientID].m_aName, pName, MAX_NAME_LENGTH);\n\treturn 0;\n}\n\n\n\nvoid CServer::SetClientName(int ClientID, const char *pName)\n{\n\tif(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY)\n\t\treturn;\n\n\tif(!pName)\n\t\treturn;\n\n\tchar aCleanName[MAX_NAME_LENGTH];\n\tstr_copy(aCleanName, pName, sizeof(aCleanName));\n\n\t// clear name\n\tfor(char *p = aCleanName; *p; ++p)\n\t{\n\t\tif(*p < 32)\n\t\t\t*p = ' ';\n\t}\n\n\tif(TrySetClientName(ClientID, aCleanName))\n\t{\n\t\t// auto rename\n\t\tfor(int i = 1;; i++)\n\t\t{\n\t\t\tchar aNameTry[MAX_NAME_LENGTH];\n\t\t\tstr_format(aNameTry, sizeof(aCleanName), \"(%d)%s\", i, aCleanName);\n\t\t\tif(TrySetClientName(ClientID, aNameTry) == 0)\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid CServer::SetClientClan(int ClientID, const char *pClan)\n{\n\tif(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY || !pClan)\n\t\treturn;\n\n\tstr_copy(m_aClients[ClientID].m_aClan, pClan, MAX_CLAN_LENGTH);\n}\n\nvoid CServer::SetClientCountry(int ClientID, int Country)\n{\n\tif(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY)\n\t\treturn;\n\n\tm_aClients[ClientID].m_Country = Country;\n}\n\nvoid CServer::SetClientScore(int ClientID, int Score)\n{\n\tif(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY)\n\t\treturn;\n\tm_aClients[ClientID].m_Score = Score;\n}\n\nvoid CServer::Kick(int ClientID, const char *pReason)\n{\n\tif(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CClient::STATE_EMPTY)\n\t{\n\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"server\", \"invalid client id to kick\");\n\t\treturn;\n\t}\n\telse if(m_RconClientID == ClientID)\n\t{\n\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"server\", \"you can't kick yourself\");\n \t\treturn;\n\t}\n\telse if(m_aClients[ClientID].m_Authed > m_RconAuthLevel)\n\t{\n\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"server\", \"kick command denied\");\n \t\treturn;\n\t}\n\n\tm_NetServer.Drop(ClientID, pReason);\n}\n\n/*int CServer::Tick()\n{\n\treturn m_CurrentGameTick;\n}*/\n\nint64 CServer::TickStartTime(int Tick)\n{\n\treturn m_GameStartTime + (time_freq()*Tick)/SERVER_TICK_SPEED;\n}\n\n/*int CServer::TickSpeed()\n{\n\treturn SERVER_TICK_SPEED;\n}*/\n\nint CServer::Init()\n{\n\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t{\n\t\tm_aClients[i].m_State = CClient::STATE_EMPTY;\n\t\tm_aClients[i].m_aName[0] = 0;\n\t\tm_aClients[i].m_aClan[0] = 0;\n\t\tm_aClients[i].m_Country = -1;\n\t\tm_aClients[i].m_Snapshots.Init();\n\t}\n\n\tm_CurrentGameTick = 0;\n\n\treturn 0;\n}\n\nvoid CServer::SetRconCID(int ClientID)\n{\n\tm_RconClientID = ClientID;\n}\n\nbool CServer::IsAuthed(int ClientID)\n{\n\treturn m_aClients[ClientID].m_Authed;\n}\n\nbool CServer::IsBanned(int ClientID)\n{\n\treturn m_ServerBan.IsBanned(m_NetServer.ClientAddr(ClientID), 0, 0);\n}\n\nint CServer::GetClientInfo(int ClientID, CClientInfo *pInfo)\n{\n\tdbg_assert(ClientID >= 0 && ClientID < MAX_CLIENTS, \"client_id is not valid\");\n\tdbg_assert(pInfo != 0, \"info can not be null\");\n\n\tif(m_aClients[ClientID].m_State == CClient::STATE_INGAME)\n\t{\n\t\tpInfo->m_pName = m_aClients[ClientID].m_aName;\n\t\tpInfo->m_Latency = m_aClients[ClientID].m_Latency;\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nvoid CServer::GetClientAddr(int ClientID, char *pAddrStr, int Size)\n{\n\tif(ClientID >= 0 && ClientID < MAX_CLIENTS && m_aClients[ClientID].m_State == CClient::STATE_INGAME)\n\t\tnet_addr_str(m_NetServer.ClientAddr(ClientID), pAddrStr, Size, false);\n}\n\n\nconst char *CServer::ClientName(int ClientID)\n{\n\tif(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY)\n\t\treturn \"(invalid)\";\n\tif(m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME)\n\t\treturn m_aClients[ClientID].m_aName;\n\telse\n\t\treturn \"(connecting)\";\n\n}\n\nconst char *CServer::ClientClan(int ClientID)\n{\n\tif(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY)\n\t\treturn \"\";\n\tif(m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME)\n\t\treturn m_aClients[ClientID].m_aClan;\n\telse\n\t\treturn \"\";\n}\n\nint CServer::ClientCountry(int ClientID)\n{\n\tif(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY)\n\t\treturn -1;\n\tif(m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME)\n\t\treturn m_aClients[ClientID].m_Country;\n\telse\n\t\treturn -1;\n}\n\nbool CServer::ClientIngame(int ClientID)\n{\n\treturn ClientID >= 0 && ClientID < MAX_CLIENTS && m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME;\n}\n\nint CServer::MaxClients() const\n{\n\treturn m_NetServer.MaxClients();\n}\n\nint CServer::SendMsg(CMsgPacker *pMsg, int Flags, int ClientID)\n{\n\tCNetChunk Packet;\n\tif(!pMsg)\n\t\treturn -1;\n\n\tmem_zero(&Packet, sizeof(CNetChunk));\n\tPacket.m_ClientID = ClientID;\n\tPacket.m_pData = pMsg->Data();\n\tPacket.m_DataSize = pMsg->Size();\n\n\tif(Flags&MSGFLAG_VITAL)\n\t\tPacket.m_Flags |= NETSENDFLAG_VITAL;\n\tif(Flags&MSGFLAG_FLUSH)\n\t\tPacket.m_Flags |= NETSENDFLAG_FLUSH;\n\n\t// write message to demo recorder\n\tif(!(Flags&MSGFLAG_NORECORD))\n\t\tm_DemoRecorder.RecordMessage(pMsg->Data(), pMsg->Size());\n\n\tif(!(Flags&MSGFLAG_NOSEND))\n\t{\n\t\tif(ClientID == -1)\n\t\t{\n\t\t\t// broadcast\n\t\t\tint i;\n\t\t\tfor(i = 0; i < MAX_CLIENTS; i++)\n\t\t\t\tif(m_aClients[i].m_State == CClient::STATE_INGAME && !m_aClients[i].m_Quitting)\n\t\t\t\t{\n\t\t\t\t\tPacket.m_ClientID = i;\n\t\t\t\t\tm_NetServer.Send(&Packet);\n\t\t\t\t}\n\t\t}\n\t\telse\n\t\t\tm_NetServer.Send(&Packet);\n\t}\n\treturn 0;\n}\n\nvoid CServer::DoSnapshot()\n{\n\tGameServer()->OnPreSnap();\n\n\t// create snapshot for demo recording\n\tif(m_DemoRecorder.IsRecording())\n\t{\n\t\tchar aData[CSnapshot::MAX_SIZE];\n\t\tint SnapshotSize;\n\n\t\t// build snap and possibly add some messages\n\t\tm_SnapshotBuilder.Init();\n\t\tGameServer()->OnSnap(-1);\n\t\tSnapshotSize = m_SnapshotBuilder.Finish(aData);\n\n\t\t// write snapshot\n\t\tm_DemoRecorder.RecordSnapshot(Tick(), aData, SnapshotSize);\n\t}\n\n\t// create snapshots for all clients\n\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t{\n\t\t// client must be ingame to recive snapshots\n\t\tif(m_aClients[i].m_State != CClient::STATE_INGAME)\n\t\t\tcontinue;\n\n\t\t// this client is trying to recover, don't spam snapshots\n\t\tif(m_aClients[i].m_SnapRate == CClient::SNAPRATE_RECOVER && (Tick()%50) != 0)\n\t\t\tcontinue;\n\n\t\t// this client is trying to recover, don't spam snapshots\n\t\tif(m_aClients[i].m_SnapRate == CClient::SNAPRATE_INIT && (Tick()%10) != 0)\n\t\t\tcontinue;\n\n\t\t{\n\t\t\tchar aData[CSnapshot::MAX_SIZE];\n\t\t\tCSnapshot *pData = (CSnapshot*)aData;\t// Fix compiler warning for strict-aliasing\n\t\t\tchar aDeltaData[CSnapshot::MAX_SIZE];\n\t\t\tchar aCompData[CSnapshot::MAX_SIZE];\n\t\t\tint SnapshotSize;\n\t\t\tint Crc;\n\t\t\tstatic CSnapshot EmptySnap;\n\t\t\tCSnapshot *pDeltashot = &EmptySnap;\n\t\t\tint DeltashotSize;\n\t\t\tint DeltaTick = -1;\n\t\t\tint DeltaSize;\n\n\t\t\tm_SnapshotBuilder.Init();\n\n\t\t\tGameServer()->OnSnap(i);\n\n\t\t\t// finish snapshot\n\t\t\tSnapshotSize = m_SnapshotBuilder.Finish(pData);\n\t\t\tCrc = pData->Crc();\n\n\t\t\t// remove old snapshos\n\t\t\t// keep 3 seconds worth of snapshots\n\t\t\tm_aClients[i].m_Snapshots.PurgeUntil(m_CurrentGameTick-SERVER_TICK_SPEED*3);\n\n\t\t\t// save it the snapshot\n\t\t\tm_aClients[i].m_Snapshots.Add(m_CurrentGameTick, time_get(), SnapshotSize, pData, 0);\n\n\t\t\t// find snapshot that we can preform delta against\n\t\t\tEmptySnap.Clear();\n\n\t\t\t{\n\t\t\t\tDeltashotSize = m_aClients[i].m_Snapshots.Get(m_aClients[i].m_LastAckedSnapshot, 0, &pDeltashot, 0);\n\t\t\t\tif(DeltashotSize >= 0)\n\t\t\t\t\tDeltaTick = m_aClients[i].m_LastAckedSnapshot;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// no acked package found, force client to recover rate\n\t\t\t\t\tif(m_aClients[i].m_SnapRate == CClient::SNAPRATE_FULL)\n\t\t\t\t\t\tm_aClients[i].m_SnapRate = CClient::SNAPRATE_RECOVER;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// create delta\n\t\t\tDeltaSize = m_SnapshotDelta.CreateDelta(pDeltashot, pData, aDeltaData);\n\n\t\t\tif(DeltaSize)\n\t\t\t{\n\t\t\t\t// compress it\n\t\t\t\tint SnapshotSize;\n\t\t\t\tconst int MaxSize = MAX_SNAPSHOT_PACKSIZE;\n\t\t\t\tint NumPackets;\n\n\t\t\t\tSnapshotSize = CVariableInt::Compress(aDeltaData, DeltaSize, aCompData);\n\t\t\t\tNumPackets = (SnapshotSize+MaxSize-1)/MaxSize;\n\n\t\t\t\tfor(int n = 0, Left = SnapshotSize; Left; n++)\n\t\t\t\t{\n\t\t\t\t\tint Chunk = Left < MaxSize ? Left : MaxSize;\n\t\t\t\t\tLeft -= Chunk;\n\n\t\t\t\t\tif(NumPackets == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tCMsgPacker Msg(NETMSG_SNAPSINGLE, true);\n\t\t\t\t\t\tMsg.AddInt(m_CurrentGameTick);\n\t\t\t\t\t\tMsg.AddInt(m_CurrentGameTick-DeltaTick);\n\t\t\t\t\t\tMsg.AddInt(Crc);\n\t\t\t\t\t\tMsg.AddInt(Chunk);\n\t\t\t\t\t\tMsg.AddRaw(&aCompData[n*MaxSize], Chunk);\n\t\t\t\t\t\tSendMsg(&Msg, MSGFLAG_FLUSH, i);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tCMsgPacker Msg(NETMSG_SNAP, true);\n\t\t\t\t\t\tMsg.AddInt(m_CurrentGameTick);\n\t\t\t\t\t\tMsg.AddInt(m_CurrentGameTick-DeltaTick);\n\t\t\t\t\t\tMsg.AddInt(NumPackets);\n\t\t\t\t\t\tMsg.AddInt(n);\n\t\t\t\t\t\tMsg.AddInt(Crc);\n\t\t\t\t\t\tMsg.AddInt(Chunk);\n\t\t\t\t\t\tMsg.AddRaw(&aCompData[n*MaxSize], Chunk);\n\t\t\t\t\t\tSendMsg(&Msg, MSGFLAG_FLUSH, i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tCMsgPacker Msg(NETMSG_SNAPEMPTY, true);\n\t\t\t\tMsg.AddInt(m_CurrentGameTick);\n\t\t\t\tMsg.AddInt(m_CurrentGameTick-DeltaTick);\n\t\t\t\tSendMsg(&Msg, MSGFLAG_FLUSH, i);\n\t\t\t}\n\t\t}\n\t}\n\n\tGameServer()->OnPostSnap();\n}\n\n\nint CServer::NewClientCallback(int ClientID, void *pUser)\n{\n\tCServer *pThis = (CServer *)pUser;\n\tpThis->m_aClients[ClientID].m_State = CClient::STATE_AUTH;\n\tpThis->m_aClients[ClientID].m_aName[0] = 0;\n\tpThis->m_aClients[ClientID].m_aClan[0] = 0;\n\tpThis->m_aClients[ClientID].m_Country = -1;\n\tpThis->m_aClients[ClientID].m_Authed = AUTHED_NO;\n\tpThis->m_aClients[ClientID].m_AuthTries = 0;\n\tpThis->m_aClients[ClientID].m_pRconCmdToSend = 0;\n\tpThis->m_aClients[ClientID].m_Quitting = false;\n\tpThis->m_aClients[ClientID].Reset();\n\treturn 0;\n}\n\nint CServer::DelClientCallback(int ClientID, const char *pReason, void *pUser)\n{\n\tCServer *pThis = (CServer *)pUser;\n\n\tchar aAddrStr[NETADDR_MAXSTRSIZE];\n\tnet_addr_str(pThis->m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true);\n\tchar aBuf[256];\n\tstr_format(aBuf, sizeof(aBuf), \"client dropped. cid=%d addr=%s reason='%s'\", ClientID, aAddrStr, pReason);\n\tpThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"server\", aBuf);\n\n\t// notify the mod about the drop\n\tif(pThis->m_aClients[ClientID].m_State >= CClient::STATE_READY)\n\t{\n\t\tpThis->m_aClients[ClientID].m_Quitting = true;\n\t\tpThis->GameServer()->OnClientDrop(ClientID, pReason);\n\t}\n\n\tpThis->m_aClients[ClientID].m_State = CClient::STATE_EMPTY;\n\tpThis->m_aClients[ClientID].m_aName[0] = 0;\n\tpThis->m_aClients[ClientID].m_aClan[0] = 0;\n\tpThis->m_aClients[ClientID].m_Country = -1;\n\tpThis->m_aClients[ClientID].m_Authed = AUTHED_NO;\n\tpThis->m_aClients[ClientID].m_AuthTries = 0;\n\tpThis->m_aClients[ClientID].m_pRconCmdToSend = 0;\n\tpThis->m_aClients[ClientID].m_Quitting = false;\n\tpThis->m_aClients[ClientID].m_Snapshots.PurgeAll();\n\treturn 0;\n}\n\nvoid CServer::SendMap(int ClientID)\n{\n\tCMsgPacker Msg(NETMSG_MAP_CHANGE, true);\n\tMsg.AddString(GetMapName(), 0);\n\tMsg.AddInt(m_CurrentMapCrc);\n\tMsg.AddInt(m_CurrentMapSize);\n\tMsg.AddInt(m_MapChunksPerRequest);\n\tMsg.AddInt(MAP_CHUNK_SIZE);\n\tSendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID);\n}\n\nvoid CServer::SendConnectionReady(int ClientID)\n{\n\tCMsgPacker Msg(NETMSG_CON_READY, true);\n\tSendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID);\n}\n\nvoid CServer::SendRconLine(int ClientID, const char *pLine)\n{\n\tCMsgPacker Msg(NETMSG_RCON_LINE, true);\n\tMsg.AddString(pLine, 512);\n\tSendMsg(&Msg, MSGFLAG_VITAL, ClientID);\n}\n\nvoid CServer::SendRconLineAuthed(const char *pLine, void *pUser)\n{\n\tCServer *pThis = (CServer *)pUser;\n\tstatic volatile int ReentryGuard = 0;\n\tint i;\n\n\tif(ReentryGuard) return;\n\tReentryGuard++;\n\n\tfor(i = 0; i < MAX_CLIENTS; i++)\n\t{\n\t\tif(pThis->m_aClients[i].m_State != CClient::STATE_EMPTY && pThis->m_aClients[i].m_Authed >= pThis->m_RconAuthLevel)\n\t\t\tpThis->SendRconLine(i, pLine);\n\t}\n\n\tReentryGuard--;\n}\n\nvoid CServer::SendRconCmdAdd(const IConsole::CCommandInfo *pCommandInfo, int ClientID)\n{\n\tCMsgPacker Msg(NETMSG_RCON_CMD_ADD, true);\n\tMsg.AddString(pCommandInfo->m_pName, IConsole::TEMPCMD_NAME_LENGTH);\n\tMsg.AddString(pCommandInfo->m_pHelp, IConsole::TEMPCMD_HELP_LENGTH);\n\tMsg.AddString(pCommandInfo->m_pParams, IConsole::TEMPCMD_PARAMS_LENGTH);\n\tSendMsg(&Msg, MSGFLAG_VITAL, ClientID);\n}\n\nvoid CServer::SendRconCmdRem(const IConsole::CCommandInfo *pCommandInfo, int ClientID)\n{\n\tCMsgPacker Msg(NETMSG_RCON_CMD_REM, true);\n\tMsg.AddString(pCommandInfo->m_pName, 256);\n\tSendMsg(&Msg, MSGFLAG_VITAL, ClientID);\n}\n\nvoid CServer::UpdateClientRconCommands()\n{\n\tint ClientID = Tick() % MAX_CLIENTS;\n\n\tif(m_aClients[ClientID].m_State != CClient::STATE_EMPTY && m_aClients[ClientID].m_Authed)\n\t{\n\t\tint ConsoleAccessLevel = m_aClients[ClientID].m_Authed == AUTHED_ADMIN ? IConsole::ACCESS_LEVEL_ADMIN : IConsole::ACCESS_LEVEL_MOD;\n\t\tfor(int i = 0; i < MAX_RCONCMD_SEND && m_aClients[ClientID].m_pRconCmdToSend; ++i)\n\t\t{\n\t\t\tSendRconCmdAdd(m_aClients[ClientID].m_pRconCmdToSend, ClientID);\n\t\t\tm_aClients[ClientID].m_pRconCmdToSend = m_aClients[ClientID].m_pRconCmdToSend->NextCommandInfo(ConsoleAccessLevel, CFGFLAG_SERVER);\n\t\t}\n\t}\n}\n\nvoid CServer::ProcessClientPacket(CNetChunk *pPacket)\n{\n\tint ClientID = pPacket->m_ClientID;\n\tCUnpacker Unpacker;\n\tUnpacker.Reset(pPacket->m_pData, pPacket->m_DataSize);\n\n\t// unpack msgid and system flag\n\tint Msg = Unpacker.GetInt();\n\tint Sys = Msg&1;\n\tMsg >>= 1;\n\n\tif(Unpacker.Error())\n\t\treturn;\n\n\tif(Sys)\n\t{\n\t\t// system message\n\t\tif(Msg == NETMSG_INFO)\n\t\t{\n\t\t\tif(m_aClients[ClientID].m_State == CClient::STATE_AUTH)\n\t\t\t{\n\t\t\t\tconst char *pVersion = Unpacker.GetString(CUnpacker::SANITIZE_CC);\n\t\t\t\tif(str_comp(pVersion, GameServer()->NetVersion()) != 0)\n\t\t\t\t{\n\t\t\t\t\t// wrong version\n\t\t\t\t\tchar aReason[256];\n\t\t\t\t\tstr_format(aReason, sizeof(aReason), \"Wrong version. Server is running '%s' and client '%s'\", GameServer()->NetVersion(), pVersion);\n\t\t\t\t\tm_NetServer.Drop(ClientID, aReason);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst char *pPassword = Unpacker.GetString(CUnpacker::SANITIZE_CC);\n\t\t\t\tif(g_Config.m_Password[0] != 0 && str_comp(g_Config.m_Password, pPassword) != 0)\n\t\t\t\t{\n\t\t\t\t\t// wrong password\n\t\t\t\t\tm_NetServer.Drop(ClientID, \"Wrong password\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tm_aClients[ClientID].m_State = CClient::STATE_CONNECTING;\n\t\t\t\tSendMap(ClientID);\n\t\t\t}\n\t\t}\n\t\telse if(Msg == NETMSG_REQUEST_MAP_DATA)\n\t\t{\n\t\t\tif(m_aClients[ClientID].m_State == CClient::STATE_CONNECTING)\n\t\t\t{\n\t\t\t\tint ChunkSize = MAP_CHUNK_SIZE;\n\n\t\t\t\t// send map chunks\n\t\t\t\tfor(int i = 0; i < m_MapChunksPerRequest && m_aClients[ClientID].m_MapChunk >= 0; ++i)\n\t\t\t\t{\n\t\t\t\t\tint Chunk = m_aClients[ClientID].m_MapChunk;\n\t\t\t\t\tint Offset = Chunk * ChunkSize;\n\n\t\t\t\t\t// check for last part\n\t\t\t\t\tif(Offset+ChunkSize >= m_CurrentMapSize)\n\t\t\t\t\t{\n\t\t\t\t\t\tChunkSize = m_CurrentMapSize-Offset;\n\t\t\t\t\t\tm_aClients[ClientID].m_MapChunk = -1;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tm_aClients[ClientID].m_MapChunk++;\n\n\t\t\t\t\tCMsgPacker Msg(NETMSG_MAP_DATA, true);\n\t\t\t\t\tMsg.AddRaw(&m_pCurrentMapData[Offset], ChunkSize);\n\t\t\t\t\tSendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID);\n\n\t\t\t\t\tif(g_Config.m_Debug)\n\t\t\t\t\t{\n\t\t\t\t\t\tchar aBuf[64];\n\t\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"sending chunk %d with size %d\", Chunk, ChunkSize);\n\t\t\t\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"server\", aBuf);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if(Msg == NETMSG_READY)\n\t\t{\n\t\t\tif(m_aClients[ClientID].m_State == CClient::STATE_CONNECTING)\n\t\t\t{\n\t\t\t\tchar aAddrStr[NETADDR_MAXSTRSIZE];\n\t\t\t\tnet_addr_str(m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true);\n\n\t\t\t\tchar aBuf[256];\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"player is ready. ClientID=%x addr=%s\", ClientID, aAddrStr);\n\t\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"server\", aBuf);\n\t\t\t\tm_aClients[ClientID].m_State = CClient::STATE_READY;\n\t\t\t\tGameServer()->OnClientConnected(ClientID);\n\t\t\t\tSendConnectionReady(ClientID);\n\t\t\t}\n\t\t}\n\t\telse if(Msg == NETMSG_ENTERGAME)\n\t\t{\n\t\t\tif(m_aClients[ClientID].m_State == CClient::STATE_READY && GameServer()->IsClientReady(ClientID))\n\t\t\t{\n\t\t\t\tchar aAddrStr[NETADDR_MAXSTRSIZE];\n\t\t\t\tnet_addr_str(m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true);\n\n\t\t\t\tchar aBuf[256];\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"player has entered the game. ClientID=%x addr=%s\", ClientID, aAddrStr);\n\t\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"server\", aBuf);\n\t\t\t\tm_aClients[ClientID].m_State = CClient::STATE_INGAME;\n\t\t\t\tGameServer()->OnClientEnter(ClientID);\n\t\t\t}\n\t\t}\n\t\telse if(Msg == NETMSG_INPUT)\n\t\t{\n\t\t\tCClient::CInput *pInput;\n\t\t\tint64 TagTime;\n\n\t\t\tm_aClients[ClientID].m_LastAckedSnapshot = Unpacker.GetInt();\n\t\t\tint IntendedTick = Unpacker.GetInt();\n\t\t\tint Size = Unpacker.GetInt();\n\n\t\t\t// check for errors\n\t\t\tif(Unpacker.Error() || Size/4 > MAX_INPUT_SIZE)\n\t\t\t\treturn;\n\n\t\t\tif(m_aClients[ClientID].m_LastAckedSnapshot > 0)\n\t\t\t\tm_aClients[ClientID].m_SnapRate = CClient::SNAPRATE_FULL;\n\n\t\t\tif(m_aClients[ClientID].m_Snapshots.Get(m_aClients[ClientID].m_LastAckedSnapshot, &TagTime, 0, 0) >= 0)\n\t\t\t\tm_aClients[ClientID].m_Latency = (int)(((time_get()-TagTime)*1000)/time_freq());\n\n\t\t\t// add message to report the input timing\n\t\t\t// skip packets that are old\n\t\t\tif(IntendedTick > m_aClients[ClientID].m_LastInputTick)\n\t\t\t{\n\t\t\t\tint TimeLeft = ((TickStartTime(IntendedTick)-time_get())*1000) / time_freq();\n\n\t\t\t\tCMsgPacker Msg(NETMSG_INPUTTIMING, true);\n\t\t\t\tMsg.AddInt(IntendedTick);\n\t\t\t\tMsg.AddInt(TimeLeft);\n\t\t\t\tSendMsg(&Msg, 0, ClientID);\n\t\t\t}\n\n\t\t\tm_aClients[ClientID].m_LastInputTick = IntendedTick;\n\n\t\t\tpInput = &m_aClients[ClientID].m_aInputs[m_aClients[ClientID].m_CurrentInput];\n\n\t\t\tif(IntendedTick <= Tick())\n\t\t\t\tIntendedTick = Tick()+1;\n\n\t\t\tpInput->m_GameTick = IntendedTick;\n\n\t\t\tfor(int i = 0; i < Size/4; i++)\n\t\t\t\tpInput->m_aData[i] = Unpacker.GetInt();\n\n\t\t\tmem_copy(m_aClients[ClientID].m_LatestInput.m_aData, pInput->m_aData, MAX_INPUT_SIZE*sizeof(int));\n\n\t\t\tm_aClients[ClientID].m_CurrentInput++;\n\t\t\tm_aClients[ClientID].m_CurrentInput %= 200;\n\n\t\t\t// call the mod with the fresh input data\n\t\t\tif(m_aClients[ClientID].m_State == CClient::STATE_INGAME)\n\t\t\t\tGameServer()->OnClientDirectInput(ClientID, m_aClients[ClientID].m_LatestInput.m_aData);\n\t\t}\n\t\telse if(Msg == NETMSG_RCON_CMD)\n\t\t{\n\t\t\tconst char *pCmd = Unpacker.GetString();\n\n\t\t\tif(Unpacker.Error() == 0 && m_aClients[ClientID].m_Authed)\n\t\t\t{\n\t\t\t\tchar aBuf[256];\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"ClientID=%d rcon='%s'\", ClientID, pCmd);\n\t\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"server\", aBuf);\n\t\t\t\tm_RconClientID = ClientID;\n\t\t\t\tm_RconAuthLevel = m_aClients[ClientID].m_Authed;\n\t\t\t\tConsole()->SetAccessLevel(m_aClients[ClientID].m_Authed == AUTHED_ADMIN ? IConsole::ACCESS_LEVEL_ADMIN : IConsole::ACCESS_LEVEL_MOD);\n\t\t\t\tConsole()->ExecuteLineFlag(pCmd, CFGFLAG_SERVER);\n\t\t\t\tConsole()->SetAccessLevel(IConsole::ACCESS_LEVEL_ADMIN);\n\t\t\t\tm_RconClientID = IServer::RCON_CID_SERV;\n\t\t\t\tm_RconAuthLevel = AUTHED_ADMIN;\n\t\t\t}\n\t\t}\n\t\telse if(Msg == NETMSG_RCON_AUTH)\n\t\t{\n\t\t\tconst char *pPw = Unpacker.GetString(CUnpacker::SANITIZE_CC);\n\n\t\t\tif(Unpacker.Error() == 0)\n\t\t\t{\n\t\t\t\tif(g_Config.m_SvRconPassword[0] == 0 && g_Config.m_SvRconModPassword[0] == 0)\n\t\t\t\t{\n\t\t\t\t\tSendRconLine(ClientID, \"No rcon password set on server. Set sv_rcon_password and/or sv_rcon_mod_password to enable the remote console.\");\n\t\t\t\t}\n\t\t\t\telse if(g_Config.m_SvRconPassword[0] && str_comp(pPw, g_Config.m_SvRconPassword) == 0)\n\t\t\t\t{\n\t\t\t\t\tCMsgPacker Msg(NETMSG_RCON_AUTH_ON, true);\n\t\t\t\t\tSendMsg(&Msg, MSGFLAG_VITAL, ClientID);\n\n\t\t\t\t\tm_aClients[ClientID].m_Authed = AUTHED_ADMIN;\n\t\t\t\t\tm_aClients[ClientID].m_pRconCmdToSend = Console()->FirstCommandInfo(IConsole::ACCESS_LEVEL_ADMIN, CFGFLAG_SERVER);\n\t\t\t\t\tSendRconLine(ClientID, \"Admin authentication successful. Full remote console access granted.\");\n\t\t\t\t\tchar aBuf[256];\n\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"ClientID=%d authed (admin)\", ClientID);\n\t\t\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"server\", aBuf);\n\t\t\t\t}\n\t\t\t\telse if(g_Config.m_SvRconModPassword[0] && str_comp(pPw, g_Config.m_SvRconModPassword) == 0)\n\t\t\t\t{\n\t\t\t\t\tCMsgPacker Msg(NETMSG_RCON_AUTH_ON, true);\n\t\t\t\t\tSendMsg(&Msg, MSGFLAG_VITAL, ClientID);\n\n\t\t\t\t\tm_aClients[ClientID].m_Authed = AUTHED_MOD;\n\t\t\t\t\tm_aClients[ClientID].m_pRconCmdToSend = Console()->FirstCommandInfo(IConsole::ACCESS_LEVEL_MOD, CFGFLAG_SERVER);\n\t\t\t\t\tSendRconLine(ClientID, \"Moderator authentication successful. Limited remote console access granted.\");\n\t\t\t\t\tchar aBuf[256];\n\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"ClientID=%d authed (moderator)\", ClientID);\n\t\t\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"server\", aBuf);\n\t\t\t\t}\n\t\t\t\telse if(g_Config.m_SvRconMaxTries)\n\t\t\t\t{\n\t\t\t\t\tm_aClients[ClientID].m_AuthTries++;\n\t\t\t\t\tchar aBuf[128];\n\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"Wrong password %d/%d.\", m_aClients[ClientID].m_AuthTries, g_Config.m_SvRconMaxTries);\n\t\t\t\t\tSendRconLine(ClientID, aBuf);\n\t\t\t\t\tif(m_aClients[ClientID].m_AuthTries >= g_Config.m_SvRconMaxTries)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(!g_Config.m_SvRconBantime)\n\t\t\t\t\t\t\tm_NetServer.Drop(ClientID, \"Too many remote console authentication tries\");\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tm_ServerBan.BanAddr(m_NetServer.ClientAddr(ClientID), g_Config.m_SvRconBantime*60, \"Too many remote console authentication tries\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSendRconLine(ClientID, \"Wrong password.\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if(Msg == NETMSG_PING)\n\t\t{\n\t\t\tCMsgPacker Msg(NETMSG_PING_REPLY, true);\n\t\t\tSendMsg(&Msg, 0, ClientID);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(g_Config.m_Debug)\n\t\t\t{\n\t\t\t\tchar aHex[] = \"0123456789ABCDEF\";\n\t\t\t\tchar aBuf[512];\n\n\t\t\t\tfor(int b = 0; b < pPacket->m_DataSize && b < 32; b++)\n\t\t\t\t{\n\t\t\t\t\taBuf[b*3] = aHex[((const unsigned char *)pPacket->m_pData)[b]>>4];\n\t\t\t\t\taBuf[b*3+1] = aHex[((const unsigned char *)pPacket->m_pData)[b]&0xf];\n\t\t\t\t\taBuf[b*3+2] = ' ';\n\t\t\t\t\taBuf[b*3+3] = 0;\n\t\t\t\t}\n\n\t\t\t\tchar aBufMsg[256];\n\t\t\t\tstr_format(aBufMsg, sizeof(aBufMsg), \"strange message ClientID=%d msg=%d data_size=%d\", ClientID, Msg, pPacket->m_DataSize);\n\t\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"server\", aBufMsg);\n\t\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"server\", aBuf);\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\t// game message\n\t\tif(m_aClients[ClientID].m_State >= CClient::STATE_READY)\n\t\t\tGameServer()->OnMessage(Msg, &Unpacker, ClientID);\n\t}\n}\n\nvoid CServer::SendServerInfo(const NETADDR *pAddr, int Token)\n{\n\tCNetChunk Packet;\n\tCPacker Packer;\n\n\t// count the players\n\tint PlayerCount = 0, ClientCount = 0;\n\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t{\n\t\tif(m_aClients[i].m_State != CClient::STATE_EMPTY)\n\t\t{\n\t\t\tif(GameServer()->IsClientPlayer(i))\n\t\t\t\tPlayerCount++;\n\n\t\t\tClientCount++;\n\t\t}\n\t}\n\n\tPacker.Reset();\n\n\tPacker.AddRaw(SERVERBROWSE_INFO, sizeof(SERVERBROWSE_INFO));\n\tPacker.AddInt(Token);\n\n\tPacker.AddString(GameServer()->Version(), 32);\n\tPacker.AddString(g_Config.m_SvName, 64);\n\tPacker.AddString(g_Config.m_SvHostname, 128);\n\tPacker.AddString(GetMapName(), 32);\n\n\t// gametype\n\tPacker.AddString(GameServer()->GameType(), 16);\n\n\t// flags\n\tint Flag = g_Config.m_Password[0] ? SERVERINFO_FLAG_PASSWORD : 0;\t// password set\n\tPacker.AddInt(Flag);\n\n\tPacker.AddInt(g_Config.m_SvSkillLevel);\t// server skill level\n\tPacker.AddInt(PlayerCount); // num players\n\tPacker.AddInt(m_NetServer.MaxClients()-g_Config.m_SvSpectatorSlots); // max players\n\tPacker.AddInt(ClientCount); // num clients\n\tPacker.AddInt(m_NetServer.MaxClients()); // max clients\n\n\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t{\n\t\tif(m_aClients[i].m_State != CClient::STATE_EMPTY)\n\t\t{\n\t\t\tPacker.AddString(ClientName(i), MAX_NAME_LENGTH); // client name\n\t\t\tPacker.AddString(ClientClan(i), MAX_CLAN_LENGTH); // client clan\n\t\t\tPacker.AddInt(m_aClients[i].m_Country); // client country\n\t\t\tPacker.AddInt(m_aClients[i].m_Score); // client score\n\t\t\tPacker.AddInt(GameServer()->IsClientPlayer(i)?1:0); // is player?\n\t\t}\n\t}\n\n\tPacket.m_ClientID = -1;\n\tPacket.m_Address = *pAddr;\n\tPacket.m_Flags = NETSENDFLAG_CONNLESS;\n\tPacket.m_DataSize = Packer.Size();\n\tPacket.m_pData = Packer.Data();\n\tm_NetServer.Send(&Packet);\n}\n\nvoid CServer::UpdateServerInfo()\n{\n\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t{\n\t\tif(m_aClients[i].m_State != CClient::STATE_EMPTY)\n\t\t\tSendServerInfo(m_NetServer.ClientAddr(i), -1);\n\t}\n}\n\n\nvoid CServer::PumpNetwork()\n{\n\tCNetChunk Packet;\n\n\tm_NetServer.Update();\n\n\t// process packets\n\twhile(m_NetServer.Recv(&Packet))\n\t{\n\t\tif(Packet.m_ClientID == -1)\n\t\t{\n\t\t\t// stateless\n\t\t\tif(!m_Register.RegisterProcessPacket(&Packet))\n\t\t\t{\n\t\t\t\tif(Packet.m_DataSize == sizeof(SERVERBROWSE_GETINFO)+1 &&\n\t\t\t\t\tmem_comp(Packet.m_pData, SERVERBROWSE_GETINFO, sizeof(SERVERBROWSE_GETINFO)) == 0)\n\t\t\t\t{\n\t\t\t\t\tSendServerInfo(&Packet.m_Address, ((unsigned char *)Packet.m_pData)[sizeof(SERVERBROWSE_GETINFO)]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tProcessClientPacket(&Packet);\n\t}\n\n\tm_ServerBan.Update();\n\tm_Econ.Update();\n}\n\nchar *CServer::GetMapName()\n{\n\t// get the name of the map without his path\n\tchar *pMapShortName = &g_Config.m_SvMap[0];\n\tfor(int i = 0; i < str_length(g_Config.m_SvMap)-1; i++)\n\t{\n\t\tif(g_Config.m_SvMap[i] == '/' || g_Config.m_SvMap[i] == '\\\\')\n\t\t\tpMapShortName = &g_Config.m_SvMap[i+1];\n\t}\n\treturn pMapShortName;\n}\n\nint CServer::LoadMap(const char *pMapName)\n{\n\t//DATAFILE *df;\n\tchar aBuf[512];\n\tstr_format(aBuf, sizeof(aBuf), \"maps/%s.map\", pMapName);\n\n\t/*df = datafile_load(buf);\n\tif(!df)\n\t\treturn 0;*/\n\n\t// check for valid standard map\n\tif(!m_MapChecker.ReadAndValidateMap(Storage(), aBuf, IStorage::TYPE_ALL))\n\t{\n\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"mapchecker\", \"invalid standard map\");\n\t\treturn 0;\n\t}\n\n\tif(!m_pMap->Load(aBuf))\n\t\treturn 0;\n\n\t// stop recording when we change map\n\tm_DemoRecorder.Stop();\n\n\t// reinit snapshot ids\n\tm_IDPool.TimeoutIDs();\n\n\t// get the crc of the map\n\tm_CurrentMapCrc = m_pMap->Crc();\n\tchar aBufMsg[256];\n\tstr_format(aBufMsg, sizeof(aBufMsg), \"%s crc is %08x\", aBuf, m_CurrentMapCrc);\n\tConsole()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"server\", aBufMsg);\n\n\tstr_copy(m_aCurrentMap, pMapName, sizeof(m_aCurrentMap));\n\t//map_set(df);\n\n\t// load complete map into memory for download\n\t{\n\t\tIOHANDLE File = Storage()->OpenFile(aBuf, IOFLAG_READ, IStorage::TYPE_ALL);\n\t\tm_CurrentMapSize = (int)io_length(File);\n\t\tif(m_pCurrentMapData)\n\t\t\tmem_free(m_pCurrentMapData);\n\t\tm_pCurrentMapData = (unsigned char *)mem_alloc(m_CurrentMapSize, 1);\n\t\tio_read(File, m_pCurrentMapData, m_CurrentMapSize);\n\t\tio_close(File);\n\t}\n\treturn 1;\n}\n\nvoid CServer::InitRegister(CNetServer *pNetServer, IEngineMasterServer *pMasterServer, IConsole *pConsole)\n{\n\tm_Register.Init(pNetServer, pMasterServer, pConsole);\n}\n\nint CServer::Run()\n{\n\t//\n\tm_PrintCBIndex = Console()->RegisterPrintCallback(g_Config.m_ConsoleOutputLevel, SendRconLineAuthed, this);\n\n\t// load map\n\tif(!LoadMap(g_Config.m_SvMap))\n\t{\n\t\tdbg_msg(\"server\", \"failed to load map. mapname='%s'\", g_Config.m_SvMap);\n\t\treturn -1;\n\t}\n\tm_MapChunksPerRequest = g_Config.m_SvMapDownloadSpeed;\n\n\t// start server\n\tNETADDR BindAddr;\n\tif(g_Config.m_Bindaddr[0] && net_host_lookup(g_Config.m_Bindaddr, &BindAddr, NETTYPE_ALL) == 0)\n\t{\n\t\t// sweet!\n\t\tBindAddr.type = NETTYPE_ALL;\n\t\tBindAddr.port = g_Config.m_SvPort;\n\t}\n\telse\n\t{\n\t\tmem_zero(&BindAddr, sizeof(BindAddr));\n\t\tBindAddr.type = NETTYPE_ALL;\n\t\tBindAddr.port = g_Config.m_SvPort;\n\t}\n\n\tif(!m_NetServer.Open(BindAddr, &m_ServerBan, g_Config.m_SvMaxClients, g_Config.m_SvMaxClientsPerIP, 0))\n\t{\n\t\tdbg_msg(\"server\", \"couldn't open socket. port %d might already be in use\", g_Config.m_SvPort);\n\t\treturn -1;\n\t}\n\n\tm_NetServer.SetCallbacks(NewClientCallback, DelClientCallback, this);\n\n\tm_Econ.Init(Console(), &m_ServerBan);\n\n\tchar aBuf[256];\n\tstr_format(aBuf, sizeof(aBuf), \"server name is '%s'\", g_Config.m_SvName);\n\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"server\", aBuf);\n\n\tGameServer()->OnInit();\n\tstr_format(aBuf, sizeof(aBuf), \"version %s\", GameServer()->NetVersion());\n\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"server\", aBuf);\n\n\t// process pending commands\n\tm_pConsole->StoreCommands(false);\n\n\t// start game\n\t{\n\t\tint64 ReportTime = time_get();\n\t\tint ReportInterval = 3;\n\n\t\tm_Lastheartbeat = 0;\n\t\tm_GameStartTime = time_get();\n\n\t\tif(g_Config.m_Debug)\n\t\t{\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"baseline memory usage %dk\", mem_stats()->allocated/1024);\n\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"server\", aBuf);\n\t\t}\n\n\t\twhile(m_RunServer)\n\t\t{\n\t\t\tint64 t = time_get();\n\t\t\tint NewTicks = 0;\n\n\t\t\t// load new map TODO: don't poll this\n\t\t\tif(str_comp(g_Config.m_SvMap, m_aCurrentMap) != 0 || m_MapReload || m_CurrentGameTick >= 0x6FFFFFFF) //\tforce reload to make sure the ticks stay within a valid range\n\t\t\t{\n\t\t\t\tm_MapReload = 0;\n\n\t\t\t\t// load map\n\t\t\t\tif(LoadMap(g_Config.m_SvMap))\n\t\t\t\t{\n\t\t\t\t\t// new map loaded\n\t\t\t\t\tGameServer()->OnShutdown();\n\n\t\t\t\t\tfor(int c = 0; c < MAX_CLIENTS; c++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(m_aClients[c].m_State <= CClient::STATE_AUTH)\n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\tSendMap(c);\n\t\t\t\t\t\tm_aClients[c].Reset();\n\t\t\t\t\t\tm_aClients[c].m_State = CClient::STATE_CONNECTING;\n\t\t\t\t\t}\n\n\t\t\t\t\tm_GameStartTime = time_get();\n\t\t\t\t\tm_CurrentGameTick = 0;\n\t\t\t\t\tKernel()->ReregisterInterface(GameServer());\n\t\t\t\t\tGameServer()->OnInit();\n\t\t\t\t\tUpdateServerInfo();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"failed to load map. mapname='%s'\", g_Config.m_SvMap);\n\t\t\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"server\", aBuf);\n\t\t\t\t\tstr_copy(g_Config.m_SvMap, m_aCurrentMap, sizeof(g_Config.m_SvMap));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\twhile(t > TickStartTime(m_CurrentGameTick+1))\n\t\t\t{\n\t\t\t\tm_CurrentGameTick++;\n\t\t\t\tNewTicks++;\n\n\t\t\t\t// apply new input\n\t\t\t\tfor(int c = 0; c < MAX_CLIENTS; c++)\n\t\t\t\t{\n\t\t\t\t\tif(m_aClients[c].m_State == CClient::STATE_EMPTY)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tfor(int i = 0; i < 200; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(m_aClients[c].m_aInputs[i].m_GameTick == Tick())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(m_aClients[c].m_State == CClient::STATE_INGAME)\n\t\t\t\t\t\t\t\tGameServer()->OnClientPredictedInput(c, m_aClients[c].m_aInputs[i].m_aData);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tGameServer()->OnTick();\n\t\t\t}\n\n\t\t\t// snap game\n\t\t\tif(NewTicks)\n\t\t\t{\n\t\t\t\tif(g_Config.m_SvHighBandwidth || (m_CurrentGameTick%2) == 0)\n\t\t\t\t\tDoSnapshot();\n\n\t\t\t\tUpdateClientRconCommands();\n\t\t\t}\n\n\t\t\t// master server stuff\n\t\t\tm_Register.RegisterUpdate(m_NetServer.NetType());\n\n\t\t\tPumpNetwork();\n\n\t\t\tif(ReportTime < time_get())\n\t\t\t{\n\t\t\t\tif(g_Config.m_Debug)\n\t\t\t\t{\n\t\t\t\t\t/*\n\t\t\t\t\tstatic NETSTATS prev_stats;\n\t\t\t\t\tNETSTATS stats;\n\t\t\t\t\tnetserver_stats(net, &stats);\n\n\t\t\t\t\tperf_next();\n\n\t\t\t\t\tif(config.dbg_pref)\n\t\t\t\t\t\tperf_dump(&rootscope);\n\n\t\t\t\t\tdbg_msg(\"server\", \"send=%8d recv=%8d\",\n\t\t\t\t\t\t(stats.send_bytes - prev_stats.send_bytes)/reportinterval,\n\t\t\t\t\t\t(stats.recv_bytes - prev_stats.recv_bytes)/reportinterval);\n\n\t\t\t\t\tprev_stats = stats;\n\t\t\t\t\t*/\n\t\t\t\t}\n\n\t\t\t\tReportTime += time_freq()*ReportInterval;\n\t\t\t}\n\n\t\t\t// wait for incomming data\n\t\t\tnet_socket_read_wait(m_NetServer.Socket(), 5);\n\t\t}\n\t}\n\t// disconnect all clients on shutdown\n\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t{\n\t\tif(m_aClients[i].m_State != CClient::STATE_EMPTY)\n\t\t\tm_NetServer.Drop(i, \"Server shutdown\");\n\n\t\tm_Econ.Shutdown();\n\t}\n\n\tGameServer()->OnShutdown();\n\tm_pMap->Unload();\n\n\tif(m_pCurrentMapData)\n\t\tmem_free(m_pCurrentMapData);\n\treturn 0;\n}\n\nvoid CServer::ConKick(IConsole::IResult *pResult, void *pUser)\n{\n\tif(pResult->NumArguments() > 1)\n\t{\n\t\tchar aBuf[128];\n\t\tstr_format(aBuf, sizeof(aBuf), \"Kicked (%s)\", pResult->GetString(1));\n\t\t((CServer *)pUser)->Kick(pResult->GetInteger(0), aBuf);\n\t}\n\telse\n\t\t((CServer *)pUser)->Kick(pResult->GetInteger(0), \"Kicked by console\");\n}\n\nvoid CServer::ConStatus(IConsole::IResult *pResult, void *pUser)\n{\n\tchar aBuf[1024];\n\tchar aAddrStr[NETADDR_MAXSTRSIZE];\n\tCServer* pThis = static_cast<CServer *>(pUser);\n\n\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t{\n\t\tif(pThis->m_aClients[i].m_State != CClient::STATE_EMPTY)\n\t\t{\n\t\t\tnet_addr_str(pThis->m_NetServer.ClientAddr(i), aAddrStr, sizeof(aAddrStr), true);\n\t\t\tif(pThis->m_aClients[i].m_State == CClient::STATE_INGAME)\n\t\t\t{\n\t\t\t\tconst char *pAuthStr = pThis->m_aClients[i].m_Authed == CServer::AUTHED_ADMIN ? \"(Admin)\" :\n\t\t\t\t\t\t\t\t\t\tpThis->m_aClients[i].m_Authed == CServer::AUTHED_MOD ? \"(Mod)\" : \"\";\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"id=%d addr=%s name='%s' score=%d %s\", i, aAddrStr,\n\t\t\t\t\tpThis->m_aClients[i].m_aName, pThis->m_aClients[i].m_Score, pAuthStr);\n\t\t\t}\n\t\t\telse\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"id=%d addr=%s connecting\", i, aAddrStr);\n\t\t\tpThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"Server\", aBuf);\n\t\t}\n\t}\n}\n\nvoid CServer::ConShutdown(IConsole::IResult *pResult, void *pUser)\n{\n\t((CServer *)pUser)->m_RunServer = 0;\n}\n\nvoid CServer::DemoRecorder_HandleAutoStart()\n{\n\tif(g_Config.m_SvAutoDemoRecord)\n\t{\n\t\tm_DemoRecorder.Stop();\n\t\tchar aFilename[128];\n\t\tchar aDate[20];\n\t\tstr_timestamp(aDate, sizeof(aDate));\n\t\tstr_format(aFilename, sizeof(aFilename), \"demos/%s_%s.demo\", \"auto/autorecord\", aDate);\n\t\tm_DemoRecorder.Start(Storage(), m_pConsole, aFilename, GameServer()->NetVersion(), m_aCurrentMap, m_CurrentMapCrc, \"server\");\n\t\tif(g_Config.m_SvAutoDemoMax)\n\t\t{\n\t\t\t// clean up auto recorded demos\n\t\t\tCFileCollection AutoDemos;\n\t\t\tAutoDemos.Init(Storage(), \"demos/server\", \"autorecord\", \".demo\", g_Config.m_SvAutoDemoMax);\n\t\t}\n\t}\n}\n\nbool CServer::DemoRecorder_IsRecording()\n{\n\treturn m_DemoRecorder.IsRecording();\n}\n\nvoid CServer::ConRecord(IConsole::IResult *pResult, void *pUser)\n{\n\tCServer* pServer = (CServer *)pUser;\n\tchar aFilename[128];\n\n\tif(pResult->NumArguments())\n\t\tstr_format(aFilename, sizeof(aFilename), \"demos/%s.demo\", pResult->GetString(0));\n\telse\n\t{\n\t\tchar aDate[20];\n\t\tstr_timestamp(aDate, sizeof(aDate));\n\t\tstr_format(aFilename, sizeof(aFilename), \"demos/demo_%s.demo\", aDate);\n\t}\n\tpServer->m_DemoRecorder.Start(pServer->Storage(), pServer->Console(), aFilename, pServer->GameServer()->NetVersion(), pServer->m_aCurrentMap, pServer->m_CurrentMapCrc, \"server\");\n}\n\nvoid CServer::ConStopRecord(IConsole::IResult *pResult, void *pUser)\n{\n\t((CServer *)pUser)->m_DemoRecorder.Stop();\n}\n\nvoid CServer::ConMapReload(IConsole::IResult *pResult, void *pUser)\n{\n\t((CServer *)pUser)->m_MapReload = 1;\n}\n\nvoid CServer::ConLogout(IConsole::IResult *pResult, void *pUser)\n{\n\tCServer *pServer = (CServer *)pUser;\n\n\tif(pServer->m_RconClientID >= 0 && pServer->m_RconClientID < MAX_CLIENTS &&\n\t\tpServer->m_aClients[pServer->m_RconClientID].m_State != CServer::CClient::STATE_EMPTY)\n\t{\n\t\tCMsgPacker Msg(NETMSG_RCON_AUTH_OFF, true);\n\t\tpServer->SendMsg(&Msg, MSGFLAG_VITAL, pServer->m_RconClientID);\n\n\t\tpServer->m_aClients[pServer->m_RconClientID].m_Authed = AUTHED_NO;\n\t\tpServer->m_aClients[pServer->m_RconClientID].m_AuthTries = 0;\n\t\tpServer->m_aClients[pServer->m_RconClientID].m_pRconCmdToSend = 0;\n\t\tpServer->SendRconLine(pServer->m_RconClientID, \"Logout successful.\");\n\t\tchar aBuf[32];\n\t\tstr_format(aBuf, sizeof(aBuf), \"ClientID=%d logged out\", pServer->m_RconClientID);\n\t\tpServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"server\", aBuf);\n\t}\n}\n\nvoid CServer::ConchainSpecialInfoupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)\n{\n\tpfnCallback(pResult, pCallbackUserData);\n\tif(pResult->NumArguments())\n\t\t((CServer *)pUserData)->UpdateServerInfo();\n}\n\nvoid CServer::ConchainMaxclientsperipUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)\n{\n\tpfnCallback(pResult, pCallbackUserData);\n\tif(pResult->NumArguments())\n\t\t((CServer *)pUserData)->m_NetServer.SetMaxClientsPerIP(pResult->GetInteger(0));\n}\n\nvoid CServer::ConchainModCommandUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)\n{\n\tif(pResult->NumArguments() == 2)\n\t{\n\t\tCServer *pThis = static_cast<CServer *>(pUserData);\n\t\tconst IConsole::CCommandInfo *pInfo = pThis->Console()->GetCommandInfo(pResult->GetString(0), CFGFLAG_SERVER, false);\n\t\tint OldAccessLevel = 0;\n\t\tif(pInfo)\n\t\t\tOldAccessLevel = pInfo->GetAccessLevel();\n\t\tpfnCallback(pResult, pCallbackUserData);\n\t\tif(pInfo && OldAccessLevel != pInfo->GetAccessLevel())\n\t\t{\n\t\t\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t\t\t{\n\t\t\t\tif(pThis->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY || pThis->m_aClients[i].m_Authed != CServer::AUTHED_MOD ||\n\t\t\t\t\t(pThis->m_aClients[i].m_pRconCmdToSend && str_comp(pResult->GetString(0), pThis->m_aClients[i].m_pRconCmdToSend->m_pName) >= 0))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif(OldAccessLevel == IConsole::ACCESS_LEVEL_ADMIN)\n\t\t\t\t\tpThis->SendRconCmdAdd(pInfo, i);\n\t\t\t\telse\n\t\t\t\t\tpThis->SendRconCmdRem(pInfo, i);\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t\tpfnCallback(pResult, pCallbackUserData);\n}\n\nvoid CServer::ConchainConsoleOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)\n{\n\tpfnCallback(pResult, pCallbackUserData);\n\tif(pResult->NumArguments() == 1)\n\t{\n\t\tCServer *pThis = static_cast<CServer *>(pUserData);\n\t\tpThis->Console()->SetPrintOutputLevel(pThis->m_PrintCBIndex, pResult->GetInteger(0));\n\t}\n}\n\nvoid CServer::RegisterCommands()\n{\n\tm_pConsole = Kernel()->RequestInterface<IConsole>();\n\tm_pGameServer = Kernel()->RequestInterface<IGameServer>();\n\tm_pMap = Kernel()->RequestInterface<IEngineMap>();\n\tm_pStorage = Kernel()->RequestInterface<IStorage>();\n\n\t// register console commands\n\tConsole()->Register(\"kick\", \"i?r\", CFGFLAG_SERVER, ConKick, this, \"Kick player with specified id for any reason\");\n\tConsole()->Register(\"status\", \"\", CFGFLAG_SERVER, ConStatus, this, \"List players\");\n\tConsole()->Register(\"shutdown\", \"\", CFGFLAG_SERVER, ConShutdown, this, \"Shut down\");\n\tConsole()->Register(\"logout\", \"\", CFGFLAG_SERVER, ConLogout, this, \"Logout of rcon\");\n\n\tConsole()->Register(\"record\", \"?s\", CFGFLAG_SERVER|CFGFLAG_STORE, ConRecord, this, \"Record to a file\");\n\tConsole()->Register(\"stoprecord\", \"\", CFGFLAG_SERVER, ConStopRecord, this, \"Stop recording\");\n\n\tConsole()->Register(\"reload\", \"\", CFGFLAG_SERVER, ConMapReload, this, \"Reload the map\");\n\n\tConsole()->Chain(\"sv_name\", ConchainSpecialInfoupdate, this);\n\tConsole()->Chain(\"password\", ConchainSpecialInfoupdate, this);\n\n\tConsole()->Chain(\"sv_max_clients_per_ip\", ConchainMaxclientsperipUpdate, this);\n\tConsole()->Chain(\"mod_command\", ConchainModCommandUpdate, this);\n\tConsole()->Chain(\"console_output_level\", ConchainConsoleOutputLevelUpdate, this);\n\n\t// register console commands in sub parts\n\tm_ServerBan.InitServerBan(Console(), Storage(), this);\n\tm_pGameServer->OnConsoleInit();\n}\n\n\nint CServer::SnapNewID()\n{\n\treturn m_IDPool.NewID();\n}\n\nvoid CServer::SnapFreeID(int ID)\n{\n\tm_IDPool.FreeID(ID);\n}\n\n\nvoid *CServer::SnapNewItem(int Type, int ID, int Size)\n{\n\tdbg_assert(Type >= 0 && Type <=0xffff, \"incorrect type\");\n\tdbg_assert(ID >= 0 && ID <=0xffff, \"incorrect id\");\n\treturn ID < 0 ? 0 : m_SnapshotBuilder.NewItem(Type, ID, Size);\n}\n\nvoid CServer::SnapSetStaticsize(int ItemType, int Size)\n{\n\tm_SnapshotDelta.SetStaticsize(ItemType, Size);\n}\n\nstatic CServer *CreateServer() { return new CServer(); }\n\nint main(int argc, const char **argv) // ignore_convention\n{\n#if defined(CONF_FAMILY_WINDOWS)\n\tfor(int i = 1; i < argc; i++) // ignore_convention\n\t{\n\t\tif(str_comp(\"-s\", argv[i]) == 0 || str_comp(\"--silent\", argv[i]) == 0) // ignore_convention\n\t\t{\n\t\t\tShowWindow(GetConsoleWindow(), SW_HIDE);\n\t\t\tbreak;\n\t\t}\n\t}\n#endif\n\n\tCServer *pServer = CreateServer();\n\tIKernel *pKernel = IKernel::Create();\n\n\t// create the components\n\tIEngine *pEngine = CreateEngine(\"Teeworlds\");\n\tIEngineMap *pEngineMap = CreateEngineMap();\n\tIGameServer *pGameServer = CreateGameServer();\n\tIConsole *pConsole = CreateConsole(CFGFLAG_SERVER|CFGFLAG_ECON);\n\tIEngineMasterServer *pEngineMasterServer = CreateEngineMasterServer();\n\tIStorage *pStorage = CreateStorage(\"Teeworlds\", IStorage::STORAGETYPE_SERVER, argc, argv); // ignore_convention\n\tIConfig *pConfig = CreateConfig();\n\n\tpServer->InitRegister(&pServer->m_NetServer, pEngineMasterServer, pConsole);\n\n\t{\n\t\tbool RegisterFail = false;\n\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(pServer); // register as both\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(pEngine);\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineMap*>(pEngineMap)); // register as both\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IMap*>(pEngineMap));\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(pGameServer);\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(pConsole);\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(pStorage);\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(pConfig);\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineMasterServer*>(pEngineMasterServer)); // register as both\n\t\tRegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IMasterServer*>(pEngineMasterServer));\n\n\t\tif(RegisterFail)\n\t\t\treturn -1;\n\t}\n\n\tpEngine->Init();\n\tpConfig->Init();\n\tpEngineMasterServer->Init();\n\tpEngineMasterServer->Load();\n\n\t// register all console commands\n\tpServer->RegisterCommands();\n\n\t// execute autoexec file\n\tpConsole->ExecuteFile(\"autoexec.cfg\");\n\n\t// parse the command line arguments\n\tif(argc > 1) // ignore_convention\n\t\tpConsole->ParseArguments(argc-1, &argv[1]); // ignore_convention\n\n\t// restore empty config strings to their defaults\n\tpConfig->RestoreStrings();\n\n\tpEngine->InitLogfile();\n\n\t// run the server\n\tdbg_msg(\"server\", \"starting...\");\n\tpServer->Run();\n\n\t// free\n\tdelete pServer;\n\tdelete pKernel;\n\tdelete pEngine;\n\tdelete pEngineMap;\n\tdelete pGameServer;\n\tdelete pConsole;\n\tdelete pEngineMasterServer;\n\tdelete pStorage;\n\tdelete pConfig;\n\n\treturn 0;\n}\n\n"
  },
  {
    "path": "src/engine/server/server.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SERVER_SERVER_H\n#define ENGINE_SERVER_SERVER_H\n\n#include <engine/server.h>\n\n\nclass CSnapIDPool\n{\n\tenum\n\t{\n\t\tMAX_IDS = 16*1024,\n\t};\n\n\tclass CID\n\t{\n\tpublic:\n\t\tshort m_Next;\n\t\tshort m_State; // 0 = free, 1 = alloced, 2 = timed\n\t\tint m_Timeout;\n\t};\n\n\tCID m_aIDs[MAX_IDS];\n\n\tint m_FirstFree;\n\tint m_FirstTimed;\n\tint m_LastTimed;\n\tint m_Usage;\n\tint m_InUsage;\n\npublic:\n\n\tCSnapIDPool();\n\n\tvoid Reset();\n\tvoid RemoveFirstTimeout();\n\tint NewID();\n\tvoid TimeoutIDs();\n\tvoid FreeID(int ID);\n};\n\n\nclass CServerBan : public CNetBan\n{\n\tclass CServer *m_pServer;\n\n\ttemplate<class T> int BanExt(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason);\n\npublic:\n\tclass CServer *Server() const { return m_pServer; }\n\n\tvoid InitServerBan(class IConsole *pConsole, class IStorage *pStorage, class CServer* pServer);\n\n\tvirtual int BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason);\n\tvirtual int BanRange(const CNetRange *pRange, int Seconds, const char *pReason);\n\n\tstatic void ConBanExt(class IConsole::IResult *pResult, void *pUser);\n};\n\n\nclass CServer : public IServer\n{\n\tclass IGameServer *m_pGameServer;\n\tclass IConsole *m_pConsole;\n\tclass IStorage *m_pStorage;\npublic:\n\tclass IGameServer *GameServer() { return m_pGameServer; }\n\tclass IConsole *Console() { return m_pConsole; }\n\tclass IStorage *Storage() { return m_pStorage; }\n\n\tenum\n\t{\n\t\tAUTHED_NO=0,\n\t\tAUTHED_MOD,\n\t\tAUTHED_ADMIN,\n\n\t\tMAX_RCONCMD_SEND=16,\n\t};\n\n\tclass CClient\n\t{\n\tpublic:\n\n\t\tenum\n\t\t{\n\t\t\tSTATE_EMPTY = 0,\n\t\t\tSTATE_AUTH,\n\t\t\tSTATE_CONNECTING,\n\t\t\tSTATE_READY,\n\t\t\tSTATE_INGAME,\n\n\t\t\tSNAPRATE_INIT=0,\n\t\t\tSNAPRATE_FULL,\n\t\t\tSNAPRATE_RECOVER\n\t\t};\n\n\t\tclass CInput\n\t\t{\n\t\tpublic:\n\t\t\tint m_aData[MAX_INPUT_SIZE];\n\t\t\tint m_GameTick; // the tick that was chosen for the input\n\t\t};\n\n\t\t// connection state info\n\t\tint m_State;\n\t\tint m_Latency;\n\t\tint m_SnapRate;\n\n\t\tint m_LastAckedSnapshot;\n\t\tint m_LastInputTick;\n\t\tCSnapshotStorage m_Snapshots;\n\n\t\tCInput m_LatestInput;\n\t\tCInput m_aInputs[200]; // TODO: handle input better\n\t\tint m_CurrentInput;\n\n\t\tchar m_aName[MAX_NAME_LENGTH];\n\t\tchar m_aClan[MAX_CLAN_LENGTH];\n\t\tint m_Country;\n\t\tint m_Score;\n\t\tint m_Authed;\n\t\tint m_AuthTries;\n\n\t\tint m_MapChunk;\n\t\tbool m_Quitting;\n\t\tconst IConsole::CCommandInfo *m_pRconCmdToSend;\n\n\t\tvoid Reset();\n\t};\n\n\tCClient m_aClients[MAX_CLIENTS];\n\n\tCSnapshotDelta m_SnapshotDelta;\n\tCSnapshotBuilder m_SnapshotBuilder;\n\tCSnapIDPool m_IDPool;\n\tCNetServer m_NetServer;\n\tCEcon m_Econ;\n\tCServerBan m_ServerBan;\n\n\tIEngineMap *m_pMap;\n\n\tint64 m_GameStartTime;\n\t//int m_CurrentGameTick;\n\tint m_RunServer;\n\tint m_MapReload;\n\tint m_RconClientID;\n\tint m_RconAuthLevel;\n\tint m_PrintCBIndex;\n\n\tint64 m_Lastheartbeat;\n\t//static NETADDR4 master_server;\n\n\t// map\n\tenum\n\t{\n\t\tMAP_CHUNK_SIZE=NET_MAX_PAYLOAD-NET_MAX_CHUNKHEADERSIZE-4, // msg type\n\t};\n\tchar m_aCurrentMap[64];\n\tunsigned m_CurrentMapCrc;\n\tunsigned char *m_pCurrentMapData;\n\tint m_CurrentMapSize;\n\tint m_MapChunksPerRequest;\n\n\tCDemoRecorder m_DemoRecorder;\n\tCRegister m_Register;\n\tCMapChecker m_MapChecker;\n\n\tCServer();\n\n\tint TrySetClientName(int ClientID, const char *pName);\n\n\tvirtual void SetClientName(int ClientID, const char *pName);\n\tvirtual void SetClientClan(int ClientID, char const *pClan);\n\tvirtual void SetClientCountry(int ClientID, int Country);\n\tvirtual void SetClientScore(int ClientID, int Score);\n\n\tvoid Kick(int ClientID, const char *pReason);\n\n\tvoid DemoRecorder_HandleAutoStart();\n\tbool DemoRecorder_IsRecording();\n\n\t//int Tick()\n\tint64 TickStartTime(int Tick);\n\t//int TickSpeed()\n\n\tint Init();\n\n\tvoid SetRconCID(int ClientID);\n\tbool IsAuthed(int ClientID);\n\tbool IsBanned(int ClientID);\n\tint GetClientInfo(int ClientID, CClientInfo *pInfo);\n\tvoid GetClientAddr(int ClientID, char *pAddrStr, int Size);\n\tconst char *ClientName(int ClientID);\n\tconst char *ClientClan(int ClientID);\n\tint ClientCountry(int ClientID);\n\tbool ClientIngame(int ClientID);\n\tint MaxClients() const;\n\n\tvirtual int SendMsg(CMsgPacker *pMsg, int Flags, int ClientID);\n\n\tvoid DoSnapshot();\n\n\tstatic int NewClientCallback(int ClientID, void *pUser);\n\tstatic int DelClientCallback(int ClientID, const char *pReason, void *pUser);\n\n\tvoid SendMap(int ClientID);\n\tvoid SendConnectionReady(int ClientID);\n\tvoid SendRconLine(int ClientID, const char *pLine);\n\tstatic void SendRconLineAuthed(const char *pLine, void *pUser);\n\n\tvoid SendRconCmdAdd(const IConsole::CCommandInfo *pCommandInfo, int ClientID);\n\tvoid SendRconCmdRem(const IConsole::CCommandInfo *pCommandInfo, int ClientID);\n\tvoid UpdateClientRconCommands();\n\n\tvoid ProcessClientPacket(CNetChunk *pPacket);\n\n\tvoid SendServerInfo(const NETADDR *pAddr, int Token);\n\tvoid UpdateServerInfo();\n\n\tvoid PumpNetwork();\n\n\tchar *GetMapName();\n\tint LoadMap(const char *pMapName);\n\n\tvoid InitRegister(CNetServer *pNetServer, IEngineMasterServer *pMasterServer, IConsole *pConsole);\n\tint Run();\n\n\tstatic void ConKick(IConsole::IResult *pResult, void *pUser);\n\tstatic void ConStatus(IConsole::IResult *pResult, void *pUser);\n\tstatic void ConShutdown(IConsole::IResult *pResult, void *pUser);\n\tstatic void ConRecord(IConsole::IResult *pResult, void *pUser);\n\tstatic void ConStopRecord(IConsole::IResult *pResult, void *pUser);\n\tstatic void ConMapReload(IConsole::IResult *pResult, void *pUser);\n\tstatic void ConLogout(IConsole::IResult *pResult, void *pUser);\n\tstatic void ConchainSpecialInfoupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData);\n\tstatic void ConchainMaxclientsperipUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData);\n\tstatic void ConchainModCommandUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData);\n\tstatic void ConchainConsoleOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData);\n\n\tvoid RegisterCommands();\n\n\n\tvirtual int SnapNewID();\n\tvirtual void SnapFreeID(int ID);\n\tvirtual void *SnapNewItem(int Type, int ID, int Size);\n\tvoid SnapSetStaticsize(int ItemType, int Size);\n};\n\n#endif\n"
  },
  {
    "path": "src/engine/server.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SERVER_H\n#define ENGINE_SERVER_H\n#include \"kernel.h\"\n#include \"message.h\"\n\nclass IServer : public IInterface\n{\n\tMACRO_INTERFACE(\"server\", 0)\nprotected:\n\tint m_CurrentGameTick;\n\tint m_TickSpeed;\n\npublic:\n\t/*\n\t\tStructure: CClientInfo\n\t*/\n\tstruct CClientInfo\n\t{\n\t\tconst char *m_pName;\n\t\tint m_Latency;\n\t};\n\n\tint Tick() const { return m_CurrentGameTick; }\n\tint TickSpeed() const { return m_TickSpeed; }\n\n\tvirtual int MaxClients() const = 0;\n\tvirtual const char *ClientName(int ClientID) = 0;\n\tvirtual const char *ClientClan(int ClientID) = 0;\n\tvirtual int ClientCountry(int ClientID) = 0;\n\tvirtual bool ClientIngame(int ClientID) = 0;\n\tvirtual int GetClientInfo(int ClientID, CClientInfo *pInfo) = 0;\n\tvirtual void GetClientAddr(int ClientID, char *pAddrStr, int Size) = 0;\n\n\tvirtual int SendMsg(CMsgPacker *pMsg, int Flags, int ClientID) = 0;\n\n\ttemplate<class T>\n\tint SendPackMsg(T *pMsg, int Flags, int ClientID)\n\t{\n\t\tCMsgPacker Packer(pMsg->MsgID(), false);\n\t\tif(pMsg->Pack(&Packer))\n\t\t\treturn -1;\n\t\treturn SendMsg(&Packer, Flags, ClientID);\n\t}\n\n\tvirtual void SetClientName(int ClientID, char const *pName) = 0;\n\tvirtual void SetClientClan(int ClientID, char const *pClan) = 0;\n\tvirtual void SetClientCountry(int ClientID, int Country) = 0;\n\tvirtual void SetClientScore(int ClientID, int Score) = 0;\n\n\tvirtual int SnapNewID() = 0;\n\tvirtual void SnapFreeID(int ID) = 0;\n\tvirtual void *SnapNewItem(int Type, int ID, int Size) = 0;\n\n\tvirtual void SnapSetStaticsize(int ItemType, int Size) = 0;\n\n\tenum\n\t{\n\t\tRCON_CID_SERV=-1,\n\t\tRCON_CID_VOTE=-2,\n\t};\n\tvirtual void SetRconCID(int ClientID) = 0;\n\tvirtual bool IsAuthed(int ClientID) = 0;\n\tvirtual bool IsBanned(int ClientID) = 0;\n\tvirtual void Kick(int ClientID, const char *pReason) = 0;\n\n\tvirtual void DemoRecorder_HandleAutoStart() = 0;\n\tvirtual bool DemoRecorder_IsRecording() = 0;\n};\n\nclass IGameServer : public IInterface\n{\n\tMACRO_INTERFACE(\"gameserver\", 0)\nprotected:\npublic:\n\tvirtual void OnInit() = 0;\n\tvirtual void OnConsoleInit() = 0;\n\tvirtual void OnShutdown() = 0;\n\n\tvirtual void OnTick() = 0;\n\tvirtual void OnPreSnap() = 0;\n\tvirtual void OnSnap(int ClientID) = 0;\n\tvirtual void OnPostSnap() = 0;\n\n\tvirtual void OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) = 0;\n\n\tvirtual void OnClientConnected(int ClientID) = 0;\n\tvirtual void OnClientEnter(int ClientID) = 0;\n\tvirtual void OnClientDrop(int ClientID, const char *pReason) = 0;\n\tvirtual void OnClientDirectInput(int ClientID, void *pInput) = 0;\n\tvirtual void OnClientPredictedInput(int ClientID, void *pInput) = 0;\n\n\tvirtual bool IsClientReady(int ClientID) = 0;\n\tvirtual bool IsClientPlayer(int ClientID) = 0;\n\n\tvirtual const char *GameType() = 0;\n\tvirtual const char *Version() = 0;\n\tvirtual const char *NetVersion() = 0;\n};\n\nextern IGameServer *CreateGameServer();\n#endif\n"
  },
  {
    "path": "src/engine/serverbrowser.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SERVERBROWSER_H\n#define ENGINE_SERVERBROWSER_H\n\n#include <engine/shared/protocol.h>\n\n#include \"kernel.h\"\n\n/*\n\tStructure: CServerInfo\n*/\nclass CServerInfo\n{\npublic:\n\t/*\n\t\tStructure: CInfoClient\n\t*/\n\tclass CClient\n\t{\n\tpublic:\n\t\tchar m_aName[MAX_NAME_LENGTH];\n\t\tchar m_aClan[MAX_CLAN_LENGTH];\n\t\tint m_Country;\n\t\tint m_Score;\n\t\tbool m_Player;\n\n\t\tint m_FriendState;\n\t};\n\n\t//int m_SortedIndex;\n\tint m_ServerIndex;\n\n\tNETADDR m_NetAddr;\n\n\tint m_QuickSearchHit;\n\tint m_FriendState;\n\n\tint m_MaxClients;\n\tint m_NumClients;\n\tint m_MaxPlayers;\n\tint m_NumPlayers;\n\tint m_Flags;\n\tint m_ServerLevel;\n\tint m_Favorite;\n\tint m_Latency; // in ms\n\tchar m_aGameType[16];\n\tchar m_aName[64];\n\tchar m_aHostname[128];\n\tchar m_aMap[32];\n\tchar m_aVersion[32];\n\tchar m_aAddress[NETADDR_MAXSTRSIZE];\n\tCClient m_aClients[MAX_CLIENTS];\n};\n\nclass IServerBrowser : public IInterface\n{\n\tMACRO_INTERFACE(\"serverbrowser\", 0)\npublic:\n\n\t/* Constants: Server Browser Sorting\n\t\tSORT_NAME - Sort by name.\n\t\tSORT_PING - Sort by ping.\n\t\tSORT_MAP - Sort by map\n\t\tSORT_GAMETYPE - Sort by game type. DM, TDM etc.\n\t\tSORT_NUMPLAYERS - Sort after how many players there are on the server.\n\t*/\n\tenum{\n\t\tSORT_NAME = 0,\n\t\tSORT_PING,\n\t\tSORT_MAP,\n\t\tSORT_GAMETYPE,\n\t\tSORT_NUMPLAYERS,\n\n\t\tQUICK_SERVERNAME=1,\n\t\tQUICK_PLAYER=2,\n\t\tQUICK_MAPNAME=4,\n\n\t\tTYPE_INTERNET = 0,\n\t\tTYPE_LAN = 1,\n\n\t\tFLAG_PASSWORD\t=1,\n\t\tFLAG_PURE\t\t=2,\n\t\tFLAG_PUREMAP\t=4,\n\n\t\tFILTER_EMPTY=32,\n\t\tFILTER_FULL=64,\n\t\tFILTER_SPECTATORS=128,\n\t\tFILTER_FRIENDS=256,\n\t\tFILTER_PW=512,\n\t\tFILTER_FAVORITE=1024,\n\t\tFILTER_COMPAT_VERSION=2048,\n\t\tFILTER_PURE=4096,\n\t\tFILTER_PURE_MAP=8192,\n\t\tFILTER_GAMETYPE_STRICT=16384,\n\t\tFILTER_COUNTRY=32768,\n\t\tFILTER_PING=65536,\n\t};\n\n\tvirtual void Refresh(int Type) = 0;\n\tvirtual bool IsRefreshing() const = 0;\n\tvirtual bool IsRefreshingMasters() const = 0;\n\tvirtual int LoadingProgression() const = 0;\n\n\tvirtual int NumServers() const = 0;\n\tvirtual int NumPlayers() const = 0;\n\n\tvirtual int NumSortedServers(int Index) const = 0;\n\tvirtual int NumSortedPlayers(int Index) const = 0;\n\tvirtual const CServerInfo *SortedGet(int FilterIndex, int Index) const = 0;\n\tvirtual const void *GetID(int FilterIndex, int Index) const = 0;\n\n\tvirtual bool IsFavorite(const NETADDR &Addr) = 0;\t// todo: remove this\n\tvirtual void AddFavorite(const CServerInfo *pEntry) = 0;\n\tvirtual void RemoveFavorite(const CServerInfo *pEntry) = 0;\n\n\tvirtual int AddFilter(int Flag, int Ping, int Country, const char* pGametype, const char* pServerAddress) = 0;\n\tvirtual void SetFilter(int Index, int SortHash, int Ping, int Country, const char* pGametype, const char* pServerAddress) = 0;\n\tvirtual void GetFilter(int Index, int *pSortHash, int *pPing, int *pCountry, char* pGametype, char* pServerAddress) = 0;\n\tvirtual void RemoveFilter(int Index) = 0;\n};\n\n#endif\n"
  },
  {
    "path": "src/engine/shared/compression.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n\n#include \"compression.h\"\n\n// Format: ESDDDDDD EDDDDDDD EDD... Extended, Data, Sign\nunsigned char *CVariableInt::Pack(unsigned char *pDst, int i)\n{\n\t*pDst = (i>>25)&0x40; // set sign bit if i<0\n\ti = i^(i>>31); // if(i<0) i = ~i\n\n\t*pDst |= i&0x3F; // pack 6bit into dst\n\ti >>= 6; // discard 6 bits\n\tif(i)\n\t{\n\t\t*pDst |= 0x80; // set extend bit\n\t\twhile(1)\n\t\t{\n\t\t\tpDst++;\n\t\t\t*pDst = i&(0x7F); // pack 7bit\n\t\t\ti >>= 7; // discard 7 bits\n\t\t\t*pDst |= (i!=0)<<7; // set extend bit (may branch)\n\t\t\tif(!i)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tpDst++;\n\treturn pDst;\n}\n\nconst unsigned char *CVariableInt::Unpack(const unsigned char *pSrc, int *pInOut)\n{\n\tint Sign = (*pSrc>>6)&1;\n\t*pInOut = *pSrc&0x3F;\n\n\tdo\n\t{\n\t\tif(!(*pSrc&0x80)) break;\n\t\tpSrc++;\n\t\t*pInOut |= (*pSrc&(0x7F))<<(6);\n\n\t\tif(!(*pSrc&0x80)) break;\n\t\tpSrc++;\n\t\t*pInOut |= (*pSrc&(0x7F))<<(6+7);\n\n\t\tif(!(*pSrc&0x80)) break;\n\t\tpSrc++;\n\t\t*pInOut |= (*pSrc&(0x7F))<<(6+7+7);\n\n\t\tif(!(*pSrc&0x80)) break;\n\t\tpSrc++;\n\t\t*pInOut |= (*pSrc&(0x7F))<<(6+7+7+7);\n\t} while(0);\n\n\tpSrc++;\n\t*pInOut ^= -Sign; // if(sign) *i = ~(*i)\n\treturn pSrc;\n}\n\n\nlong CVariableInt::Decompress(const void *pSrc_, int Size, void *pDst_)\n{\n\tconst unsigned char *pSrc = (unsigned char *)pSrc_;\n\tconst unsigned char *pEnd = pSrc + Size;\n\tint *pDst = (int *)pDst_;\n\twhile(pSrc < pEnd)\n\t{\n\t\tpSrc = CVariableInt::Unpack(pSrc, pDst);\n\t\tpDst++;\n\t}\n\treturn (long)((unsigned char *)pDst-(unsigned char *)pDst_);\n}\n\nlong CVariableInt::Compress(const void *pSrc_, int Size, void *pDst_)\n{\n\tint *pSrc = (int *)pSrc_;\n\tunsigned char *pDst = (unsigned char *)pDst_;\n\tSize /= 4;\n\twhile(Size)\n\t{\n\t\tpDst = CVariableInt::Pack(pDst, *pSrc);\n\t\tSize--;\n\t\tpSrc++;\n\t}\n\treturn (long)(pDst-(unsigned char *)pDst_);\n}\n\n"
  },
  {
    "path": "src/engine/shared/compression.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SHARED_COMPRESSION_H\n#define ENGINE_SHARED_COMPRESSION_H\n// variable int packing\nclass CVariableInt\n{\npublic:\n\tstatic unsigned char *Pack(unsigned char *pDst, int i);\n\tstatic const unsigned char *Unpack(const unsigned char *pSrc, int *pInOut);\n\tstatic long Compress(const void *pSrc, int Size, void *pDst);\n\tstatic long Decompress(const void *pSrc, int Size, void *pDst);\n};\n#endif\n"
  },
  {
    "path": "src/engine/shared/config.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/config.h>\n#include <engine/storage.h>\n#include <engine/shared/config.h>\n\nCConfiguration g_Config;\n\nclass CConfig : public IConfig\n{\n\tIStorage *m_pStorage;\n\tIOHANDLE m_ConfigFile;\n\n\tstruct CCallback\n\t{\n\t\tSAVECALLBACKFUNC m_pfnFunc;\n\t\tvoid *m_pUserData;\n\t};\n\n\tenum\n\t{\n\t\tMAX_CALLBACKS = 16\n\t};\n\n\tCCallback m_aCallbacks[MAX_CALLBACKS];\n\tint m_NumCallbacks;\n\n\tvoid EscapeParam(char *pDst, const char *pSrc, int size)\n\t{\n\t\tfor(int i = 0; *pSrc && i < size - 1; ++i)\n\t\t{\n\t\t\tif(*pSrc == '\"' || *pSrc == '\\\\') // escape \\ and \"\n\t\t\t\t*pDst++ = '\\\\';\n\t\t\t*pDst++ = *pSrc++;\n\t\t}\n\t\t*pDst = 0;\n\t}\n\npublic:\n\n\tCConfig()\n\t{\n\t\tm_ConfigFile = 0;\n\t\tm_NumCallbacks = 0;\n\t}\n\n\tvirtual void Init()\n\t{\n\t\tm_pStorage = Kernel()->RequestInterface<IStorage>();\n\t\tReset();\n\t}\n\n\tvirtual void Reset()\n\t{\n\t\t#define MACRO_CONFIG_INT(Name,ScriptName,def,min,max,flags,desc) g_Config.m_##Name = def;\n\t\t#define MACRO_CONFIG_STR(Name,ScriptName,len,def,flags,desc) str_copy(g_Config.m_##Name, def, len);\n\n\t\t#include \"config_variables.h\"\n\n\t\t#undef MACRO_CONFIG_INT\n\t\t#undef MACRO_CONFIG_STR\n\t}\n\n\tvirtual void RestoreStrings()\n\t{\n\t\t#define MACRO_CONFIG_INT(Name,ScriptName,def,min,max,flags,desc)\t// nop\n\t\t#define MACRO_CONFIG_STR(Name,ScriptName,len,def,flags,desc) if(!g_Config.m_##Name[0] && def[0]) str_copy(g_Config.m_##Name, def, len);\n\n\t\t#include \"config_variables.h\"\n\n\t\t#undef MACRO_CONFIG_INT\n\t\t#undef MACRO_CONFIG_STR\n\t}\n\n\tvirtual void Save()\n\t{\n\t\tif(!m_pStorage)\n\t\t\treturn;\n\t\tm_ConfigFile = m_pStorage->OpenFile(\"settings.cfg\", IOFLAG_WRITE, IStorage::TYPE_SAVE);\n\n\t\tif(!m_ConfigFile)\n\t\t\treturn;\n\n\t\tchar aLineBuf[1024*2];\n\t\tchar aEscapeBuf[1024*2];\n\n\t\t#define MACRO_CONFIG_INT(Name,ScriptName,def,min,max,flags,desc) if((flags)&CFGFLAG_SAVE){ str_format(aLineBuf, sizeof(aLineBuf), \"%s %i\", #ScriptName, g_Config.m_##Name); WriteLine(aLineBuf); }\n\t\t#define MACRO_CONFIG_STR(Name,ScriptName,len,def,flags,desc) if((flags)&CFGFLAG_SAVE){ EscapeParam(aEscapeBuf, g_Config.m_##Name, sizeof(aEscapeBuf)); str_format(aLineBuf, sizeof(aLineBuf), \"%s \\\"%s\\\"\", #ScriptName, aEscapeBuf); WriteLine(aLineBuf); }\n\n\t\t#include \"config_variables.h\"\n\n\t\t#undef MACRO_CONFIG_INT\n\t\t#undef MACRO_CONFIG_STR\n\n\t\tfor(int i = 0; i < m_NumCallbacks; i++)\n\t\t\tm_aCallbacks[i].m_pfnFunc(this, m_aCallbacks[i].m_pUserData);\n\n\t\tio_close(m_ConfigFile);\n\t\tm_ConfigFile = 0;\n\t}\n\n\tvirtual void RegisterCallback(SAVECALLBACKFUNC pfnFunc, void *pUserData)\n\t{\n\t\tdbg_assert(m_NumCallbacks < MAX_CALLBACKS, \"too many config callbacks\");\n\t\tm_aCallbacks[m_NumCallbacks].m_pfnFunc = pfnFunc;\n\t\tm_aCallbacks[m_NumCallbacks].m_pUserData = pUserData;\n\t\tm_NumCallbacks++;\n\t}\n\n\tvirtual void WriteLine(const char *pLine)\n\t{\n\t\tif(!m_ConfigFile)\n\t\t\treturn;\n\t\tio_write(m_ConfigFile, pLine, str_length(pLine));\n\t\tio_write_newline(m_ConfigFile);\n\t}\n};\n\nIConfig *CreateConfig() { return new CConfig; }\n"
  },
  {
    "path": "src/engine/shared/config.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SHARED_CONFIG_H\n#define ENGINE_SHARED_CONFIG_H\n\nstruct CConfiguration\n{\n\t#define MACRO_CONFIG_INT(Name,ScriptName,Def,Min,Max,Save,Desc) int m_##Name;\n\t#define MACRO_CONFIG_STR(Name,ScriptName,Len,Def,Save,Desc) char m_##Name[Len]; // Flawfinder: ignore\n\t#include \"config_variables.h\"\n\t#undef MACRO_CONFIG_INT\n\t#undef MACRO_CONFIG_STR\n};\n\nextern CConfiguration g_Config;\n\nenum\n{\n\tCFGFLAG_SAVE=1,\n\tCFGFLAG_CLIENT=2,\n\tCFGFLAG_SERVER=4,\n\tCFGFLAG_STORE=8,\n\tCFGFLAG_MASTER=16,\n\tCFGFLAG_ECON=32,\n};\n\n#endif\n"
  },
  {
    "path": "src/engine/shared/config_variables.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SHARED_CONFIG_VARIABLES_H\n#define ENGINE_SHARED_CONFIG_VARIABLES_H\n#undef ENGINE_SHARED_CONFIG_VARIABLES_H // this file will be included several times\n\n// TODO: remove this\n#include \"././game/variables.h\"\n\n\nMACRO_CONFIG_STR(PlayerName, player_name, 16, \"nameless tee\", CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Name of the player\")\nMACRO_CONFIG_STR(PlayerClan, player_clan, 12, \"\", CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Clan of the player\")\nMACRO_CONFIG_INT(PlayerCountry, player_country, -1, -1, 1000, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Country of the player\")\nMACRO_CONFIG_STR(Password, password, 32, \"\", CFGFLAG_CLIENT|CFGFLAG_SERVER, \"Password to the server\")\nMACRO_CONFIG_STR(Logfile, logfile, 128, \"\", CFGFLAG_SAVE|CFGFLAG_CLIENT|CFGFLAG_SERVER, \"Filename to log all output to\")\nMACRO_CONFIG_INT(ConsoleOutputLevel, console_output_level, 0, 0, 2, CFGFLAG_CLIENT|CFGFLAG_SERVER, \"Adjusts the amount of information in the console\")\n\nMACRO_CONFIG_INT(ClCpuThrottle, cl_cpu_throttle, 0, 0, 100, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"\")\nMACRO_CONFIG_INT(ClEditor, cl_editor, 0, 0, 1, CFGFLAG_CLIENT, \"\")\nMACRO_CONFIG_INT(ClLoadCountryFlags, cl_load_country_flags, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Load and show country flags\")\n\nMACRO_CONFIG_INT(ClAutoDemoRecord, cl_auto_demo_record, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Automatically record demos\")\nMACRO_CONFIG_INT(ClAutoDemoMax, cl_auto_demo_max, 10, 0, 1000, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Maximum number of automatically recorded demos (0 = no limit)\")\nMACRO_CONFIG_INT(ClAutoScreenshot, cl_auto_screenshot, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Automatically take game over screenshot\")\nMACRO_CONFIG_INT(ClAutoScreenshotMax, cl_auto_screenshot_max, 10, 0, 1000, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Maximum number of automatically created screenshots (0 = no limit)\")\n\nMACRO_CONFIG_INT(ClEventthread, cl_eventthread, 0, 0, 1, CFGFLAG_CLIENT, \"Enables the usage of a thread to pump the events\")\n\nMACRO_CONFIG_INT(InpGrab, inp_grab, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Use forceful input grabbing method\")\n\nMACRO_CONFIG_STR(BrFilterString, br_filter_string, 25, \"\", CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Server browser filtering string\")\nMACRO_CONFIG_INT(BrFilterFull, br_filter_full, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Filter out full server in browser\")\nMACRO_CONFIG_INT(BrFilterEmpty, br_filter_empty, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Filter out empty server in browser\")\nMACRO_CONFIG_INT(BrFilterSpectators, br_filter_spectators, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Filter out spectators from player numbers\")\nMACRO_CONFIG_INT(BrFilterFriends, br_filter_friends, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Filter out servers with no friends\")\nMACRO_CONFIG_INT(BrFilterCountry, br_filter_country, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Filter out servers with non-matching player country\")\nMACRO_CONFIG_INT(BrFilterCountryIndex, br_filter_country_index, -1, -1, 999, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Player country to filter by in the server browser\")\nMACRO_CONFIG_INT(BrFilterPw, br_filter_pw, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Filter out password protected servers in browser\")\nMACRO_CONFIG_INT(BrFilterPing, br_filter_ping, 999, 0, 999, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Ping to filter by in the server browser\")\nMACRO_CONFIG_STR(BrFilterGametype, br_filter_gametype, 128, \"\", CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Game types to filter\")\nMACRO_CONFIG_INT(BrFilterGametypeStrict, br_filter_gametype_strict, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Strict gametype filter\")\nMACRO_CONFIG_STR(BrFilterServerAddress, br_filter_serveraddress, 128, \"\", CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Server address to filter\")\nMACRO_CONFIG_INT(BrFilterPure, br_filter_pure, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Filter out non-standard servers in browser\")\nMACRO_CONFIG_INT(BrFilterPureMap, br_filter_pure_map, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Filter out non-standard maps in browser\")\nMACRO_CONFIG_INT(BrFilterCompatversion, br_filter_compatversion, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Filter out non-compatible servers in browser\")\n\nMACRO_CONFIG_INT(BrSort, br_sort, 0, 0, 256, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"\")\nMACRO_CONFIG_INT(BrSortOrder, br_sort_order, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"\")\nMACRO_CONFIG_INT(BrMaxRequests, br_max_requests, 25, 0, 1000, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Number of requests to use when refreshing server browser\")\n\nMACRO_CONFIG_INT(SndBufferSize, snd_buffer_size, 512, 128, 32768, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Sound buffer size\")\nMACRO_CONFIG_INT(SndRate, snd_rate, 48000, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Sound mixing rate\")\nMACRO_CONFIG_INT(SndEnable, snd_enable, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Sound enable\")\nMACRO_CONFIG_INT(SndMusic, snd_enable_music, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Play background music\")\nMACRO_CONFIG_INT(SndVolume, snd_volume, 100, 0, 100, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Sound volume\")\nMACRO_CONFIG_INT(SndDevice, snd_device, -1, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"(deprecated) Sound device to use\")\n\nMACRO_CONFIG_INT(SndNonactiveMute, snd_nonactive_mute, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"\")\n\nMACRO_CONFIG_INT(GfxScreenWidth, gfx_screen_width, 0, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Screen resolution width\")\nMACRO_CONFIG_INT(GfxScreenHeight, gfx_screen_height, 0, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Screen resolution height\")\nMACRO_CONFIG_INT(GfxBorderless, gfx_borderless, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Borderless window (not to be used with fullscreen)\")\nMACRO_CONFIG_INT(GfxFullscreen, gfx_fullscreen, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Fullscreen\")\nMACRO_CONFIG_INT(GfxAlphabits, gfx_alphabits, 0, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Alpha bits for framebuffer (fullscreen only)\")\nMACRO_CONFIG_INT(GfxClear, gfx_clear, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Clear screen before rendering\")\nMACRO_CONFIG_INT(GfxVsync, gfx_vsync, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Vertical sync\")\nMACRO_CONFIG_INT(GfxDisplayAllModes, gfx_display_all_modes, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"\")\nMACRO_CONFIG_INT(GfxTextureCompression, gfx_texture_compression, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Use texture compression\")\nMACRO_CONFIG_INT(GfxHighDetail, gfx_high_detail, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"High detail\")\nMACRO_CONFIG_INT(GfxTextureQuality, gfx_texture_quality, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"\")\nMACRO_CONFIG_INT(GfxFsaaSamples, gfx_fsaa_samples, 0, 0, 16, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"FSAA Samples\")\nMACRO_CONFIG_INT(GfxRefreshRate, gfx_refresh_rate, 0, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Screen refresh rate\")\nMACRO_CONFIG_INT(GfxFinish, gfx_finish, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"\")\nMACRO_CONFIG_INT(GfxAsyncRender, gfx_asyncrender, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Do rendering async from the the update\")\n\nMACRO_CONFIG_INT(InpMousesens, inp_mousesens, 100, 5, 100000, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Mouse sensitivity\")\n\nMACRO_CONFIG_STR(SvName, sv_name, 128, \"unnamed server\", CFGFLAG_SERVER, \"Server name\")\nMACRO_CONFIG_STR(SvHostname, sv_hostname, 128, \"\", CFGFLAG_SERVER, \"Server hostname\")\nMACRO_CONFIG_STR(Bindaddr, bindaddr, 128, \"\", CFGFLAG_CLIENT|CFGFLAG_SERVER|CFGFLAG_MASTER, \"Address to bind the client/server to\")\nMACRO_CONFIG_INT(SvPort, sv_port, 8303, 0, 0, CFGFLAG_SERVER, \"Port to use for the server\")\nMACRO_CONFIG_INT(SvExternalPort, sv_external_port, 0, 0, 0, CFGFLAG_SERVER, \"External port to report to the master servers\")\nMACRO_CONFIG_STR(SvMap, sv_map, 128, \"dm1\", CFGFLAG_SERVER, \"Map to use on the server\")\nMACRO_CONFIG_INT(SvMaxClients, sv_max_clients, 8, 1, MAX_CLIENTS, CFGFLAG_SERVER, \"Maximum number of clients that are allowed on a server\")\nMACRO_CONFIG_INT(SvMaxClientsPerIP, sv_max_clients_per_ip, 4, 1, MAX_CLIENTS, CFGFLAG_SERVER, \"Maximum number of clients with the same IP that can connect to the server\")\nMACRO_CONFIG_INT(SvMapDownloadSpeed, sv_map_download_speed, 2, 1, 16, CFGFLAG_SERVER, \"Number of map data packages a client gets on each request\")\nMACRO_CONFIG_INT(SvHighBandwidth, sv_high_bandwidth, 0, 0, 1, CFGFLAG_SERVER, \"Use high bandwidth mode. Doubles the bandwidth required for the server. LAN use only\")\nMACRO_CONFIG_INT(SvRegister, sv_register, 1, 0, 1, CFGFLAG_SERVER, \"Register server with master server for public listing\")\nMACRO_CONFIG_STR(SvRconPassword, sv_rcon_password, 32, \"\", CFGFLAG_SERVER, \"Remote console password (full access)\")\nMACRO_CONFIG_STR(SvRconModPassword, sv_rcon_mod_password, 32, \"\", CFGFLAG_SERVER, \"Remote console password for moderators (limited access)\")\nMACRO_CONFIG_INT(SvRconMaxTries, sv_rcon_max_tries, 3, 0, 100, CFGFLAG_SERVER, \"Maximum number of tries for remote console authentication\")\nMACRO_CONFIG_INT(SvRconBantime, sv_rcon_bantime, 5, 0, 1440, CFGFLAG_SERVER, \"The time a client gets banned if remote console authentication fails. 0 makes it just use kick\")\nMACRO_CONFIG_INT(SvAutoDemoRecord, sv_auto_demo_record, 0, 0, 1, CFGFLAG_SERVER, \"Automatically record demos\")\nMACRO_CONFIG_INT(SvAutoDemoMax, sv_auto_demo_max, 10, 0, 1000, CFGFLAG_SERVER, \"Maximum number of automatically recorded demos (0 = no limit)\")\n\nMACRO_CONFIG_STR(EcBindaddr, ec_bindaddr, 128, \"localhost\", CFGFLAG_ECON, \"Address to bind the external console to. Anything but 'localhost' is dangerous\")\nMACRO_CONFIG_INT(EcPort, ec_port, 0, 0, 0, CFGFLAG_ECON, \"Port to use for the external console\")\nMACRO_CONFIG_STR(EcPassword, ec_password, 32, \"\", CFGFLAG_ECON, \"External console password\")\nMACRO_CONFIG_INT(EcBantime, ec_bantime, 0, 0, 1440, CFGFLAG_ECON, \"The time a client gets banned if econ authentication fails. 0 just closes the connection\")\nMACRO_CONFIG_INT(EcAuthTimeout, ec_auth_timeout, 30, 1, 120, CFGFLAG_ECON, \"Time in seconds before the the econ authentification times out\")\nMACRO_CONFIG_INT(EcOutputLevel, ec_output_level, 1, 0, 2, CFGFLAG_ECON, \"Adjusts the amount of information in the external console\")\n\nMACRO_CONFIG_INT(Debug, debug, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SERVER, \"Debug mode\")\nMACRO_CONFIG_INT(DbgStress, dbg_stress, 0, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SERVER, \"Stress systems\")\nMACRO_CONFIG_INT(DbgStressNetwork, dbg_stress_network, 0, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SERVER, \"Stress network\")\nMACRO_CONFIG_INT(DbgPref, dbg_pref, 0, 0, 1, CFGFLAG_SERVER, \"Performance outputs\")\nMACRO_CONFIG_INT(DbgGraphs, dbg_graphs, 0, 0, 1, CFGFLAG_CLIENT, \"Performance graphs\")\nMACRO_CONFIG_INT(DbgHitch, dbg_hitch, 0, 0, 0, CFGFLAG_SERVER, \"Hitch warnings\")\nMACRO_CONFIG_STR(DbgStressServer, dbg_stress_server, 32, \"localhost\", CFGFLAG_CLIENT, \"Server to stress\")\nMACRO_CONFIG_INT(DbgResizable, dbg_resizable, 0, 0, 0, CFGFLAG_CLIENT, \"Enables window resizing\")\n#endif\n"
  },
  {
    "path": "src/engine/shared/console.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <new>\n\n#include <base/math.h>\n#include <base/system.h>\n\n#include <engine/storage.h>\n#include <engine/shared/protocol.h>\n\n#include \"config.h\"\n#include \"console.h\"\n#include \"linereader.h\"\n\n// todo: rework this\n\nconst char *CConsole::CResult::GetString(unsigned Index)\n{\n\tif (Index >= m_NumArgs)\n\t\treturn \"\";\n\treturn m_apArgs[Index];\n}\n\nint CConsole::CResult::GetInteger(unsigned Index)\n{\n\tif (Index >= m_NumArgs)\n\t\treturn 0;\n\treturn str_toint(m_apArgs[Index]);\n}\n\nfloat CConsole::CResult::GetFloat(unsigned Index)\n{\n\tif (Index >= m_NumArgs)\n\t\treturn 0.0f;\n\treturn str_tofloat(m_apArgs[Index]);\n}\n\nconst IConsole::CCommandInfo *CConsole::CCommand::NextCommandInfo(int AccessLevel, int FlagMask) const\n{\n\tconst CCommand *pInfo = m_pNext;\n\twhile(pInfo)\n\t{\n\t\tif(pInfo->m_Flags&FlagMask && pInfo->m_AccessLevel >= AccessLevel)\n\t\t\tbreak;\n\t\tpInfo = pInfo->m_pNext;\n\t}\n\treturn pInfo;\n}\n\nconst IConsole::CCommandInfo *CConsole::FirstCommandInfo(int AccessLevel, int FlagMask) const\n{\n\tfor(const CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext)\n\t{\n\t\tif(pCommand->m_Flags&FlagMask && pCommand->GetAccessLevel() >= AccessLevel)\n\t\t\treturn pCommand;\n\t}\n\n\treturn 0;\n}\n\n// the maximum number of tokens occurs in a string of length CONSOLE_MAX_STR_LENGTH with tokens size 1 separated by single spaces\n\n\nint CConsole::ParseStart(CResult *pResult, const char *pString, int Length)\n{\n\tchar *pStr;\n\tint Len = sizeof(pResult->m_aStringStorage);\n\tif(Length < Len)\n\t\tLen = Length;\n\n\tstr_copy(pResult->m_aStringStorage, pString, Len);\n\tpStr = pResult->m_aStringStorage;\n\n\t// get command\n\tpStr = str_skip_whitespaces(pStr);\n\tpResult->m_pCommand = pStr;\n\tpStr = str_skip_to_whitespace(pStr);\n\n\tif(*pStr)\n\t{\n\t\tpStr[0] = 0;\n\t\tpStr++;\n\t}\n\n\tpResult->m_pArgsStart = pStr;\n\treturn 0;\n}\n\nint CConsole::ParseArgs(CResult *pResult, const char *pFormat)\n{\n\tchar Command;\n\tchar *pStr;\n\tint Optional = 0;\n\tint Error = 0;\n\n\tpStr = pResult->m_pArgsStart;\n\n\twhile(1)\n\t{\n\t\t// fetch command\n\t\tCommand = *pFormat;\n\t\tpFormat++;\n\n\t\tif(!Command)\n\t\t\tbreak;\n\n\t\tif(Command == '?')\n\t\t\tOptional = 1;\n\t\telse\n\t\t{\n\t\t\tpStr = str_skip_whitespaces(pStr);\n\n\t\t\tif(!(*pStr)) // error, non optional command needs value\n\t\t\t{\n\t\t\t\tif(!Optional)\n\t\t\t\t\tError = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// add token\n\t\t\tif(*pStr == '\"')\n\t\t\t{\n\t\t\t\tchar *pDst;\n\t\t\t\tpStr++;\n\t\t\t\tpResult->AddArgument(pStr);\n\n\t\t\t\tpDst = pStr; // we might have to process escape data\n\t\t\t\twhile(1)\n\t\t\t\t{\n\t\t\t\t\tif(pStr[0] == '\"')\n\t\t\t\t\t\tbreak;\n\t\t\t\t\telse if(pStr[0] == '\\\\')\n\t\t\t\t\t{\n\t\t\t\t\t\tif(pStr[1] == '\\\\')\n\t\t\t\t\t\t\tpStr++; // skip due to escape\n\t\t\t\t\t\telse if(pStr[1] == '\"')\n\t\t\t\t\t\t\tpStr++; // skip due to escape\n\t\t\t\t\t}\n\t\t\t\t\telse if(pStr[0] == 0)\n\t\t\t\t\t\treturn 1; // return error\n\n\t\t\t\t\t*pDst = *pStr;\n\t\t\t\t\tpDst++;\n\t\t\t\t\tpStr++;\n\t\t\t\t}\n\n\t\t\t\t// write null termination\n\t\t\t\t*pDst = 0;\n\n\n\t\t\t\tpStr++;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tpResult->AddArgument(pStr);\n\n\t\t\t\tif(Command == 'r') // rest of the string\n\t\t\t\t\tbreak;\n\t\t\t\telse if(Command == 'i') // validate int\n\t\t\t\t\tpStr = str_skip_to_whitespace(pStr);\n\t\t\t\telse if(Command == 'f') // validate float\n\t\t\t\t\tpStr = str_skip_to_whitespace(pStr);\n\t\t\t\telse if(Command == 's') // validate string\n\t\t\t\t\tpStr = str_skip_to_whitespace(pStr);\n\n\t\t\t\tif(pStr[0] != 0) // check for end of string\n\t\t\t\t{\n\t\t\t\t\tpStr[0] = 0;\n\t\t\t\t\tpStr++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn Error;\n}\n\nint CConsole::RegisterPrintCallback(int OutputLevel, FPrintCallback pfnPrintCallback, void *pUserData)\n{\n\tif(m_NumPrintCB == MAX_PRINT_CB)\n\t\treturn -1;\n\n\tm_aPrintCB[m_NumPrintCB].m_OutputLevel = clamp(OutputLevel, (int)(OUTPUT_LEVEL_STANDARD), (int)(OUTPUT_LEVEL_DEBUG));\n\tm_aPrintCB[m_NumPrintCB].m_pfnPrintCallback = pfnPrintCallback;\n\tm_aPrintCB[m_NumPrintCB].m_pPrintCallbackUserdata = pUserData;\n\treturn m_NumPrintCB++;\n}\n\nvoid CConsole::SetPrintOutputLevel(int Index, int OutputLevel)\n{\n\tif(Index >= 0 && Index < MAX_PRINT_CB)\n\t\tm_aPrintCB[Index].m_OutputLevel = clamp(OutputLevel, (int)(OUTPUT_LEVEL_STANDARD), (int)(OUTPUT_LEVEL_DEBUG));\n}\n\nvoid CConsole::Print(int Level, const char *pFrom, const char *pStr)\n{\n\tdbg_msg(pFrom ,\"%s\", pStr);\n\tfor(int i = 0; i < m_NumPrintCB; ++i)\n\t{\n\t\tif(Level <= m_aPrintCB[i].m_OutputLevel && m_aPrintCB[i].m_pfnPrintCallback)\n\t\t{\n\t\t\tchar aBuf[1024];\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"[%s]: %s\", pFrom, pStr);\n\t\t\tm_aPrintCB[i].m_pfnPrintCallback(aBuf, m_aPrintCB[i].m_pPrintCallbackUserdata);\n\t\t}\n\t}\n}\n\nbool CConsole::LineIsValid(const char *pStr)\n{\n\tif(!pStr || *pStr == 0)\n\t\treturn false;\n\n\tdo\n\t{\n\t\tCResult Result;\n\t\tconst char *pEnd = pStr;\n\t\tconst char *pNextPart = 0;\n\t\tint InString = 0;\n\n\t\twhile(*pEnd)\n\t\t{\n\t\t\tif(*pEnd == '\"')\n\t\t\t\tInString ^= 1;\n\t\t\telse if(*pEnd == '\\\\') // escape sequences\n\t\t\t{\n\t\t\t\tif(pEnd[1] == '\"')\n\t\t\t\t\tpEnd++;\n\t\t\t}\n\t\t\telse if(!InString)\n\t\t\t{\n\t\t\t\tif(*pEnd == ';') // command separator\n\t\t\t\t{\n\t\t\t\t\tpNextPart = pEnd+1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse if(*pEnd == '#') // comment, no need to do anything more\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tpEnd++;\n\t\t}\n\n\t\tif(ParseStart(&Result, pStr, (pEnd-pStr) + 1) != 0)\n\t\t\treturn false;\n\n\t\tCCommand *pCommand = FindCommand(Result.m_pCommand, m_FlagMask);\n\t\tif(!pCommand || ParseArgs(&Result, pCommand->m_pParams))\n\t\t\treturn false;\n\n\t\tpStr = pNextPart;\n\t}\n\twhile(pStr && *pStr);\n\n\treturn true;\n}\n\nvoid CConsole::ExecuteLineStroked(int Stroke, const char *pStr)\n{\n\twhile(pStr && *pStr)\n\t{\n\t\tCResult Result;\n\t\tconst char *pEnd = pStr;\n\t\tconst char *pNextPart = 0;\n\t\tint InString = 0;\n\n\t\twhile(*pEnd)\n\t\t{\n\t\t\tif(*pEnd == '\"')\n\t\t\t\tInString ^= 1;\n\t\t\telse if(*pEnd == '\\\\') // escape sequences\n\t\t\t{\n\t\t\t\tif(pEnd[1] == '\"')\n\t\t\t\t\tpEnd++;\n\t\t\t}\n\t\t\telse if(!InString)\n\t\t\t{\n\t\t\t\tif(*pEnd == ';') // command separator\n\t\t\t\t{\n\t\t\t\t\tpNextPart = pEnd+1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse if(*pEnd == '#') // comment, no need to do anything more\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tpEnd++;\n\t\t}\n\n\t\tif(ParseStart(&Result, pStr, (pEnd-pStr) + 1) != 0)\n\t\t\treturn;\n\n\t\tif(!*Result.m_pCommand)\n\t\t\treturn;\n\n\t\tCCommand *pCommand = FindCommand(Result.m_pCommand, m_FlagMask);\n\n\t\tif(pCommand)\n\t\t{\n\t\t\tif(pCommand->GetAccessLevel() >= m_AccessLevel)\n\t\t\t{\n\t\t\t\tint IsStrokeCommand = 0;\n\t\t\t\tif(Result.m_pCommand[0] == '+')\n\t\t\t\t{\n\t\t\t\t\t// insert the stroke direction token\n\t\t\t\t\tResult.AddArgument(m_paStrokeStr[Stroke]);\n\t\t\t\t\tIsStrokeCommand = 1;\n\t\t\t\t}\n\n\t\t\t\tif(Stroke || IsStrokeCommand)\n\t\t\t\t{\n\t\t\t\t\tif(ParseArgs(&Result, pCommand->m_pParams))\n\t\t\t\t\t{\n\t\t\t\t\t\tchar aBuf[256];\n\t\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"Invalid arguments... Usage: %s %s\", pCommand->m_pName, pCommand->m_pParams);\n\t\t\t\t\t\tPrint(OUTPUT_LEVEL_STANDARD, \"Console\", aBuf);\n\t\t\t\t\t}\n\t\t\t\t\telse if(m_StoreCommands && pCommand->m_Flags&CFGFLAG_STORE)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_ExecutionQueue.AddEntry();\n\t\t\t\t\t\tm_ExecutionQueue.m_pLast->m_pfnCommandCallback = pCommand->m_pfnCallback;\n\t\t\t\t\t\tm_ExecutionQueue.m_pLast->m_pCommandUserData = pCommand->m_pUserData;\n\t\t\t\t\t\tm_ExecutionQueue.m_pLast->m_Result = Result;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tpCommand->m_pfnCallback(&Result, pCommand->m_pUserData);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(Stroke)\n\t\t\t{\n\t\t\t\tchar aBuf[256];\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"Access for command %s denied.\", Result.m_pCommand);\n\t\t\t\tPrint(OUTPUT_LEVEL_STANDARD, \"Console\", aBuf);\n\t\t\t}\n\t\t}\n\t\telse if(Stroke)\n\t\t{\n\t\t\tchar aBuf[256];\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"No such command: %s.\", Result.m_pCommand);\n\t\t\tPrint(OUTPUT_LEVEL_STANDARD, \"Console\", aBuf);\n\t\t}\n\n\t\tpStr = pNextPart;\n\t}\n}\n\nvoid CConsole::PossibleCommands(const char *pStr, int FlagMask, bool Temp, FPossibleCallback pfnCallback, void *pUser)\n{\n\tfor(CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext)\n\t{\n\t\tif(pCommand->m_Flags&FlagMask && pCommand->m_Temp == Temp)\n\t\t{\n\t\t\tif(str_find_nocase(pCommand->m_pName, pStr))\n\t\t\t\tpfnCallback(pCommand->m_pName, pUser);\n\t\t}\n\t}\n}\n\nCConsole::CCommand *CConsole::FindCommand(const char *pName, int FlagMask)\n{\n\tfor(CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext)\n\t{\n\t\tif(pCommand->m_Flags&FlagMask)\n\t\t{\n\t\t\tif(str_comp_nocase(pCommand->m_pName, pName) == 0)\n\t\t\t\treturn pCommand;\n\t\t}\n\t}\n\n\treturn 0x0;\n}\n\nvoid CConsole::ExecuteLine(const char *pStr)\n{\n\tCConsole::ExecuteLineStroked(1, pStr); // press it\n\tCConsole::ExecuteLineStroked(0, pStr); // then release it\n}\n\nvoid CConsole::ExecuteLineFlag(const char *pStr, int FlagMask)\n{\n\tint Temp = m_FlagMask;\n\tm_FlagMask = FlagMask;\n\tExecuteLine(pStr);\n\tm_FlagMask = Temp;\n}\n\n\nvoid CConsole::ExecuteFile(const char *pFilename)\n{\n\t// make sure that this isn't being executed already\n\tfor(CExecFile *pCur = m_pFirstExec; pCur; pCur = pCur->m_pPrev)\n\t\tif(str_comp(pFilename, pCur->m_pFilename) == 0)\n\t\t\treturn;\n\n\tif(!m_pStorage)\n\t\tm_pStorage = Kernel()->RequestInterface<IStorage>();\n\tif(!m_pStorage)\n\t\treturn;\n\n\t// push this one to the stack\n\tCExecFile ThisFile;\n\tCExecFile *pPrev = m_pFirstExec;\n\tThisFile.m_pFilename = pFilename;\n\tThisFile.m_pPrev = m_pFirstExec;\n\tm_pFirstExec = &ThisFile;\n\n\t// exec the file\n\tIOHANDLE File = m_pStorage->OpenFile(pFilename, IOFLAG_READ, IStorage::TYPE_ALL);\n\n\tchar aBuf[256];\n\tif(File)\n\t{\n\t\tchar *pLine;\n\t\tCLineReader lr;\n\n\t\tstr_format(aBuf, sizeof(aBuf), \"executing '%s'\", pFilename);\n\t\tPrint(IConsole::OUTPUT_LEVEL_STANDARD, \"console\", aBuf);\n\t\tlr.Init(File);\n\n\t\twhile((pLine = lr.Get()))\n\t\t\tExecuteLine(pLine);\n\n\t\tio_close(File);\n\t}\n\telse\n\t{\n\t\tstr_format(aBuf, sizeof(aBuf), \"failed to open '%s'\", pFilename);\n\t\tPrint(IConsole::OUTPUT_LEVEL_STANDARD, \"console\", aBuf);\n\t}\n\n\tm_pFirstExec = pPrev;\n}\n\nvoid CConsole::Con_Echo(IResult *pResult, void *pUserData)\n{\n\t((CConsole*)pUserData)->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"Console\", pResult->GetString(0));\n}\n\nvoid CConsole::Con_Exec(IResult *pResult, void *pUserData)\n{\n\t((CConsole*)pUserData)->ExecuteFile(pResult->GetString(0));\n}\n\nvoid CConsole::ConModCommandAccess(IResult *pResult, void *pUser)\n{\n\tCConsole* pConsole = static_cast<CConsole *>(pUser);\n\tchar aBuf[128];\n\tCCommand *pCommand = pConsole->FindCommand(pResult->GetString(0), CFGFLAG_SERVER);\n\tif(pCommand)\n\t{\n\t\tif(pResult->NumArguments() == 2)\n\t\t{\n\t\t\tpCommand->SetAccessLevel(pResult->GetInteger(1));\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"moderator access for '%s' is now %s\", pResult->GetString(0), pCommand->GetAccessLevel() ? \"enabled\" : \"disabled\");\n\t\t}\n\t\telse\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"moderator access for '%s' is %s\", pResult->GetString(0), pCommand->GetAccessLevel() ? \"enabled\" : \"disabled\");\n\t}\n\telse\n\t\tstr_format(aBuf, sizeof(aBuf), \"No such command: '%s'.\", pResult->GetString(0));\n\n\tpConsole->Print(OUTPUT_LEVEL_STANDARD, \"Console\", aBuf);\n}\n\nvoid CConsole::ConModCommandStatus(IResult *pResult, void *pUser)\n{\n\tCConsole* pConsole = static_cast<CConsole *>(pUser);\n\tchar aBuf[240];\n\tmem_zero(aBuf, sizeof(aBuf));\n\tint Used = 0;\n\n\tfor(CCommand *pCommand = pConsole->m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext)\n\t{\n\t\tif(pCommand->m_Flags&pConsole->m_FlagMask && pCommand->GetAccessLevel() == ACCESS_LEVEL_MOD)\n\t\t{\n\t\t\tint Length = str_length(pCommand->m_pName);\n\t\t\tif(Used + Length + 2 < (int)(sizeof(aBuf)))\n\t\t\t{\n\t\t\t\tif(Used > 0)\n\t\t\t\t{\n\t\t\t\t\tUsed += 2;\n\t\t\t\t\tstr_append(aBuf, \", \", sizeof(aBuf));\n\t\t\t\t}\n\t\t\t\tstr_append(aBuf, pCommand->m_pName, sizeof(aBuf));\n\t\t\t\tUsed += Length;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tpConsole->Print(OUTPUT_LEVEL_STANDARD, \"Console\", aBuf);\n\t\t\t\tmem_zero(aBuf, sizeof(aBuf));\n\t\t\t\tstr_copy(aBuf, pCommand->m_pName, sizeof(aBuf));\n\t\t\t\tUsed = Length;\n\t\t\t}\n\t\t}\n\t}\n\tif(Used > 0)\n\t\tpConsole->Print(OUTPUT_LEVEL_STANDARD, \"Console\", aBuf);\n}\n\nstruct CIntVariableData\n{\n\tIConsole *m_pConsole;\n\tint *m_pVariable;\n\tint m_Min;\n\tint m_Max;\n};\n\nstruct CStrVariableData\n{\n\tIConsole *m_pConsole;\n\tchar *m_pStr;\n\tint m_MaxSize;\n};\n\nstatic void IntVariableCommand(IConsole::IResult *pResult, void *pUserData)\n{\n\tCIntVariableData *pData = (CIntVariableData *)pUserData;\n\n\tif(pResult->NumArguments())\n\t{\n\t\tint Val = pResult->GetInteger(0);\n\n\t\t// do clamping\n\t\tif(pData->m_Min != pData->m_Max)\n\t\t{\n\t\t\tif (Val < pData->m_Min)\n\t\t\t\tVal = pData->m_Min;\n\t\t\tif (pData->m_Max != 0 && Val > pData->m_Max)\n\t\t\t\tVal = pData->m_Max;\n\t\t}\n\n\t\t*(pData->m_pVariable) = Val;\n\t}\n\telse\n\t{\n\t\tchar aBuf[1024];\n\t\tstr_format(aBuf, sizeof(aBuf), \"Value: %d\", *(pData->m_pVariable));\n\t\tpData->m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"Console\", aBuf);\n\t}\n}\n\nstatic void StrVariableCommand(IConsole::IResult *pResult, void *pUserData)\n{\n\tCStrVariableData *pData = (CStrVariableData *)pUserData;\n\n\tif(pResult->NumArguments())\n\t{\n\t\tconst char *pString = pResult->GetString(0);\n\t\tif(!str_utf8_check(pString))\n\t\t{\n\t\t\tchar Temp[4];\n\t\t\tint Length = 0;\n\t\t\twhile(*pString)\n\t\t\t{\n\t\t\t\tint Size = str_utf8_encode(Temp, static_cast<const unsigned char>(*pString++));\n\t\t\t\tif(Length+Size < pData->m_MaxSize)\n\t\t\t\t{\n\t\t\t\t\tmem_copy(pData->m_pStr+Length, &Temp, Size);\n\t\t\t\t\tLength += Size;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tpData->m_pStr[Length] = 0;\n\t\t}\n\t\telse\n\t\t\tstr_copy(pData->m_pStr, pString, pData->m_MaxSize);\n\t}\n\telse\n\t{\n\t\tchar aBuf[1024];\n\t\tstr_format(aBuf, sizeof(aBuf), \"Value: %s\", pData->m_pStr);\n\t\tpData->m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"Console\", aBuf);\n\t}\n}\n\nvoid CConsole::ConToggle(IConsole::IResult *pResult, void *pUser)\n{\n\tCConsole* pConsole = static_cast<CConsole *>(pUser);\n\tchar aBuf[128] = {0};\n\tCCommand *pCommand = pConsole->FindCommand(pResult->GetString(0), pConsole->m_FlagMask);\n\tif(pCommand)\n\t{\n\t\tFCommandCallback pfnCallback = pCommand->m_pfnCallback;\n\t\tvoid *pUserData = pCommand->m_pUserData;\n\n\t\t// check for chain\n\t\tif(pCommand->m_pfnCallback == Con_Chain)\n\t\t{\n\t\t\tCChain *pChainInfo = static_cast<CChain *>(pCommand->m_pUserData);\n\t\t\tpfnCallback = pChainInfo->m_pfnCallback;\n\t\t\tpUserData = pChainInfo->m_pCallbackUserData;\n\t\t}\n\n\t\tif(pfnCallback == IntVariableCommand)\n\t\t{\n\t\t\tCIntVariableData *pData = static_cast<CIntVariableData *>(pUserData);\n\t\t\tint Val = *(pData->m_pVariable)==pResult->GetInteger(1) ? pResult->GetInteger(2) : pResult->GetInteger(1);\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"%s %i\", pResult->GetString(0), Val);\n\t\t\tpConsole->ExecuteLine(aBuf);\n\t\t\taBuf[0] = 0;\n\t\t}\n\t\telse\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"Invalid command: '%s'.\", pResult->GetString(0));\n\t}\n\telse\n\t\tstr_format(aBuf, sizeof(aBuf), \"No such command: '%s'.\", pResult->GetString(0));\n\n\tif(aBuf[0] != 0)\n\t\tpConsole->Print(OUTPUT_LEVEL_STANDARD, \"Console\", aBuf);\n}\n\nvoid CConsole::ConToggleStroke(IConsole::IResult *pResult, void *pUser)\n{\n\tCConsole* pConsole = static_cast<CConsole *>(pUser);\n\tchar aBuf[128] = {0};\n\tCCommand *pCommand = pConsole->FindCommand(pResult->GetString(1), pConsole->m_FlagMask);\n\tif(pCommand)\n\t{\n\t\tFCommandCallback pfnCallback = pCommand->m_pfnCallback;\n\n\t\t// check for chain\n\t\tif(pCommand->m_pfnCallback == Con_Chain)\n\t\t{\n\t\t\tCChain *pChainInfo = static_cast<CChain *>(pCommand->m_pUserData);\n\t\t\tpfnCallback = pChainInfo->m_pfnCallback;\n\t\t}\n\n\t\tif(pfnCallback == IntVariableCommand)\n\t\t{\n\t\t\tint Val = pResult->GetInteger(0)==0 ? pResult->GetInteger(3) : pResult->GetInteger(2);\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"%s %i\", pResult->GetString(1), Val);\n\t\t\tpConsole->ExecuteLine(aBuf);\n\t\t\taBuf[0] = 0;\n\t\t}\n\t\telse\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"Invalid command: '%s'.\", pResult->GetString(1));\n\t}\n\telse\n\t\tstr_format(aBuf, sizeof(aBuf), \"No such command: '%s'.\", pResult->GetString(1));\n\n\tif(aBuf[0] != 0)\n\t\tpConsole->Print(OUTPUT_LEVEL_STANDARD, \"Console\", aBuf);\n}\n\nCConsole::CConsole(int FlagMask)\n{\n\tm_FlagMask = FlagMask;\n\tm_AccessLevel = ACCESS_LEVEL_ADMIN;\n\tm_pRecycleList = 0;\n\tm_TempCommands.Reset();\n\tm_StoreCommands = true;\n\tm_paStrokeStr[0] = \"0\";\n\tm_paStrokeStr[1] = \"1\";\n\tm_ExecutionQueue.Reset();\n\tm_pFirstCommand = 0;\n\tm_pFirstExec = 0;\n\tmem_zero(m_aPrintCB, sizeof(m_aPrintCB));\n\tm_NumPrintCB = 0;\n\n\tm_pStorage = 0;\n\n\t// register some basic commands\n\tRegister(\"echo\", \"r\", CFGFLAG_SERVER|CFGFLAG_CLIENT, Con_Echo, this, \"Echo the text\");\n\tRegister(\"exec\", \"r\", CFGFLAG_SERVER|CFGFLAG_CLIENT, Con_Exec, this, \"Execute the specified file\");\n\n\tRegister(\"toggle\", \"sii\", CFGFLAG_SERVER|CFGFLAG_CLIENT, ConToggle, this, \"Toggle config value\");\n\tRegister(\"+toggle\", \"sii\", CFGFLAG_CLIENT, ConToggleStroke, this, \"Toggle config value via keypress\");\n\n\tRegister(\"mod_command\", \"s?i\", CFGFLAG_SERVER, ConModCommandAccess, this, \"Specify command accessibility for moderators\");\n\tRegister(\"mod_status\", \"\", CFGFLAG_SERVER, ConModCommandStatus, this, \"List all commands which are accessible for moderators\");\n\n\t// TODO: this should disappear\n\t#define MACRO_CONFIG_INT(Name,ScriptName,Def,Min,Max,Flags,Desc) \\\n\t{ \\\n\t\tstatic CIntVariableData Data = { this, &g_Config.m_##Name, Min, Max }; \\\n\t\tRegister(#ScriptName, \"?i\", Flags, IntVariableCommand, &Data, Desc); \\\n\t}\n\n\t#define MACRO_CONFIG_STR(Name,ScriptName,Len,Def,Flags,Desc) \\\n\t{ \\\n\t\tstatic CStrVariableData Data = { this, g_Config.m_##Name, Len }; \\\n\t\tRegister(#ScriptName, \"?r\", Flags, StrVariableCommand, &Data, Desc); \\\n\t}\n\n\t#include \"config_variables.h\"\n\n\t#undef MACRO_CONFIG_INT\n\t#undef MACRO_CONFIG_STR\n}\n\nvoid CConsole::ParseArguments(int NumArgs, const char **ppArguments)\n{\n\tfor(int i = 0; i < NumArgs; i++)\n\t{\n\t\t// check for scripts to execute\n\t\tif(ppArguments[i][0] == '-' && ppArguments[i][1] == 'f' && ppArguments[i][2] == 0)\n\t\t{\n\t\t\tif(NumArgs - i > 1)\n\t\t\t\tExecuteFile(ppArguments[i+1]);\n\t\t\ti++;\n\t\t}\n\t\telse if(!str_comp(\"-s\", ppArguments[i]) || !str_comp(\"--silent\", ppArguments[i]))\n\t\t{\n\t\t\t// skip silent param\n\t\t\tcontinue;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// search arguments for overrides\n\t\t\tExecuteLine(ppArguments[i]);\n\t\t}\n\t}\n}\n\nvoid CConsole::AddCommandSorted(CCommand *pCommand)\n{\n\tif(!m_pFirstCommand || str_comp(pCommand->m_pName, m_pFirstCommand->m_pName) <= 0)\n\t{\n\t\tif(m_pFirstCommand && m_pFirstCommand->m_pNext)\n\t\t\tpCommand->m_pNext = m_pFirstCommand;\n\t\telse\n\t\t\tpCommand->m_pNext = 0;\n\t\tm_pFirstCommand = pCommand;\n\t}\n\telse\n\t{\n\t\tfor(CCommand *p = m_pFirstCommand; p; p = p->m_pNext)\n\t\t{\n\t\t\tif(!p->m_pNext || str_comp(pCommand->m_pName, p->m_pNext->m_pName) <= 0)\n\t\t\t{\n\t\t\t\tpCommand->m_pNext = p->m_pNext;\n\t\t\t\tp->m_pNext = pCommand;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid CConsole::Register(const char *pName, const char *pParams,\n\tint Flags, FCommandCallback pfnFunc, void *pUser, const char *pHelp)\n{\n\tCCommand *pCommand = FindCommand(pName, Flags);\n\tbool DoAdd = false;\n\tif(pCommand == 0)\n\t{\n\t\tpCommand = new(mem_alloc(sizeof(CCommand), sizeof(void*))) CCommand;\n\t\tDoAdd = true;\n\t}\n\tpCommand->m_pfnCallback = pfnFunc;\n\tpCommand->m_pUserData = pUser;\n\n\tpCommand->m_pName = pName;\n\tpCommand->m_pHelp = pHelp;\n\tpCommand->m_pParams = pParams;\n\n\tpCommand->m_Flags = Flags;\n\tpCommand->m_Temp = false;\n\n\tif(DoAdd)\n\t\tAddCommandSorted(pCommand);\n}\n\nvoid CConsole::RegisterTemp(const char *pName, const char *pParams,\tint Flags, const char *pHelp)\n{\n\tCCommand *pCommand;\n\tif(m_pRecycleList)\n\t{\n\t\tpCommand = m_pRecycleList;\n\t\tstr_copy(const_cast<char *>(pCommand->m_pName), pName, TEMPCMD_NAME_LENGTH);\n\t\tstr_copy(const_cast<char *>(pCommand->m_pHelp), pHelp, TEMPCMD_HELP_LENGTH);\n\t\tstr_copy(const_cast<char *>(pCommand->m_pParams), pParams, TEMPCMD_PARAMS_LENGTH);\n\n\t\tm_pRecycleList = m_pRecycleList->m_pNext;\n\t}\n\telse\n\t{\n\t\tpCommand = new(m_TempCommands.Allocate(sizeof(CCommand))) CCommand;\n\t\tchar *pMem = static_cast<char *>(m_TempCommands.Allocate(TEMPCMD_NAME_LENGTH));\n\t\tstr_copy(pMem, pName, TEMPCMD_NAME_LENGTH);\n\t\tpCommand->m_pName = pMem;\n\t\tpMem = static_cast<char *>(m_TempCommands.Allocate(TEMPCMD_HELP_LENGTH));\n\t\tstr_copy(pMem, pHelp, TEMPCMD_HELP_LENGTH);\n\t\tpCommand->m_pHelp = pMem;\n\t\tpMem = static_cast<char *>(m_TempCommands.Allocate(TEMPCMD_PARAMS_LENGTH));\n\t\tstr_copy(pMem, pParams, TEMPCMD_PARAMS_LENGTH);\n\t\tpCommand->m_pParams = pMem;\n\t}\n\n\tpCommand->m_pfnCallback = 0;\n\tpCommand->m_pUserData = 0;\n\tpCommand->m_Flags = Flags;\n\tpCommand->m_Temp = true;\n\n\tAddCommandSorted(pCommand);\n}\n\nvoid CConsole::DeregisterTemp(const char *pName)\n{\n\tif(!m_pFirstCommand)\n\t\treturn;\n\n\tCCommand *pRemoved = 0;\n\n\t// remove temp entry from command list\n\tif(m_pFirstCommand->m_Temp && str_comp(m_pFirstCommand->m_pName, pName) == 0)\n\t{\n\t\tpRemoved = m_pFirstCommand;\n\t\tm_pFirstCommand = m_pFirstCommand->m_pNext;\n\t}\n\telse\n\t{\n\t\tfor(CCommand *pCommand = m_pFirstCommand; pCommand->m_pNext; pCommand = pCommand->m_pNext)\n\t\t\tif(pCommand->m_pNext->m_Temp && str_comp(pCommand->m_pNext->m_pName, pName) == 0)\n\t\t\t{\n\t\t\t\tpRemoved = pCommand->m_pNext;\n\t\t\t\tpCommand->m_pNext = pCommand->m_pNext->m_pNext;\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n\n\t// add to recycle list\n\tif(pRemoved)\n\t{\n\t\tpRemoved->m_pNext = m_pRecycleList;\n\t\tm_pRecycleList = pRemoved;\n\t}\n}\n\nvoid CConsole::DeregisterTempAll()\n{\n\t// set non temp as first one\n\tfor(; m_pFirstCommand && m_pFirstCommand->m_Temp; m_pFirstCommand = m_pFirstCommand->m_pNext);\n\n\t// remove temp entries from command list\n\tfor(CCommand *pCommand = m_pFirstCommand; pCommand && pCommand->m_pNext; pCommand = pCommand->m_pNext)\n\t{\n\t\tCCommand *pNext = pCommand->m_pNext;\n\t\tif(pNext->m_Temp)\n\t\t{\n\t\t\tfor(; pNext && pNext->m_Temp; pNext = pNext->m_pNext);\n\t\t\tpCommand->m_pNext = pNext;\n\t\t}\n\t}\n\n\tm_TempCommands.Reset();\n\tm_pRecycleList = 0;\n}\n\nvoid CConsole::Con_Chain(IResult *pResult, void *pUserData)\n{\n\tCChain *pInfo = (CChain *)pUserData;\n\tpInfo->m_pfnChainCallback(pResult, pInfo->m_pUserData, pInfo->m_pfnCallback, pInfo->m_pCallbackUserData);\n}\n\nvoid CConsole::Chain(const char *pName, FChainCommandCallback pfnChainFunc, void *pUser)\n{\n\tCCommand *pCommand = FindCommand(pName, m_FlagMask);\n\n\tif(!pCommand)\n\t{\n\t\tchar aBuf[256];\n\t\tstr_format(aBuf, sizeof(aBuf), \"failed to chain '%s'\", pName);\n\t\tPrint(IConsole::OUTPUT_LEVEL_DEBUG, \"console\", aBuf);\n\t\treturn;\n\t}\n\n\tCChain *pChainInfo = (CChain *)mem_alloc(sizeof(CChain), sizeof(void*));\n\n\t// store info\n\tpChainInfo->m_pfnChainCallback = pfnChainFunc;\n\tpChainInfo->m_pUserData = pUser;\n\tpChainInfo->m_pfnCallback = pCommand->m_pfnCallback;\n\tpChainInfo->m_pCallbackUserData = pCommand->m_pUserData;\n\n\t// chain\n\tpCommand->m_pfnCallback = Con_Chain;\n\tpCommand->m_pUserData = pChainInfo;\n}\n\nvoid CConsole::StoreCommands(bool Store)\n{\n\tif(!Store)\n\t{\n\t\tfor(CExecutionQueue::CQueueEntry *pEntry = m_ExecutionQueue.m_pFirst; pEntry; pEntry = pEntry->m_pNext)\n\t\t\tpEntry->m_pfnCommandCallback(&pEntry->m_Result, pEntry->m_pCommandUserData);\n\t\tm_ExecutionQueue.Reset();\n\t}\n\tm_StoreCommands = Store;\n}\n\n\nconst IConsole::CCommandInfo *CConsole::GetCommandInfo(const char *pName, int FlagMask, bool Temp)\n{\n\tfor(CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext)\n\t{\n\t\tif(pCommand->m_Flags&FlagMask && pCommand->m_Temp == Temp)\n\t\t{\n\t\t\tif(str_comp_nocase(pCommand->m_pName, pName) == 0)\n\t\t\t\treturn pCommand;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n\nextern IConsole *CreateConsole(int FlagMask) { return new CConsole(FlagMask); }\n"
  },
  {
    "path": "src/engine/shared/console.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SHARED_CONSOLE_H\n#define ENGINE_SHARED_CONSOLE_H\n\n#include <engine/console.h>\n#include \"memheap.h\"\n\nclass CConsole : public IConsole\n{\n\tclass CCommand : public CCommandInfo\n\t{\n\tpublic:\n\t\tCCommand *m_pNext;\n\t\tint m_Flags;\n\t\tbool m_Temp;\n\t\tFCommandCallback m_pfnCallback;\n\t\tvoid *m_pUserData;\n\n\t\tvirtual const CCommandInfo *NextCommandInfo(int AccessLevel, int FlagMask) const;\n\n\t\tvoid SetAccessLevel(int AccessLevel) { m_AccessLevel = clamp(AccessLevel, (int)(ACCESS_LEVEL_ADMIN), (int)(ACCESS_LEVEL_MOD)); }\n\t};\n\n\n\tclass CChain\n\t{\n\tpublic:\n\t\tFChainCommandCallback m_pfnChainCallback;\n\t\tFCommandCallback m_pfnCallback;\n\t\tvoid *m_pCallbackUserData;\n\t\tvoid *m_pUserData;\n\t};\n\n\tint m_FlagMask;\n\tbool m_StoreCommands;\n\tconst char *m_paStrokeStr[2];\n\tCCommand *m_pFirstCommand;\n\n\tclass CExecFile\n\t{\n\tpublic:\n\t\tconst char *m_pFilename;\n\t\tCExecFile *m_pPrev;\n\t};\n\n\tCExecFile *m_pFirstExec;\n\tclass IStorage *m_pStorage;\n\tint m_AccessLevel;\n\n\tCCommand *m_pRecycleList;\n\tCHeap m_TempCommands;\n\n\tstatic void Con_Chain(IResult *pResult, void *pUserData);\n\tstatic void Con_Echo(IResult *pResult, void *pUserData);\n\tstatic void Con_Exec(IResult *pResult, void *pUserData);\n\tstatic void ConToggle(IResult *pResult, void *pUser);\n\tstatic void ConToggleStroke(IResult *pResult, void *pUser);\n\tstatic void ConModCommandAccess(IResult *pResult, void *pUser);\n\tstatic void ConModCommandStatus(IConsole::IResult *pResult, void *pUser);\n\n\tvoid ExecuteFileRecurse(const char *pFilename);\n\tvoid ExecuteLineStroked(int Stroke, const char *pStr);\n\n\tstruct\n\t{\n\t\tint m_OutputLevel;\n\t\tFPrintCallback m_pfnPrintCallback;\n\t\tvoid *m_pPrintCallbackUserdata;\n\t} m_aPrintCB[MAX_PRINT_CB];\n\tint m_NumPrintCB;\n\n\tenum\n\t{\n\t\tCONSOLE_MAX_STR_LENGTH = 1024,\n\t\tMAX_PARTS = (CONSOLE_MAX_STR_LENGTH+1)/2\n\t};\n\n\tclass CResult : public IResult\n\t{\n\tpublic:\n\t\tchar m_aStringStorage[CONSOLE_MAX_STR_LENGTH+1];\n\t\tchar *m_pArgsStart;\n\n\t\tconst char *m_pCommand;\n\t\tconst char *m_apArgs[MAX_PARTS];\n\n\t\tCResult() : IResult()\n\t\t{\n\t\t\tmem_zero(m_aStringStorage, sizeof(m_aStringStorage));\n\t\t\tm_pArgsStart = 0;\n\t\t\tm_pCommand = 0;\n\t\t\tmem_zero(m_apArgs, sizeof(m_apArgs));\n\t\t}\n\n\t\tCResult &operator =(const CResult &Other)\n\t\t{\n\t\t\tif(this != &Other)\n\t\t\t{\n\t\t\t\tIResult::operator=(Other);\n\t\t\t\tint Offset = m_aStringStorage - Other.m_aStringStorage;\n\t\t\t\tmem_copy(m_aStringStorage, Other.m_aStringStorage, sizeof(m_aStringStorage));\n\t\t\t\tm_pArgsStart = Other.m_pArgsStart + Offset;\n\t\t\t\tm_pCommand = Other.m_pCommand + Offset;\n\t\t\t\tfor(unsigned i = 0; i < Other.m_NumArgs; ++i)\n\t\t\t\t\tm_apArgs[i] = Other.m_apArgs[i] + Offset;\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\n\t\tvoid AddArgument(const char *pArg)\n\t\t{\n\t\t\tm_apArgs[m_NumArgs++] = pArg;\n\t\t}\n\n\t\tvirtual const char *GetString(unsigned Index);\n\t\tvirtual int GetInteger(unsigned Index);\n\t\tvirtual float GetFloat(unsigned Index);\n\t};\n\n\tint ParseStart(CResult *pResult, const char *pString, int Length);\n\tint ParseArgs(CResult *pResult, const char *pFormat);\n\n\tclass CExecutionQueue\n\t{\n\t\tCHeap m_Queue;\n\n\tpublic:\n\t\tstruct CQueueEntry\n\t\t{\n\t\t\tCQueueEntry *m_pNext;\n\t\t\tFCommandCallback m_pfnCommandCallback;\n\t\t\tvoid *m_pCommandUserData;\n\t\t\tCResult m_Result;\n\t\t} *m_pFirst, *m_pLast;\n\n\t\tvoid AddEntry()\n\t\t{\n\t\t\tCQueueEntry *pEntry = static_cast<CQueueEntry *>(m_Queue.Allocate(sizeof(CQueueEntry)));\n\t\t\tpEntry->m_pNext = 0;\n\t\t\tif(!m_pFirst)\n\t\t\t\tm_pFirst = pEntry;\n\t\t\tif(m_pLast)\n\t\t\t\tm_pLast->m_pNext = pEntry;\n\t\t\tm_pLast = pEntry;\n\t\t\t(void)new(&(pEntry->m_Result)) CResult;\n\t\t}\n\t\tvoid Reset()\n\t\t{\n\t\t\tm_Queue.Reset();\n\t\t\tm_pFirst = m_pLast = 0;\n\t\t}\n\t} m_ExecutionQueue;\n\n\tvoid AddCommandSorted(CCommand *pCommand);\n\tCCommand *FindCommand(const char *pName, int FlagMask);\n\npublic:\n\tCConsole(int FlagMask);\n\n\tvirtual const CCommandInfo *FirstCommandInfo(int AccessLevel, int FlagMask) const;\n\tvirtual const CCommandInfo *GetCommandInfo(const char *pName, int FlagMask, bool Temp);\n\tvirtual void PossibleCommands(const char *pStr, int FlagMask, bool Temp, FPossibleCallback pfnCallback, void *pUser);\n\n\tvirtual void ParseArguments(int NumArgs, const char **ppArguments);\n\tvirtual void Register(const char *pName, const char *pParams, int Flags, FCommandCallback pfnFunc, void *pUser, const char *pHelp);\n\tvirtual void RegisterTemp(const char *pName, const char *pParams, int Flags, const char *pHelp);\n\tvirtual void DeregisterTemp(const char *pName);\n\tvirtual void DeregisterTempAll();\n\tvirtual void Chain(const char *pName, FChainCommandCallback pfnChainFunc, void *pUser);\n\tvirtual void StoreCommands(bool Store);\n\n\tvirtual bool LineIsValid(const char *pStr);\n\tvirtual void ExecuteLine(const char *pStr);\n\tvirtual void ExecuteLineFlag(const char *pStr, int FlagMask);\n\tvirtual void ExecuteFile(const char *pFilename);\n\n\tvirtual int RegisterPrintCallback(int OutputLevel, FPrintCallback pfnPrintCallback, void *pUserData);\n\tvirtual void SetPrintOutputLevel(int Index, int OutputLevel);\n\tvirtual void Print(int Level, const char *pFrom, const char *pStr);\n\n\tvoid SetAccessLevel(int AccessLevel) { m_AccessLevel = clamp(AccessLevel, (int)(ACCESS_LEVEL_ADMIN), (int)(ACCESS_LEVEL_MOD)); }\n};\n\n#endif\n"
  },
  {
    "path": "src/engine/shared/datafile.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/math.h>\n#include <base/system.h>\n#include <engine/storage.h>\n#include \"datafile.h\"\n#include <zlib.h>\n\nstatic const int DEBUG=0;\n\nstruct CDatafileItemType\n{\n\tint m_Type;\n\tint m_Start;\n\tint m_Num;\n} ;\n\nstruct CDatafileItem\n{\n\tint m_TypeAndID;\n\tint m_Size;\n};\n\nstruct CDatafileHeader\n{\n\tchar m_aID[4];\n\tint m_Version;\n\tint m_Size;\n\tint m_Swaplen;\n\tint m_NumItemTypes;\n\tint m_NumItems;\n\tint m_NumRawData;\n\tint m_ItemSize;\n\tint m_DataSize;\n};\n\nstruct CDatafileData\n{\n\tint m_NumItemTypes;\n\tint m_NumItems;\n\tint m_NumRawData;\n\tint m_ItemSize;\n\tint m_DataSize;\n\tchar m_aStart[4];\n};\n\nstruct CDatafileInfo\n{\n\tCDatafileItemType *m_pItemTypes;\n\tint *m_pItemOffsets;\n\tint *m_pDataOffsets;\n\tint *m_pDataSizes;\n\n\tchar *m_pItemStart;\n\tchar *m_pDataStart;\n};\n\nstruct CDatafile\n{\n\tIOHANDLE m_File;\n\tunsigned m_Crc;\n\tCDatafileInfo m_Info;\n\tCDatafileHeader m_Header;\n\tint m_DataStartOffset;\n\tchar **m_ppDataPtrs;\n\tchar *m_pData;\n};\n\nbool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int StorageType)\n{\n\tdbg_msg(\"datafile\", \"loading. filename='%s'\", pFilename);\n\n\tIOHANDLE File = pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType);\n\tif(!File)\n\t{\n\t\tdbg_msg(\"datafile\", \"could not open '%s'\", pFilename);\n\t\treturn false;\n\t}\n\n\n\t// take the CRC of the file and store it\n\tunsigned Crc = 0;\n\t{\n\t\tenum\n\t\t{\n\t\t\tBUFFER_SIZE = 64*1024\n\t\t};\n\n\t\tunsigned char aBuffer[BUFFER_SIZE];\n\n\t\twhile(1)\n\t\t{\n\t\t\tunsigned Bytes = io_read(File, aBuffer, BUFFER_SIZE);\n\t\t\tif(Bytes <= 0)\n\t\t\t\tbreak;\n\t\t\tCrc = crc32(Crc, aBuffer, Bytes); // ignore_convention\n\t\t}\n\n\t\tio_seek(File, 0, IOSEEK_START);\n\t}\n\n\n\t// TODO: change this header\n\tCDatafileHeader Header;\n\tio_read(File, &Header, sizeof(Header));\n\tif(Header.m_aID[0] != 'A' || Header.m_aID[1] != 'T' || Header.m_aID[2] != 'A' || Header.m_aID[3] != 'D')\n\t{\n\t\tif(Header.m_aID[0] != 'D' || Header.m_aID[1] != 'A' || Header.m_aID[2] != 'T' || Header.m_aID[3] != 'A')\n\t\t{\n\t\t\tdbg_msg(\"datafile\", \"wrong signature. %x %x %x %x\", Header.m_aID[0], Header.m_aID[1], Header.m_aID[2], Header.m_aID[3]);\n\t\t\tio_close(File);\n\t\t\treturn 0;\n\t\t}\n\t}\n\n#if defined(CONF_ARCH_ENDIAN_BIG)\n\tswap_endian(&Header, sizeof(int), sizeof(Header)/sizeof(int));\n#endif\n\tif(Header.m_Version != 3 && Header.m_Version != 4)\n\t{\n\t\tdbg_msg(\"datafile\", \"wrong version. version=%x\", Header.m_Version);\n\t\tio_close(File);\n\t\treturn 0;\n\t}\n\n\t// read in the rest except the data\n\tunsigned Size = 0;\n\tSize += Header.m_NumItemTypes*sizeof(CDatafileItemType);\n\tSize += (Header.m_NumItems+Header.m_NumRawData)*sizeof(int);\n\tif(Header.m_Version == 4)\n\t\tSize += Header.m_NumRawData*sizeof(int); // v4 has uncompressed data sizes aswell\n\tSize += Header.m_ItemSize;\n\n\tunsigned AllocSize = Size;\n\tAllocSize += sizeof(CDatafile); // add space for info structure\n\tAllocSize += Header.m_NumRawData*sizeof(void*); // add space for data pointers\n\n\tCDatafile *pTmpDataFile = (CDatafile*)mem_alloc(AllocSize, 1);\n\tpTmpDataFile->m_Header = Header;\n\tpTmpDataFile->m_DataStartOffset = sizeof(CDatafileHeader) + Size;\n\tpTmpDataFile->m_ppDataPtrs = (char**)(pTmpDataFile+1);\n\tpTmpDataFile->m_pData = (char *)(pTmpDataFile+1)+Header.m_NumRawData*sizeof(char *);\n\tpTmpDataFile->m_File = File;\n\tpTmpDataFile->m_Crc = Crc;\n\n\t// clear the data pointers\n\tmem_zero(pTmpDataFile->m_ppDataPtrs, Header.m_NumRawData*sizeof(void*));\n\n\t// read types, offsets, sizes and item data\n\tunsigned ReadSize = io_read(File, pTmpDataFile->m_pData, Size);\n\tif(ReadSize != Size)\n\t{\n\t\tio_close(pTmpDataFile->m_File);\n\t\tmem_free(pTmpDataFile);\n\t\tpTmpDataFile = 0;\n\t\tdbg_msg(\"datafile\", \"couldn't load the whole thing, wanted=%d got=%d\", Size, ReadSize);\n\t\treturn false;\n\t}\n\n\tClose();\n\tm_pDataFile = pTmpDataFile;\n\n#if defined(CONF_ARCH_ENDIAN_BIG)\n\tswap_endian(m_pDataFile->m_pData, sizeof(int), min(static_cast<unsigned>(Header.m_Swaplen), Size) / sizeof(int));\n#endif\n\n\t//if(DEBUG)\n\t{\n\t\tdbg_msg(\"datafile\", \"allocsize=%d\", AllocSize);\n\t\tdbg_msg(\"datafile\", \"readsize=%d\", ReadSize);\n\t\tdbg_msg(\"datafile\", \"swaplen=%d\", Header.m_Swaplen);\n\t\tdbg_msg(\"datafile\", \"item_size=%d\", m_pDataFile->m_Header.m_ItemSize);\n\t}\n\n\tm_pDataFile->m_Info.m_pItemTypes = (CDatafileItemType *)m_pDataFile->m_pData;\n\tm_pDataFile->m_Info.m_pItemOffsets = (int *)&m_pDataFile->m_Info.m_pItemTypes[m_pDataFile->m_Header.m_NumItemTypes];\n\tm_pDataFile->m_Info.m_pDataOffsets = (int *)&m_pDataFile->m_Info.m_pItemOffsets[m_pDataFile->m_Header.m_NumItems];\n\tm_pDataFile->m_Info.m_pDataSizes = (int *)&m_pDataFile->m_Info.m_pDataOffsets[m_pDataFile->m_Header.m_NumRawData];\n\n\tif(Header.m_Version == 4)\n\t\tm_pDataFile->m_Info.m_pItemStart = (char *)&m_pDataFile->m_Info.m_pDataSizes[m_pDataFile->m_Header.m_NumRawData];\n\telse\n\t\tm_pDataFile->m_Info.m_pItemStart = (char *)&m_pDataFile->m_Info.m_pDataOffsets[m_pDataFile->m_Header.m_NumRawData];\n\tm_pDataFile->m_Info.m_pDataStart = m_pDataFile->m_Info.m_pItemStart + m_pDataFile->m_Header.m_ItemSize;\n\n\tdbg_msg(\"datafile\", \"loading done. datafile='%s'\", pFilename);\n\n\tif(DEBUG)\n\t{\n\t\t/*\n\t\tfor(int i = 0; i < m_pDataFile->data.num_raw_data; i++)\n\t\t{\n\t\t\tvoid *p = datafile_get_data(df, i);\n\t\t\tdbg_msg(\"datafile\", \"%d %d\", (int)((char*)p - (char*)(&m_pDataFile->data)), size);\n\t\t}\n\n\t\tfor(int i = 0; i < datafile_num_items(df); i++)\n\t\t{\n\t\t\tint type, id;\n\t\t\tvoid *data = datafile_get_item(df, i, &type, &id);\n\t\t\tdbg_msg(\"map\", \"\\t%d: type=%x id=%x p=%p offset=%d\", i, type, id, data, m_pDataFile->info.item_offsets[i]);\n\t\t\tint *idata = (int*)data;\n\t\t\tfor(int k = 0; k < 3; k++)\n\t\t\t\tdbg_msg(\"datafile\", \"\\t\\t%d=%d (%x)\", k, idata[k], idata[k]);\n\t\t}\n\n\t\tfor(int i = 0; i < m_pDataFile->data.num_m_aItemTypes; i++)\n\t\t{\n\t\t\tdbg_msg(\"map\", \"\\t%d: type=%x start=%d num=%d\", i,\n\t\t\t\tm_pDataFile->info.m_aItemTypes[i].type,\n\t\t\t\tm_pDataFile->info.m_aItemTypes[i].start,\n\t\t\t\tm_pDataFile->info.m_aItemTypes[i].num);\n\t\t\tfor(int k = 0; k < m_pDataFile->info.m_aItemTypes[i].num; k++)\n\t\t\t{\n\t\t\t\tint type, id;\n\t\t\t\tdatafile_get_item(df, m_pDataFile->info.m_aItemTypes[i].start+k, &type, &id);\n\t\t\t\tif(type != m_pDataFile->info.m_aItemTypes[i].type)\n\t\t\t\t\tdbg_msg(\"map\", \"\\tERROR\");\n\t\t\t}\n\t\t}\n\t\t*/\n\t}\n\n\treturn true;\n}\n\nbool CDataFileReader::GetCrcSize(class IStorage *pStorage, const char *pFilename, int StorageType, unsigned *pCrc, unsigned *pSize)\n{\n\tIOHANDLE File = pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType);\n\tif(!File)\n\t\treturn false;\n\n\t// get crc and size\n\tunsigned Crc = 0;\n\tunsigned Size = 0;\n\tunsigned char aBuffer[64*1024];\n\twhile(1)\n\t{\n\t\tunsigned Bytes = io_read(File, aBuffer, sizeof(aBuffer));\n\t\tif(Bytes <= 0)\n\t\t\tbreak;\n\t\tCrc = crc32(Crc, aBuffer, Bytes); // ignore_convention\n\t\tSize += Bytes;\n\t}\n\n\tio_close(File);\n\n\t*pCrc = Crc;\n\t*pSize = Size;\n\treturn true;\n}\n\nint CDataFileReader::NumData()\n{\n\tif(!m_pDataFile) { return 0; }\n\treturn m_pDataFile->m_Header.m_NumRawData;\n}\n\n// always returns the size in the file\nint CDataFileReader::GetDataSize(int Index)\n{\n\tif(!m_pDataFile) { return 0; }\n\n\tif(Index == m_pDataFile->m_Header.m_NumRawData-1)\n\t\treturn m_pDataFile->m_Header.m_DataSize-m_pDataFile->m_Info.m_pDataOffsets[Index];\n\treturn m_pDataFile->m_Info.m_pDataOffsets[Index+1]-m_pDataFile->m_Info.m_pDataOffsets[Index];\n}\n\nvoid *CDataFileReader::GetDataImpl(int Index, int Swap)\n{\n\tif(!m_pDataFile) { return 0; }\n\n\t// load it if needed\n\tif(!m_pDataFile->m_ppDataPtrs[Index])\n\t{\n\t\t// fetch the data size\n\t\tint DataSize = GetDataSize(Index);\n#if defined(CONF_ARCH_ENDIAN_BIG)\n\t\tint SwapSize = DataSize;\n#endif\n\n\t\tif(m_pDataFile->m_Header.m_Version == 4)\n\t\t{\n\t\t\t// v4 has compressed data\n\t\t\tvoid *pTemp = (char *)mem_alloc(DataSize, 1);\n\t\t\tunsigned long UncompressedSize = m_pDataFile->m_Info.m_pDataSizes[Index];\n\t\t\tunsigned long s;\n\n\t\t\tdbg_msg(\"datafile\", \"loading data index=%d size=%d uncompressed=%d\", Index, DataSize, UncompressedSize);\n\t\t\tm_pDataFile->m_ppDataPtrs[Index] = (char *)mem_alloc(UncompressedSize, 1);\n\n\t\t\t// read the compressed data\n\t\t\tio_seek(m_pDataFile->m_File, m_pDataFile->m_DataStartOffset+m_pDataFile->m_Info.m_pDataOffsets[Index], IOSEEK_START);\n\t\t\tio_read(m_pDataFile->m_File, pTemp, DataSize);\n\n\t\t\t// decompress the data, TODO: check for errors\n\t\t\ts = UncompressedSize;\n\t\t\tuncompress((Bytef*)m_pDataFile->m_ppDataPtrs[Index], &s, (Bytef*)pTemp, DataSize); // ignore_convention\n#if defined(CONF_ARCH_ENDIAN_BIG)\n\t\t\tSwapSize = s;\n#endif\n\n\t\t\t// clean up the temporary buffers\n\t\t\tmem_free(pTemp);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// load the data\n\t\t\tdbg_msg(\"datafile\", \"loading data index=%d size=%d\", Index, DataSize);\n\t\t\tm_pDataFile->m_ppDataPtrs[Index] = (char *)mem_alloc(DataSize, 1);\n\t\t\tio_seek(m_pDataFile->m_File, m_pDataFile->m_DataStartOffset+m_pDataFile->m_Info.m_pDataOffsets[Index], IOSEEK_START);\n\t\t\tio_read(m_pDataFile->m_File, m_pDataFile->m_ppDataPtrs[Index], DataSize);\n\t\t}\n\n#if defined(CONF_ARCH_ENDIAN_BIG)\n\t\tif(Swap && SwapSize)\n\t\t\tswap_endian(m_pDataFile->m_ppDataPtrs[Index], sizeof(int), SwapSize/sizeof(int));\n#endif\n\t}\n\n\treturn m_pDataFile->m_ppDataPtrs[Index];\n}\n\nvoid *CDataFileReader::GetData(int Index)\n{\n\treturn GetDataImpl(Index, 0);\n}\n\nvoid *CDataFileReader::GetDataSwapped(int Index)\n{\n\treturn GetDataImpl(Index, 1);\n}\n\nvoid CDataFileReader::UnloadData(int Index)\n{\n\tif(Index < 0)\n\t\treturn;\n\n\t//\n\tmem_free(m_pDataFile->m_ppDataPtrs[Index]);\n\tm_pDataFile->m_ppDataPtrs[Index] = 0x0;\n}\n\nint CDataFileReader::GetItemSize(int Index)\n{\n\tif(!m_pDataFile) { return 0; }\n\tif(Index == m_pDataFile->m_Header.m_NumItems-1)\n\t\treturn m_pDataFile->m_Header.m_ItemSize-m_pDataFile->m_Info.m_pItemOffsets[Index];\n\treturn m_pDataFile->m_Info.m_pItemOffsets[Index+1]-m_pDataFile->m_Info.m_pItemOffsets[Index];\n}\n\nvoid *CDataFileReader::GetItem(int Index, int *pType, int *pID)\n{\n\tif(!m_pDataFile) { if(pType) *pType = 0; if(pID) *pID = 0; return 0; }\n\n\tCDatafileItem *i = (CDatafileItem *)(m_pDataFile->m_Info.m_pItemStart+m_pDataFile->m_Info.m_pItemOffsets[Index]);\n\tif(pType)\n\t\t*pType = (i->m_TypeAndID>>16)&0xffff; // remove sign extention\n\tif(pID)\n\t\t*pID = i->m_TypeAndID&0xffff;\n\treturn (void *)(i+1);\n}\n\nvoid CDataFileReader::GetType(int Type, int *pStart, int *pNum)\n{\n\t*pStart = 0;\n\t*pNum = 0;\n\n\tif(!m_pDataFile)\n\t\treturn;\n\n\tfor(int i = 0; i < m_pDataFile->m_Header.m_NumItemTypes; i++)\n\t{\n\t\tif(m_pDataFile->m_Info.m_pItemTypes[i].m_Type == Type)\n\t\t{\n\t\t\t*pStart = m_pDataFile->m_Info.m_pItemTypes[i].m_Start;\n\t\t\t*pNum = m_pDataFile->m_Info.m_pItemTypes[i].m_Num;\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nvoid *CDataFileReader::FindItem(int Type, int ID)\n{\n\tif(!m_pDataFile) return 0;\n\n\tint Start, Num;\n\tGetType(Type, &Start, &Num);\n\tfor(int i = 0; i < Num; i++)\n\t{\n\t\tint ItemID;\n\t\tvoid *pItem = GetItem(Start+i,0, &ItemID);\n\t\tif(ID == ItemID)\n\t\t\treturn pItem;\n\t}\n\treturn 0;\n}\n\nint CDataFileReader::NumItems()\n{\n\tif(!m_pDataFile) return 0;\n\treturn m_pDataFile->m_Header.m_NumItems;\n}\n\nbool CDataFileReader::Close()\n{\n\tif(!m_pDataFile)\n\t\treturn true;\n\n\t// free the data that is loaded\n\tint i;\n\tfor(i = 0; i < m_pDataFile->m_Header.m_NumRawData; i++)\n\t\tmem_free(m_pDataFile->m_ppDataPtrs[i]);\n\n\tio_close(m_pDataFile->m_File);\n\tmem_free(m_pDataFile);\n\tm_pDataFile = 0;\n\treturn true;\n}\n\nunsigned CDataFileReader::Crc()\n{\n\tif(!m_pDataFile) return 0xFFFFFFFF;\n\treturn m_pDataFile->m_Crc;\n}\n\n\nCDataFileWriter::CDataFileWriter()\n{\n\tm_File = 0;\n\tm_pItemTypes = static_cast<CItemTypeInfo *>(mem_alloc(sizeof(CItemTypeInfo) * MAX_ITEM_TYPES, 1));\n\tm_pItems = static_cast<CItemInfo *>(mem_alloc(sizeof(CItemInfo) * MAX_ITEMS, 1));\n\tm_pDatas = static_cast<CDataInfo *>(mem_alloc(sizeof(CDataInfo) * MAX_DATAS, 1));\n}\n\nCDataFileWriter::~CDataFileWriter()\n{\n\tmem_free(m_pItemTypes);\n\tm_pItemTypes = 0;\n\tmem_free(m_pItems);\n\tm_pItems = 0;\n\tmem_free(m_pDatas);\n\tm_pDatas = 0;\n}\n\nbool CDataFileWriter::Open(class IStorage *pStorage, const char *pFilename)\n{\n\tdbg_assert(!m_File, \"a file already exists\");\n\tm_File = pStorage->OpenFile(pFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE);\n\tif(!m_File)\n\t\treturn false;\n\n\tm_NumItems = 0;\n\tm_NumDatas = 0;\n\tm_NumItemTypes = 0;\n\tmem_zero(m_pItemTypes, sizeof(CItemTypeInfo) * MAX_ITEM_TYPES);\n\n\tfor(int i = 0; i < MAX_ITEM_TYPES; i++)\n\t{\n\t\tm_pItemTypes[i].m_First = -1;\n\t\tm_pItemTypes[i].m_Last = -1;\n\t}\n\n\treturn true;\n}\n\nint CDataFileWriter::AddItem(int Type, int ID, int Size, void *pData)\n{\n\tif(!m_File) return 0;\n\n\tdbg_assert(Type >= 0 && Type < 0xFFFF, \"incorrect type\");\n\tdbg_assert(m_NumItems < 1024, \"too many items\");\n\tdbg_assert(Size%sizeof(int) == 0, \"incorrect boundary\");\n\n\tm_pItems[m_NumItems].m_Type = Type;\n\tm_pItems[m_NumItems].m_ID = ID;\n\tm_pItems[m_NumItems].m_Size = Size;\n\n\t// copy data\n\tm_pItems[m_NumItems].m_pData = mem_alloc(Size, 1);\n\tmem_copy(m_pItems[m_NumItems].m_pData, pData, Size);\n\n\tif(!m_pItemTypes[Type].m_Num) // count item types\n\t\tm_NumItemTypes++;\n\n\t// link\n\tm_pItems[m_NumItems].m_Prev = m_pItemTypes[Type].m_Last;\n\tm_pItems[m_NumItems].m_Next = -1;\n\n\tif(m_pItemTypes[Type].m_Last != -1)\n\t\tm_pItems[m_pItemTypes[Type].m_Last].m_Next = m_NumItems;\n\tm_pItemTypes[Type].m_Last = m_NumItems;\n\n\tif(m_pItemTypes[Type].m_First == -1)\n\t\tm_pItemTypes[Type].m_First = m_NumItems;\n\n\tm_pItemTypes[Type].m_Num++;\n\n\tm_NumItems++;\n\treturn m_NumItems-1;\n}\n\nint CDataFileWriter::AddData(int Size, void *pData)\n{\n\tif(!m_File) return 0;\n\n\tdbg_assert(m_NumDatas < 1024, \"too much data\");\n\n\tCDataInfo *pInfo = &m_pDatas[m_NumDatas];\n\tunsigned long s = compressBound(Size);\n\tvoid *pCompData = mem_alloc(s, 1); // temporary buffer that we use during compression\n\n\tint Result = compress((Bytef*)pCompData, &s, (Bytef*)pData, Size); // ignore_convention\n\tif(Result != Z_OK)\n\t{\n\t\tdbg_msg(\"datafile\", \"compression error %d\", Result);\n\t\tdbg_assert(0, \"zlib error\");\n\t}\n\n\tpInfo->m_UncompressedSize = Size;\n\tpInfo->m_CompressedSize = (int)s;\n\tpInfo->m_pCompressedData = mem_alloc(pInfo->m_CompressedSize, 1);\n\tmem_copy(pInfo->m_pCompressedData, pCompData, pInfo->m_CompressedSize);\n\tmem_free(pCompData);\n\n\tm_NumDatas++;\n\treturn m_NumDatas-1;\n}\n\nint CDataFileWriter::AddDataSwapped(int Size, void *pData)\n{\n\tdbg_assert(Size%sizeof(int) == 0, \"incorrect boundary\");\n\n#if defined(CONF_ARCH_ENDIAN_BIG)\n\tvoid *pSwapped = mem_alloc(Size, 1); // temporary buffer that we use during compression\n\tmem_copy(pSwapped, pData, Size);\n\tswap_endian(pSwapped, sizeof(int), Size/sizeof(int));\n\tint Index = AddData(Size, pSwapped);\n\tmem_free(pSwapped);\n\treturn Index;\n#else\n\treturn AddData(Size, pData);\n#endif\n}\n\n\nint CDataFileWriter::Finish()\n{\n\tif(!m_File) return 1;\n\n\tint ItemSize = 0;\n\tint TypesSize, HeaderSize, OffsetSize, FileSize, SwapSize;\n\tint DataSize = 0;\n\tCDatafileHeader Header;\n\n\t// we should now write this file!\n\tif(DEBUG)\n\t\tdbg_msg(\"datafile\", \"writing\");\n\n\t// calculate sizes\n\tfor(int i = 0; i < m_NumItems; i++)\n\t{\n\t\tif(DEBUG)\n\t\t\tdbg_msg(\"datafile\", \"item=%d size=%d (%d)\", i, m_pItems[i].m_Size, m_pItems[i].m_Size+sizeof(CDatafileItem));\n\t\tItemSize += m_pItems[i].m_Size + sizeof(CDatafileItem);\n\t}\n\n\n\tfor(int i = 0; i < m_NumDatas; i++)\n\t\tDataSize += m_pDatas[i].m_CompressedSize;\n\n\t// calculate the complete size\n\tTypesSize = m_NumItemTypes*sizeof(CDatafileItemType);\n\tHeaderSize = sizeof(CDatafileHeader);\n\tOffsetSize = (m_NumItems + m_NumDatas + m_NumDatas) * sizeof(int); // ItemOffsets, DataOffsets, DataUncompressedSizes\n\tFileSize = HeaderSize + TypesSize + OffsetSize + ItemSize + DataSize;\n\tSwapSize = FileSize - DataSize;\n\n\t(void)SwapSize;\n\n\tif(DEBUG)\n\t\tdbg_msg(\"datafile\", \"num_m_aItemTypes=%d TypesSize=%d m_aItemsize=%d DataSize=%d\", m_NumItemTypes, TypesSize, ItemSize, DataSize);\n\n\t// construct Header\n\t{\n\t\tHeader.m_aID[0] = 'D';\n\t\tHeader.m_aID[1] = 'A';\n\t\tHeader.m_aID[2] = 'T';\n\t\tHeader.m_aID[3] = 'A';\n\t\tHeader.m_Version = 4;\n\t\tHeader.m_Size = FileSize - 16;\n\t\tHeader.m_Swaplen = SwapSize - 16;\n\t\tHeader.m_NumItemTypes = m_NumItemTypes;\n\t\tHeader.m_NumItems = m_NumItems;\n\t\tHeader.m_NumRawData = m_NumDatas;\n\t\tHeader.m_ItemSize = ItemSize;\n\t\tHeader.m_DataSize = DataSize;\n\n\t\t// write Header\n\t\tif(DEBUG)\n\t\t\tdbg_msg(\"datafile\", \"HeaderSize=%d\", sizeof(Header));\n#if defined(CONF_ARCH_ENDIAN_BIG)\n\t\tswap_endian(&Header, sizeof(int), sizeof(Header)/sizeof(int));\n#endif\n\t\tio_write(m_File, &Header, sizeof(Header));\n\t}\n\n\t// write types\n\tfor(int i = 0, Count = 0; i < 0xffff; i++)\n\t{\n\t\tif(m_pItemTypes[i].m_Num)\n\t\t{\n\t\t\t// write info\n\t\t\tCDatafileItemType Info;\n\t\t\tInfo.m_Type = i;\n\t\t\tInfo.m_Start = Count;\n\t\t\tInfo.m_Num = m_pItemTypes[i].m_Num;\n\t\t\tif(DEBUG)\n\t\t\t\tdbg_msg(\"datafile\", \"writing type=%x start=%d num=%d\", Info.m_Type, Info.m_Start, Info.m_Num);\n#if defined(CONF_ARCH_ENDIAN_BIG)\n\t\t\tswap_endian(&Info, sizeof(int), sizeof(CDatafileItemType)/sizeof(int));\n#endif\n\t\t\tio_write(m_File, &Info, sizeof(Info));\n\t\t\tCount += m_pItemTypes[i].m_Num;\n\t\t}\n\t}\n\n\t// write item offsets\n\tfor(int i = 0, Offset = 0; i < 0xffff; i++)\n\t{\n\t\tif(m_pItemTypes[i].m_Num)\n\t\t{\n\t\t\t// write all m_pItems in of this type\n\t\t\tint k = m_pItemTypes[i].m_First;\n\t\t\twhile(k != -1)\n\t\t\t{\n\t\t\t\tif(DEBUG)\n\t\t\t\t\tdbg_msg(\"datafile\", \"writing item offset num=%d offset=%d\", k, Offset);\n\t\t\t\tint Temp = Offset;\n#if defined(CONF_ARCH_ENDIAN_BIG)\n\t\t\t\tswap_endian(&Temp, sizeof(int), sizeof(Temp)/sizeof(int));\n#endif\n\t\t\t\tio_write(m_File, &Temp, sizeof(Temp));\n\t\t\t\tOffset += m_pItems[k].m_Size + sizeof(CDatafileItem);\n\n\t\t\t\t// next\n\t\t\t\tk = m_pItems[k].m_Next;\n\t\t\t}\n\t\t}\n\t}\n\n\t// write data offsets\n\tfor(int i = 0, Offset = 0; i < m_NumDatas; i++)\n\t{\n\t\tif(DEBUG)\n\t\t\tdbg_msg(\"datafile\", \"writing data offset num=%d offset=%d\", i, Offset);\n\t\tint Temp = Offset;\n#if defined(CONF_ARCH_ENDIAN_BIG)\n\t\tswap_endian(&Temp, sizeof(int), sizeof(Temp)/sizeof(int));\n#endif\n\t\tio_write(m_File, &Temp, sizeof(Temp));\n\t\tOffset += m_pDatas[i].m_CompressedSize;\n\t}\n\n\t// write data uncompressed sizes\n\tfor(int i = 0; i < m_NumDatas; i++)\n\t{\n\t\tif(DEBUG)\n\t\t\tdbg_msg(\"datafile\", \"writing data uncompressed size num=%d size=%d\", i, m_pDatas[i].m_UncompressedSize);\n\t\tint UncompressedSize = m_pDatas[i].m_UncompressedSize;\n#if defined(CONF_ARCH_ENDIAN_BIG)\n\t\tswap_endian(&UncompressedSize, sizeof(int), sizeof(UncompressedSize)/sizeof(int));\n#endif\n\t\tio_write(m_File, &UncompressedSize, sizeof(UncompressedSize));\n\t}\n\n\t// write m_pItems\n\tfor(int i = 0; i < 0xffff; i++)\n\t{\n\t\tif(m_pItemTypes[i].m_Num)\n\t\t{\n\t\t\t// write all m_pItems in of this type\n\t\t\tint k = m_pItemTypes[i].m_First;\n\t\t\twhile(k != -1)\n\t\t\t{\n\t\t\t\tCDatafileItem Item;\n\t\t\t\tItem.m_TypeAndID = (i<<16)|m_pItems[k].m_ID;\n\t\t\t\tItem.m_Size = m_pItems[k].m_Size;\n\t\t\t\tif(DEBUG)\n\t\t\t\t\tdbg_msg(\"datafile\", \"writing item type=%x idx=%d id=%d size=%d\", i, k, m_pItems[k].m_ID, m_pItems[k].m_Size);\n\n#if defined(CONF_ARCH_ENDIAN_BIG)\n\t\t\t\tswap_endian(&Item, sizeof(int), sizeof(Item)/sizeof(int));\n\t\t\t\tswap_endian(m_pItems[k].m_pData, sizeof(int), m_pItems[k].m_Size/sizeof(int));\n#endif\n\t\t\t\tio_write(m_File, &Item, sizeof(Item));\n\t\t\t\tio_write(m_File, m_pItems[k].m_pData, m_pItems[k].m_Size);\n\n\t\t\t\t// next\n\t\t\t\tk = m_pItems[k].m_Next;\n\t\t\t}\n\t\t}\n\t}\n\n\t// write data\n\tfor(int i = 0; i < m_NumDatas; i++)\n\t{\n\t\tif(DEBUG)\n\t\t\tdbg_msg(\"datafile\", \"writing data id=%d size=%d\", i, m_pDatas[i].m_CompressedSize);\n\t\tio_write(m_File, m_pDatas[i].m_pCompressedData, m_pDatas[i].m_CompressedSize);\n\t}\n\n\t// free data\n\tfor(int i = 0; i < m_NumItems; i++)\n\t\tmem_free(m_pItems[i].m_pData);\n\tfor(int i = 0; i < m_NumDatas; ++i)\n\t\tmem_free(m_pDatas[i].m_pCompressedData);\n\n\tio_close(m_File);\n\tm_File = 0;\n\n\tif(DEBUG)\n\t\tdbg_msg(\"datafile\", \"done\");\n\treturn 0;\n}\n"
  },
  {
    "path": "src/engine/shared/datafile.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SHARED_DATAFILE_H\n#define ENGINE_SHARED_DATAFILE_H\n\n// raw datafile access\nclass CDataFileReader\n{\n\tstruct CDatafile *m_pDataFile;\n\tvoid *GetDataImpl(int Index, int Swap);\npublic:\n\tCDataFileReader() : m_pDataFile(0) {}\n\t~CDataFileReader() { Close(); }\n\n\tbool IsOpen() const { return m_pDataFile != 0; }\n\n\tbool Open(class IStorage *pStorage, const char *pFilename, int StorageType);\n\tbool Close();\n\n\tstatic bool GetCrcSize(class IStorage *pStorage, const char *pFilename, int StorageType, unsigned *pCrc, unsigned *pSize);\n\n\tvoid *GetData(int Index);\n\tvoid *GetDataSwapped(int Index); // makes sure that the data is 32bit LE ints when saved\n\tint GetDataSize(int Index);\n\tvoid UnloadData(int Index);\n\tvoid *GetItem(int Index, int *pType, int *pID);\n\tint GetItemSize(int Index);\n\tvoid GetType(int Type, int *pStart, int *pNum);\n\tvoid *FindItem(int Type, int ID);\n\tint NumItems();\n\tint NumData();\n\tvoid Unload();\n\n\tunsigned Crc();\n};\n\n// write access\nclass CDataFileWriter\n{\n\tstruct CDataInfo\n\t{\n\t\tint m_UncompressedSize;\n\t\tint m_CompressedSize;\n\t\tvoid *m_pCompressedData;\n\t};\n\n\tstruct CItemInfo\n\t{\n\t\tint m_Type;\n\t\tint m_ID;\n\t\tint m_Size;\n\t\tint m_Next;\n\t\tint m_Prev;\n\t\tvoid *m_pData;\n\t};\n\n\tstruct CItemTypeInfo\n\t{\n\t\tint m_Num;\n\t\tint m_First;\n\t\tint m_Last;\n\t};\n\n\tenum\n\t{\n\t\tMAX_ITEM_TYPES=0xffff,\n\t\tMAX_ITEMS=1024,\n\t\tMAX_DATAS=1024,\n\t};\n\n\tIOHANDLE m_File;\n\tint m_NumItems;\n\tint m_NumDatas;\n\tint m_NumItemTypes;\n\tCItemTypeInfo *m_pItemTypes;\n\tCItemInfo *m_pItems;\n\tCDataInfo *m_pDatas;\n\npublic:\n\tCDataFileWriter();\n\t~CDataFileWriter();\n\tbool Open(class IStorage *pStorage, const char *Filename);\n\tint AddData(int Size, void *pData);\n\tint AddDataSwapped(int Size, void *pData);\n\tint AddItem(int Type, int ID, int Size, void *pData);\n\tint Finish();\n};\n\n\n#endif\n"
  },
  {
    "path": "src/engine/shared/demo.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/math.h>\n#include <base/system.h>\n\n#include <engine/console.h>\n#include <engine/storage.h>\n\n#include \"compression.h\"\n#include \"demo.h\"\n#include \"memheap.h\"\n#include \"network.h\"\n#include \"snapshot.h\"\n\nstatic const unsigned char gs_aHeaderMarker[7] = {'T', 'W', 'D', 'E', 'M', 'O', 0};\nstatic const unsigned char gs_ActVersion = 4;\nstatic const int gs_LengthOffset = 152;\nstatic const int gs_NumMarkersOffset = 176;\n\n\nCDemoRecorder::CDemoRecorder(class CSnapshotDelta *pSnapshotDelta)\n{\n\tm_File = 0;\n\tm_LastTickMarker = -1;\n\tm_pSnapshotDelta = pSnapshotDelta;\n}\n\n// Record\nint CDemoRecorder::Start(class IStorage *pStorage, class IConsole *pConsole, const char *pFilename, const char *pNetVersion, const char *pMap, unsigned Crc, const char *pType)\n{\n\tCDemoHeader Header;\n\tif(m_File)\n\t\treturn -1;\n\n\tm_pConsole = pConsole;\n\n\t// open mapfile\n\tchar aMapFilename[128];\n\t// try the normal maps folder\n\tstr_format(aMapFilename, sizeof(aMapFilename), \"maps/%s.map\", pMap);\n\tIOHANDLE MapFile = pStorage->OpenFile(aMapFilename, IOFLAG_READ, IStorage::TYPE_ALL);\n\tif(!MapFile)\n\t{\n\t\t// try the downloaded maps\n\t\tstr_format(aMapFilename, sizeof(aMapFilename), \"downloadedmaps/%s_%08x.map\", pMap, Crc);\n\t\tMapFile = pStorage->OpenFile(aMapFilename, IOFLAG_READ, IStorage::TYPE_ALL);\n\t}\n\tif(!MapFile)\n\t{\n\t\t// search for the map within subfolders\n\t\tchar aBuf[512];\n\t\tstr_format(aMapFilename, sizeof(aMapFilename), \"%s.map\", pMap);\n\t\tif(pStorage->FindFile(aMapFilename, \"maps\", IStorage::TYPE_ALL, aBuf, sizeof(aBuf)))\n\t\t\tMapFile = pStorage->OpenFile(aBuf, IOFLAG_READ, IStorage::TYPE_ALL);\n\t}\n\tif(!MapFile)\n\t{\n\t\tchar aBuf[256];\n\t\tstr_format(aBuf, sizeof(aBuf), \"Unable to open mapfile '%s'\", pMap);\n\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"demo_recorder\", aBuf);\n\t\treturn -1;\n\t}\n\n\tIOHANDLE DemoFile = pStorage->OpenFile(pFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE);\n\tif(!DemoFile)\n\t{\n\t\tio_close(MapFile);\n\t\tMapFile = 0;\n\t\tchar aBuf[256];\n\t\tstr_format(aBuf, sizeof(aBuf), \"Unable to open '%s' for recording\", pFilename);\n\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"demo_recorder\", aBuf);\n\t\treturn -1;\n\t}\n\n\t// write header\n\tmem_zero(&Header, sizeof(Header));\n\tmem_copy(Header.m_aMarker, gs_aHeaderMarker, sizeof(Header.m_aMarker));\n\tHeader.m_Version = gs_ActVersion;\n\tstr_copy(Header.m_aNetversion, pNetVersion, sizeof(Header.m_aNetversion));\n\tstr_copy(Header.m_aMapName, pMap, sizeof(Header.m_aMapName));\n\tunsigned MapSize = io_length(MapFile);\n\tHeader.m_aMapSize[0] = (MapSize>>24)&0xff;\n\tHeader.m_aMapSize[1] = (MapSize>>16)&0xff;\n\tHeader.m_aMapSize[2] = (MapSize>>8)&0xff;\n\tHeader.m_aMapSize[3] = (MapSize)&0xff;\n\tHeader.m_aMapCrc[0] = (Crc>>24)&0xff;\n\tHeader.m_aMapCrc[1] = (Crc>>16)&0xff;\n\tHeader.m_aMapCrc[2] = (Crc>>8)&0xff;\n\tHeader.m_aMapCrc[3] = (Crc)&0xff;\n\tstr_copy(Header.m_aType, pType, sizeof(Header.m_aType));\n\t// Header.m_Length - add this on stop\n\tstr_timestamp(Header.m_aTimestamp, sizeof(Header.m_aTimestamp));\n\t// Header.m_aNumTimelineMarkers - add this on stop\n\t// Header.m_aTimelineMarkers - add this on stop\n\tio_write(DemoFile, &Header, sizeof(Header));\n\n\t// write map data\n\twhile(1)\n\t{\n\t\tunsigned char aChunk[1024*64];\n\t\tint Bytes = io_read(MapFile, &aChunk, sizeof(aChunk));\n\t\tif(Bytes <= 0)\n\t\t\tbreak;\n\t\tio_write(DemoFile, &aChunk, Bytes);\n\t}\n\tio_close(MapFile);\n\n\tm_LastKeyFrame = -1;\n\tm_LastTickMarker = -1;\n\tm_FirstTick = -1;\n\tm_NumTimelineMarkers = 0;\n\n\tchar aBuf[256];\n\tstr_format(aBuf, sizeof(aBuf), \"Recording to '%s'\", pFilename);\n\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"demo_recorder\", aBuf);\n\tm_File = DemoFile;\n\n\treturn 0;\n}\n\n/*\n\tTickmarker\n\t\t7\t= Always set\n\t\t6\t= Keyframe flag\n\t\t0-5\t= Delta tick\n\n\tNormal\n\t\t7 = Not set\n\t\t5-6\t= Type\n\t\t0-4\t= Size\n*/\n\nenum\n{\n\tCHUNKTYPEFLAG_TICKMARKER = 0x80,\n\tCHUNKTICKFLAG_KEYFRAME = 0x40, // only when tickmarker is set\n\n\tCHUNKMASK_TICK = 0x3f,\n\tCHUNKMASK_TYPE = 0x60,\n\tCHUNKMASK_SIZE = 0x1f,\n\n\tCHUNKTYPE_SNAPSHOT = 1,\n\tCHUNKTYPE_MESSAGE = 2,\n\tCHUNKTYPE_DELTA = 3,\n\n\tCHUNKFLAG_BIGSIZE = 0x10\n};\n\nvoid CDemoRecorder::WriteTickMarker(int Tick, int Keyframe)\n{\n\tif(m_LastTickMarker == -1 || Tick-m_LastTickMarker > 63 || Keyframe)\n\t{\n\t\tunsigned char aChunk[5];\n\t\taChunk[0] = CHUNKTYPEFLAG_TICKMARKER;\n\t\taChunk[1] = (Tick>>24)&0xff;\n\t\taChunk[2] = (Tick>>16)&0xff;\n\t\taChunk[3] = (Tick>>8)&0xff;\n\t\taChunk[4] = (Tick)&0xff;\n\n\t\tif(Keyframe)\n\t\t\taChunk[0] |= CHUNKTICKFLAG_KEYFRAME;\n\n\t\tio_write(m_File, aChunk, sizeof(aChunk));\n\t}\n\telse\n\t{\n\t\tunsigned char aChunk[1];\n\t\taChunk[0] = CHUNKTYPEFLAG_TICKMARKER | (Tick-m_LastTickMarker);\n\t\tio_write(m_File, aChunk, sizeof(aChunk));\n\t}\n\n\tm_LastTickMarker = Tick;\n\tif(m_FirstTick < 0)\n\t\tm_FirstTick = Tick;\n}\n\nvoid CDemoRecorder::Write(int Type, const void *pData, int Size)\n{\n\tchar aBuffer[64*1024];\n\tchar aBuffer2[64*1024];\n\tunsigned char aChunk[3];\n\n\tif(!m_File)\n\t\treturn;\n\n\t/* pad the data with 0 so we get an alignment of 4,\n\telse the compression won't work and miss some bytes */\n\tmem_copy(aBuffer2, pData, Size);\n\twhile(Size&3)\n\t\taBuffer2[Size++] = 0;\n\tSize = CVariableInt::Compress(aBuffer2, Size, aBuffer); // buffer2 -> buffer\n\tSize = CNetBase::Compress(aBuffer, Size, aBuffer2, sizeof(aBuffer2)); // buffer -> buffer2\n\n\n\taChunk[0] = ((Type&0x3)<<5);\n\tif(Size < 30)\n\t{\n\t\taChunk[0] |= Size;\n\t\tio_write(m_File, aChunk, 1);\n\t}\n\telse\n\t{\n\t\tif(Size < 256)\n\t\t{\n\t\t\taChunk[0] |= 30;\n\t\t\taChunk[1] = Size&0xff;\n\t\t\tio_write(m_File, aChunk, 2);\n\t\t}\n\t\telse\n\t\t{\n\t\t\taChunk[0] |= 31;\n\t\t\taChunk[1] = Size&0xff;\n\t\t\taChunk[2] = Size>>8;\n\t\t\tio_write(m_File, aChunk, 3);\n\t\t}\n\t}\n\n\tio_write(m_File, aBuffer2, Size);\n}\n\nvoid CDemoRecorder::RecordSnapshot(int Tick, const void *pData, int Size)\n{\n\tif(m_LastKeyFrame == -1 || (Tick-m_LastKeyFrame) > SERVER_TICK_SPEED*5)\n\t{\n\t\t// write full tickmarker\n\t\tWriteTickMarker(Tick, 1);\n\n\t\t// write snapshot\n\t\tWrite(CHUNKTYPE_SNAPSHOT, pData, Size);\n\n\t\tm_LastKeyFrame = Tick;\n\t\tmem_copy(m_aLastSnapshotData, pData, Size);\n\t}\n\telse\n\t{\n\t\t// create delta, prepend tick\n\t\tchar aDeltaData[CSnapshot::MAX_SIZE+sizeof(int)];\n\t\tint DeltaSize;\n\n\t\t// write tickmarker\n\t\tWriteTickMarker(Tick, 0);\n\n\t\tDeltaSize = m_pSnapshotDelta->CreateDelta((CSnapshot*)m_aLastSnapshotData, (CSnapshot*)pData, &aDeltaData);\n\t\tif(DeltaSize)\n\t\t{\n\t\t\t// record delta\n\t\t\tWrite(CHUNKTYPE_DELTA, aDeltaData, DeltaSize);\n\t\t\tmem_copy(m_aLastSnapshotData, pData, Size);\n\t\t}\n\t}\n}\n\nvoid CDemoRecorder::RecordMessage(const void *pData, int Size)\n{\n\tWrite(CHUNKTYPE_MESSAGE, pData, Size);\n}\n\nint CDemoRecorder::Stop()\n{\n\tif(!m_File)\n\t\treturn -1;\n\n\t// add the demo length to the header\n\tio_seek(m_File, gs_LengthOffset, IOSEEK_START);\n\tint DemoLength = Length();\n\tchar aLength[4];\n\taLength[0] = (DemoLength>>24)&0xff;\n\taLength[1] = (DemoLength>>16)&0xff;\n\taLength[2] = (DemoLength>>8)&0xff;\n\taLength[3] = (DemoLength)&0xff;\n\tio_write(m_File, aLength, sizeof(aLength));\n\n\t// add the timeline markers to the header\n\tio_seek(m_File, gs_NumMarkersOffset, IOSEEK_START);\n\tchar aNumMarkers[4];\n\taNumMarkers[0] = (m_NumTimelineMarkers>>24)&0xff;\n\taNumMarkers[1] = (m_NumTimelineMarkers>>16)&0xff;\n\taNumMarkers[2] = (m_NumTimelineMarkers>>8)&0xff;\n\taNumMarkers[3] = (m_NumTimelineMarkers)&0xff;\n\tio_write(m_File, aNumMarkers, sizeof(aNumMarkers));\n\tfor(int i = 0; i < m_NumTimelineMarkers; i++)\n\t{\n\t\tint Marker = m_aTimelineMarkers[i];\n\t\tchar aMarker[4];\n\t\taMarker[0] = (Marker>>24)&0xff;\n\t\taMarker[1] = (Marker>>16)&0xff;\n\t\taMarker[2] = (Marker>>8)&0xff;\n\t\taMarker[3] = (Marker)&0xff;\n\t\tio_write(m_File, aMarker, sizeof(aMarker));\n\t}\n\n\tio_close(m_File);\n\tm_File = 0;\n\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"demo_recorder\", \"Stopped recording\");\n\n\treturn 0;\n}\n\nvoid CDemoRecorder::AddDemoMarker()\n{\n\tif(m_LastTickMarker < 0 || m_NumTimelineMarkers >= MAX_TIMELINE_MARKERS)\n\t\treturn;\n\n\t// not more than 1 marker in a second\n\tif(m_NumTimelineMarkers > 0)\n\t{\n\t\tint Diff = m_LastTickMarker - m_aTimelineMarkers[m_NumTimelineMarkers-1];\n\t\tif(Diff < SERVER_TICK_SPEED*1.0f)\n\t\t\treturn;\n\t}\n\n\tm_aTimelineMarkers[m_NumTimelineMarkers++] = m_LastTickMarker;\n\n\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"demo_recorder\", \"Added timeline marker\");\n}\n\n\n\nCDemoPlayer::CDemoPlayer(class CSnapshotDelta *pSnapshotDelta)\n{\n\tm_File = 0;\n\tm_aErrorMsg[0] = 0;\n\tm_pKeyFrames = 0;\n\n\tm_pSnapshotDelta = pSnapshotDelta;\n\tm_LastSnapshotDataSize = -1;\n}\n\nvoid CDemoPlayer::SetListner(IListner *pListner)\n{\n\tm_pListner = pListner;\n}\n\n\nint CDemoPlayer::ReadChunkHeader(int *pType, int *pSize, int *pTick)\n{\n\tunsigned char Chunk = 0;\n\n\t*pSize = 0;\n\t*pType = 0;\n\n\tif(io_read(m_File, &Chunk, sizeof(Chunk)) != sizeof(Chunk))\n\t\treturn -1;\n\n\tif(Chunk&CHUNKTYPEFLAG_TICKMARKER)\n\t{\n\t\t// decode tick marker\n\t\tint Tickdelta = Chunk&(CHUNKMASK_TICK);\n\t\t*pType = Chunk&(CHUNKTYPEFLAG_TICKMARKER|CHUNKTICKFLAG_KEYFRAME);\n\n\t\tif(Tickdelta == 0)\n\t\t{\n\t\t\tunsigned char aTickdata[4];\n\t\t\tif(io_read(m_File, aTickdata, sizeof(aTickdata)) != sizeof(aTickdata))\n\t\t\t\treturn -1;\n\t\t\t*pTick = (aTickdata[0]<<24) | (aTickdata[1]<<16) | (aTickdata[2]<<8) | aTickdata[3];\n\t\t}\n\t\telse\n\t\t{\n\t\t\t*pTick += Tickdelta;\n\t\t}\n\n\t}\n\telse\n\t{\n\t\t// decode normal chunk\n\t\t*pType = (Chunk&CHUNKMASK_TYPE)>>5;\n\t\t*pSize = Chunk&CHUNKMASK_SIZE;\n\n\t\tif(*pSize == 30)\n\t\t{\n\t\t\tunsigned char aSizedata[1];\n\t\t\tif(io_read(m_File, aSizedata, sizeof(aSizedata)) != sizeof(aSizedata))\n\t\t\t\treturn -1;\n\t\t\t*pSize = aSizedata[0];\n\n\t\t}\n\t\telse if(*pSize == 31)\n\t\t{\n\t\t\tunsigned char aSizedata[2];\n\t\t\tif(io_read(m_File, aSizedata, sizeof(aSizedata)) != sizeof(aSizedata))\n\t\t\t\treturn -1;\n\t\t\t*pSize = (aSizedata[1]<<8) | aSizedata[0];\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nvoid CDemoPlayer::ScanFile()\n{\n\tlong StartPos;\n\tCHeap Heap;\n\tCKeyFrameSearch *pFirstKey = 0;\n\tCKeyFrameSearch *pCurrentKey = 0;\n\t//DEMOREC_CHUNK chunk;\n\tint ChunkSize, ChunkType, ChunkTick = 0;\n\tint i;\n\n\tStartPos = io_tell(m_File);\n\tm_Info.m_SeekablePoints = 0;\n\n\twhile(1)\n\t{\n\t\tlong CurrentPos = io_tell(m_File);\n\n\t\tif(ReadChunkHeader(&ChunkType, &ChunkSize, &ChunkTick))\n\t\t\tbreak;\n\n\t\t// read the chunk\n\t\tif(ChunkType&CHUNKTYPEFLAG_TICKMARKER)\n\t\t{\n\t\t\tif(ChunkType&CHUNKTICKFLAG_KEYFRAME)\n\t\t\t{\n\t\t\t\tCKeyFrameSearch *pKey;\n\n\t\t\t\t// save the position\n\t\t\t\tpKey = (CKeyFrameSearch *)Heap.Allocate(sizeof(CKeyFrameSearch));\n\t\t\t\tpKey->m_Frame.m_Filepos = CurrentPos;\n\t\t\t\tpKey->m_Frame.m_Tick = ChunkTick;\n\t\t\t\tpKey->m_pNext = 0;\n\t\t\t\tif(pCurrentKey)\n\t\t\t\t\tpCurrentKey->m_pNext = pKey;\n\t\t\t\tif(!pFirstKey)\n\t\t\t\t\tpFirstKey = pKey;\n\t\t\t\tpCurrentKey = pKey;\n\t\t\t\tm_Info.m_SeekablePoints++;\n\t\t\t}\n\n\t\t\tif(m_Info.m_Info.m_FirstTick == -1)\n\t\t\t\tm_Info.m_Info.m_FirstTick = ChunkTick;\n\t\t\tm_Info.m_Info.m_LastTick = ChunkTick;\n\t\t}\n\t\telse if(ChunkSize)\n\t\t\tio_skip(m_File, ChunkSize);\n\n\t}\n\n\t// copy all the frames to an array instead for fast access\n\tm_pKeyFrames = (CKeyFrame*)mem_alloc(m_Info.m_SeekablePoints*sizeof(CKeyFrame), 1);\n\tfor(pCurrentKey = pFirstKey, i = 0; pCurrentKey; pCurrentKey = pCurrentKey->m_pNext, i++)\n\t\tm_pKeyFrames[i] = pCurrentKey->m_Frame;\n\n\t// destroy the temporary heap and seek back to the start\n\tio_seek(m_File, StartPos, IOSEEK_START);\n}\n\nvoid CDemoPlayer::DoTick()\n{\n\tstatic char aCompresseddata[CSnapshot::MAX_SIZE];\n\tstatic char aDecompressed[CSnapshot::MAX_SIZE];\n\tstatic char aData[CSnapshot::MAX_SIZE];\n\tint ChunkType, ChunkTick, ChunkSize;\n\tint DataSize = 0;\n\tint GotSnapshot = 0;\n\n\t// update ticks\n\tm_Info.m_PreviousTick = m_Info.m_Info.m_CurrentTick;\n\tm_Info.m_Info.m_CurrentTick = m_Info.m_NextTick;\n\tChunkTick = m_Info.m_Info.m_CurrentTick;\n\n\twhile(1)\n\t{\n\t\tif(ReadChunkHeader(&ChunkType, &ChunkSize, &ChunkTick))\n\t\t{\n\t\t\t// stop on error or eof\n\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"demo_player\", \"end of file\");\n\t\t\tif(m_Info.m_PreviousTick == -1)\n\t\t\t{\n\t\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"demo_player\", \"empty demo\");\n\t\t\t\tStop();\n\t\t\t}\n\t\t\telse\n\t\t\t\tPause();\n\t\t\tbreak;\n\t\t}\n\n\t\t// read the chunk\n\t\tif(ChunkSize)\n\t\t{\n\t\t\tif(io_read(m_File, aCompresseddata, ChunkSize) != (unsigned)ChunkSize)\n\t\t\t{\n\t\t\t\t// stop on error or eof\n\t\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"demo_player\", \"error reading chunk\");\n\t\t\t\tStop();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tDataSize = CNetBase::Decompress(aCompresseddata, ChunkSize, aDecompressed, sizeof(aDecompressed));\n\t\t\tif(DataSize < 0)\n\t\t\t{\n\t\t\t\t// stop on error or eof\n\t\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"demo_player\", \"error during network decompression\");\n\t\t\t\tStop();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tDataSize = CVariableInt::Decompress(aDecompressed, DataSize, aData);\n\n\t\t\tif(DataSize < 0)\n\t\t\t{\n\t\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"demo_player\", \"error during intpack decompression\");\n\t\t\t\tStop();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif(ChunkType == CHUNKTYPE_DELTA)\n\t\t{\n\t\t\t// process delta snapshot\n\t\t\tstatic char aNewsnap[CSnapshot::MAX_SIZE];\n\n\t\t\tGotSnapshot = 1;\n\n\t\t\tDataSize = m_pSnapshotDelta->UnpackDelta((CSnapshot*)m_aLastSnapshotData, (CSnapshot*)aNewsnap, aData, DataSize);\n\n\t\t\tif(DataSize >= 0)\n\t\t\t{\n\t\t\t\tif(m_pListner)\n\t\t\t\t\tm_pListner->OnDemoPlayerSnapshot(aNewsnap, DataSize);\n\n\t\t\t\tm_LastSnapshotDataSize = DataSize;\n\t\t\t\tmem_copy(m_aLastSnapshotData, aNewsnap, DataSize);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tchar aBuf[256];\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"error during unpacking of delta, err=%d\", DataSize);\n\t\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"demo_player\", aBuf);\n\t\t\t}\n\t\t}\n\t\telse if(ChunkType == CHUNKTYPE_SNAPSHOT)\n\t\t{\n\t\t\t// process full snapshot\n\t\t\tGotSnapshot = 1;\n\n\t\t\tm_LastSnapshotDataSize = DataSize;\n\t\t\tmem_copy(m_aLastSnapshotData, aData, DataSize);\n\t\t\tif(m_pListner)\n\t\t\t\tm_pListner->OnDemoPlayerSnapshot(aData, DataSize);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// if there were no snapshots in this tick, replay the last one\n\t\t\tif(!GotSnapshot && m_pListner && m_LastSnapshotDataSize != -1)\n\t\t\t{\n\t\t\t\tGotSnapshot = 1;\n\t\t\t\tm_pListner->OnDemoPlayerSnapshot(m_aLastSnapshotData, m_LastSnapshotDataSize);\n\t\t\t}\n\n\t\t\t// check the remaining types\n\t\t\tif(ChunkType&CHUNKTYPEFLAG_TICKMARKER)\n\t\t\t{\n\t\t\t\tm_Info.m_NextTick = ChunkTick;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if(ChunkType == CHUNKTYPE_MESSAGE)\n\t\t\t{\n\t\t\t\tif(m_pListner)\n\t\t\t\t\tm_pListner->OnDemoPlayerMessage(aData, DataSize);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid CDemoPlayer::Pause()\n{\n\tm_Info.m_Info.m_Paused = 1;\n}\n\nvoid CDemoPlayer::Unpause()\n{\n\tif(m_Info.m_Info.m_Paused)\n\t{\n\t\t/*m_Info.start_tick = m_Info.current_tick;\n\t\tm_Info.start_time = time_get();*/\n\t\tm_Info.m_Info.m_Paused = 0;\n\t}\n}\n\nconst char *CDemoPlayer::Load(class IStorage *pStorage, class IConsole *pConsole, const char *pFilename, int StorageType, const char *pNetversion)\n{\n\tm_pConsole = pConsole;\n\tm_aErrorMsg[0] = 0;\n\tm_File = pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType);\n\tif(!m_File)\n\t{\n\t\tstr_format(m_aErrorMsg, sizeof(m_aErrorMsg), \"could not open '%s'\", pFilename);\n\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"demo_player\", m_aErrorMsg);\n\t\treturn m_aErrorMsg;\n\t}\n\n\t// store the filename\n\tstr_copy(m_aFilename, pFilename, sizeof(m_aFilename));\n\n\t// clear the playback info\n\tmem_zero(&m_Info, sizeof(m_Info));\n\tm_Info.m_Info.m_FirstTick = -1;\n\tm_Info.m_Info.m_LastTick = -1;\n\tm_Info.m_NextTick = -1;\n\tm_Info.m_Info.m_CurrentTick = -1;\n\tm_Info.m_PreviousTick = -1;\n\tm_Info.m_Info.m_Speed = 1;\n\n\tm_LastSnapshotDataSize = -1;\n\n\t// read the header\n\tio_read(m_File, &m_Info.m_Header, sizeof(m_Info.m_Header));\n\tif(mem_comp(m_Info.m_Header.m_aMarker, gs_aHeaderMarker, sizeof(gs_aHeaderMarker)) != 0)\n\t{\n\t\tstr_format(m_aErrorMsg, sizeof(m_aErrorMsg), \"'%s' is not a demo file\", pFilename);\n\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"demo_player\", m_aErrorMsg);\n\t\tio_close(m_File);\n\t\tm_File = 0;\n\t\treturn m_aErrorMsg;\n\t}\n\n\tif(m_Info.m_Header.m_Version < gs_ActVersion)\n\t{\n\t\tstr_format(m_aErrorMsg, sizeof(m_aErrorMsg), \"demo version %d is not supported\", m_Info.m_Header.m_Version);\n\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"demo_player\", m_aErrorMsg);\n\t\tio_close(m_File);\n\t\tm_File = 0;\n\t\treturn m_aErrorMsg;\n\t}\n\n\tif(str_comp(m_Info.m_Header.m_aNetversion, pNetversion) != 0)\n\t{\n\t\tstr_format(m_aErrorMsg, sizeof(m_aErrorMsg), \"net version '%s' is not supported\", m_Info.m_Header.m_aNetversion);\n\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"demo_player\", m_aErrorMsg);\n\t\tio_close(m_File);\n\t\tm_File = 0;\n\t\treturn m_aErrorMsg;\n\t}\n\n\t// get demo type\n\tif(!str_comp(m_Info.m_Header.m_aType, \"client\"))\n\t\tm_DemoType = DEMOTYPE_CLIENT;\n\telse if(!str_comp(m_Info.m_Header.m_aType, \"server\"))\n\t\tm_DemoType = DEMOTYPE_SERVER;\n\telse\n\t\tm_DemoType = DEMOTYPE_INVALID;\n\n\t// read map\n\tunsigned MapSize = (m_Info.m_Header.m_aMapSize[0]<<24) | (m_Info.m_Header.m_aMapSize[1]<<16) | (m_Info.m_Header.m_aMapSize[2]<<8) | (m_Info.m_Header.m_aMapSize[3]);\n\n\t// check if we already have the map\n\t// TODO: improve map checking (maps folder, check crc)\n\tunsigned Crc = (m_Info.m_Header.m_aMapCrc[0]<<24) | (m_Info.m_Header.m_aMapCrc[1]<<16) | (m_Info.m_Header.m_aMapCrc[2]<<8) | (m_Info.m_Header.m_aMapCrc[3]);\n\tchar aMapFilename[128];\n\tstr_format(aMapFilename, sizeof(aMapFilename), \"downloadedmaps/%s_%08x.map\", m_Info.m_Header.m_aMapName, Crc);\n\tIOHANDLE MapFile = pStorage->OpenFile(aMapFilename, IOFLAG_READ, IStorage::TYPE_ALL);\n\n\tif(MapFile)\n\t{\n\t\tio_skip(m_File, MapSize);\n\t\tio_close(MapFile);\n\t}\n\telse if(MapSize > 0)\n\t{\n\t\t// get map data\n\t\tunsigned char *pMapData = (unsigned char *)mem_alloc(MapSize, 1);\n\t\tio_read(m_File, pMapData, MapSize);\n\n\t\t// save map\n\t\tMapFile = pStorage->OpenFile(aMapFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE);\n\t\tio_write(MapFile, pMapData, MapSize);\n\t\tio_close(MapFile);\n\n\t\t// free data\n\t\tmem_free(pMapData);\n\t}\n\n\t// get timeline markers\n\tint Num = ((m_Info.m_Header.m_aNumTimelineMarkers[0]<<24)&0xFF000000) | ((m_Info.m_Header.m_aNumTimelineMarkers[1]<<16)&0xFF0000) |\n\t\t\t\t((m_Info.m_Header.m_aNumTimelineMarkers[2]<<8)&0xFF00) | (m_Info.m_Header.m_aNumTimelineMarkers[3]&0xFF);\n\tm_Info.m_Info.m_NumTimelineMarkers = Num;\n\tfor(int i = 0; i < Num && i < MAX_TIMELINE_MARKERS; i++)\n\t{\n\t\tchar *pTimelineMarker = m_Info.m_Header.m_aTimelineMarkers[i];\n\t\tm_Info.m_Info.m_aTimelineMarkers[i] = ((pTimelineMarker[0]<<24)&0xFF000000) | ((pTimelineMarker[1]<<16)&0xFF0000) |\n\t\t\t\t\t\t\t\t\t\t\t\t((pTimelineMarker[2]<<8)&0xFF00) | (pTimelineMarker[3]&0xFF);\n\t}\n\n\t// scan the file for interessting points\n\tScanFile();\n\n\t// ready for playback\n\treturn 0;\n}\n\nint CDemoPlayer::NextFrame()\n{\n\tDoTick();\n\treturn IsPlaying();\n}\n\nint CDemoPlayer::Play()\n{\n\t// fill in previous and next tick\n\twhile(m_Info.m_PreviousTick == -1 && IsPlaying())\n\t\tDoTick();\n\n\t// set start info\n\t/*m_Info.start_tick = m_Info.previous_tick;\n\tm_Info.start_time = time_get();*/\n\tm_Info.m_CurrentTime = m_Info.m_PreviousTick*time_freq()/SERVER_TICK_SPEED;\n\tm_Info.m_LastUpdate = time_get();\n\treturn 0;\n}\n\nint CDemoPlayer::SetPos(float Percent)\n{\n\tint Keyframe;\n\tint WantedTick;\n\tif(!m_File)\n\t\treturn -1;\n\n\t// -5 because we have to have a current tick and previous tick when we do the playback\n\tWantedTick = m_Info.m_Info.m_FirstTick + (int)((m_Info.m_Info.m_LastTick-m_Info.m_Info.m_FirstTick)*Percent) - 5;\n\n\tKeyframe = (int)(m_Info.m_SeekablePoints*Percent);\n\n\tif(Keyframe < 0 || Keyframe >= m_Info.m_SeekablePoints)\n\t\treturn -1;\n\n\t// get correct key frame\n\tif(m_pKeyFrames[Keyframe].m_Tick < WantedTick)\n\t\twhile(Keyframe < m_Info.m_SeekablePoints-1 && m_pKeyFrames[Keyframe].m_Tick < WantedTick)\n\t\t\tKeyframe++;\n\n\twhile(Keyframe && m_pKeyFrames[Keyframe].m_Tick > WantedTick)\n\t\tKeyframe--;\n\n\t// seek to the correct keyframe\n\tio_seek(m_File, m_pKeyFrames[Keyframe].m_Filepos, IOSEEK_START);\n\n\t//m_Info.start_tick = -1;\n\tm_Info.m_NextTick = -1;\n\tm_Info.m_Info.m_CurrentTick = -1;\n\tm_Info.m_PreviousTick = -1;\n\n\t// playback everything until we hit our tick\n\twhile(m_Info.m_PreviousTick < WantedTick)\n\t\tDoTick();\n\n\tPlay();\n\n\treturn 0;\n}\n\nvoid CDemoPlayer::SetSpeed(float Speed)\n{\n\tm_Info.m_Info.m_Speed = Speed;\n}\n\nint CDemoPlayer::Update()\n{\n\tint64 Now = time_get();\n\tint64 Deltatime = Now-m_Info.m_LastUpdate;\n\tm_Info.m_LastUpdate = Now;\n\n\tif(!IsPlaying())\n\t\treturn 0;\n\n\tif(m_Info.m_Info.m_Paused)\n\t{\n\n\t}\n\telse\n\t{\n\t\tint64 Freq = time_freq();\n\t\tm_Info.m_CurrentTime += (int64)(Deltatime*(double)m_Info.m_Info.m_Speed);\n\n\t\twhile(1)\n\t\t{\n\t\t\tint64 CurtickStart = (m_Info.m_Info.m_CurrentTick)*Freq/SERVER_TICK_SPEED;\n\n\t\t\t// break if we are ready\n\t\t\tif(CurtickStart > m_Info.m_CurrentTime)\n\t\t\t\tbreak;\n\n\t\t\t// do one more tick\n\t\t\tDoTick();\n\n\t\t\tif(m_Info.m_Info.m_Paused)\n\t\t\t\treturn 0;\n\t\t}\n\n\t\t// update intratick\n\t\t{\n\t\t\tint64 CurtickStart = (m_Info.m_Info.m_CurrentTick)*Freq/SERVER_TICK_SPEED;\n\t\t\tint64 PrevtickStart = (m_Info.m_PreviousTick)*Freq/SERVER_TICK_SPEED;\n\t\t\tm_Info.m_IntraTick = (m_Info.m_CurrentTime - PrevtickStart) / (float)(CurtickStart-PrevtickStart);\n\t\t\tm_Info.m_TickTime = (m_Info.m_CurrentTime - PrevtickStart) / (float)Freq;\n\t\t}\n\n\t\tif(m_Info.m_Info.m_CurrentTick == m_Info.m_PreviousTick ||\n\t\t\tm_Info.m_Info.m_CurrentTick == m_Info.m_NextTick)\n\t\t{\n\t\t\tchar aBuf[256];\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"tick error prev=%d cur=%d next=%d\",\n\t\t\t\tm_Info.m_PreviousTick, m_Info.m_Info.m_CurrentTick, m_Info.m_NextTick);\n\t\t\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"demo_player\", aBuf);\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nint CDemoPlayer::Stop()\n{\n\tif(!m_File)\n\t\treturn -1;\n\n\tm_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"demo_player\", \"Stopped playback\");\n\tio_close(m_File);\n\tm_File = 0;\n\tmem_free(m_pKeyFrames);\n\tm_pKeyFrames = 0;\n\tstr_copy(m_aFilename, \"\", sizeof(m_aFilename));\n\treturn 0;\n}\n\nvoid CDemoPlayer::GetDemoName(char *pBuffer, int BufferSize) const\n{\n\tconst char *pFileName = m_aFilename;\n\tconst char *pExtractedName = pFileName;\n\tconst char *pEnd = 0;\n\tfor(; *pFileName; ++pFileName)\n\t{\n\t\tif(*pFileName == '/' || *pFileName == '\\\\')\n\t\t\tpExtractedName = pFileName+1;\n\t\telse if(*pFileName == '.')\n\t\t\tpEnd = pFileName;\n\t}\n\n\tint Length = pEnd > pExtractedName ? min(BufferSize, (int)(pEnd-pExtractedName+1)) : BufferSize;\n\tstr_copy(pBuffer, pExtractedName, Length);\n}\n\nbool CDemoPlayer::GetDemoInfo(class IStorage *pStorage, const char *pFilename, int StorageType, CDemoHeader *pDemoHeader) const\n{\n\tif(!pDemoHeader)\n\t\treturn false;\n\n\tmem_zero(pDemoHeader, sizeof(CDemoHeader));\n\n\tIOHANDLE File = pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType);\n\tif(!File)\n\t\treturn false;\n\n\tio_read(File, pDemoHeader, sizeof(CDemoHeader));\n\tif(mem_comp(pDemoHeader->m_aMarker, gs_aHeaderMarker, sizeof(gs_aHeaderMarker)) || pDemoHeader->m_Version < gs_ActVersion)\n\t{\n\t\tio_close(File);\n\t\treturn false;\n\t}\n\n\tio_close(File);\n\treturn true;\n}\n\nint CDemoPlayer::GetDemoType() const\n{\n\tif(m_File)\n\t\treturn m_DemoType;\n\treturn DEMOTYPE_INVALID;\n}\n"
  },
  {
    "path": "src/engine/shared/demo.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SHARED_DEMO_H\n#define ENGINE_SHARED_DEMO_H\n\n#include <engine/demo.h>\n#include <engine/shared/protocol.h>\n\n#include \"snapshot.h\"\n\nclass CDemoRecorder : public IDemoRecorder\n{\n\tclass IConsole *m_pConsole;\n\tIOHANDLE m_File;\n\tint m_LastTickMarker;\n\tint m_LastKeyFrame;\n\tint m_FirstTick;\n\tunsigned char m_aLastSnapshotData[CSnapshot::MAX_SIZE];\n\tclass CSnapshotDelta *m_pSnapshotDelta;\n\tint m_NumTimelineMarkers;\n\tint m_aTimelineMarkers[MAX_TIMELINE_MARKERS];\n\n\tvoid WriteTickMarker(int Tick, int Keyframe);\n\tvoid Write(int Type, const void *pData, int Size);\npublic:\n\tCDemoRecorder(class CSnapshotDelta *pSnapshotDelta);\n\n\tint Start(class IStorage *pStorage, class IConsole *pConsole, const char *pFilename, const char *pNetversion, const char *pMap, unsigned MapCrc, const char *pType);\n\tint Stop();\n\tvoid AddDemoMarker();\n\n\tvoid RecordSnapshot(int Tick, const void *pData, int Size);\n\tvoid RecordMessage(const void *pData, int Size);\n\n\tbool IsRecording() const { return m_File != 0; }\n\n\tint Length() const { return (m_LastTickMarker - m_FirstTick)/SERVER_TICK_SPEED; }\n};\n\nclass CDemoPlayer : public IDemoPlayer\n{\npublic:\n\tclass IListner\n\t{\n\tpublic:\n\t\tvirtual ~IListner() {}\n\t\tvirtual void OnDemoPlayerSnapshot(void *pData, int Size) = 0;\n\t\tvirtual void OnDemoPlayerMessage(void *pData, int Size) = 0;\n\t};\n\n\tstruct CPlaybackInfo\n\t{\n\t\tCDemoHeader m_Header;\n\n\t\tIDemoPlayer::CInfo m_Info;\n\n\t\tint64 m_LastUpdate;\n\t\tint64 m_CurrentTime;\n\n\t\tint m_SeekablePoints;\n\n\t\tint m_NextTick;\n\t\tint m_PreviousTick;\n\n\t\tfloat m_IntraTick;\n\t\tfloat m_TickTime;\n\t};\n\nprivate:\n\tIListner *m_pListner;\n\n\n\t// Playback\n\tstruct CKeyFrame\n\t{\n\t\tlong m_Filepos;\n\t\tint m_Tick;\n\t};\n\n\tstruct CKeyFrameSearch\n\t{\n\t\tCKeyFrame m_Frame;\n\t\tCKeyFrameSearch *m_pNext;\n\t};\n\n\tclass IConsole *m_pConsole;\n\tIOHANDLE m_File;\n\tchar m_aFilename[256];\n\tchar m_aErrorMsg[256];\n\tCKeyFrame *m_pKeyFrames;\n\n\tCPlaybackInfo m_Info;\n\tint m_DemoType;\n\tunsigned char m_aLastSnapshotData[CSnapshot::MAX_SIZE];\n\tint m_LastSnapshotDataSize;\n\tclass CSnapshotDelta *m_pSnapshotDelta;\n\n\tint ReadChunkHeader(int *pType, int *pSize, int *pTick);\n\tvoid DoTick();\n\tvoid ScanFile();\n\tint NextFrame();\n\npublic:\n\n\tCDemoPlayer(class CSnapshotDelta *m_pSnapshotDelta);\n\n\tvoid SetListner(IListner *pListner);\n\n\tconst char *Load(class IStorage *pStorage, class IConsole *pConsole, const char *pFilename, int StorageType, const char *pNetversion);\n\tint Play();\n\tvoid Pause();\n\tvoid Unpause();\n\tint Stop();\n\tvoid SetSpeed(float Speed);\n\tint SetPos(float Percent);\n\tconst CInfo *BaseInfo() const { return &m_Info.m_Info; }\n\tvoid GetDemoName(char *pBuffer, int BufferSize) const;\n\tbool GetDemoInfo(class IStorage *pStorage, const char *pFilename, int StorageType, CDemoHeader *pDemoHeader) const;\n\tint GetDemoType() const;\n\n\tint Update();\n\n\tconst CPlaybackInfo *Info() const { return &m_Info; }\n\tint IsPlaying() const { return m_File != 0; }\n};\n\n#endif\n"
  },
  {
    "path": "src/engine/shared/econ.cpp",
    "content": "#include <engine/console.h>\n#include <engine/shared/config.h>\n\n#include \"econ.h\"\n#include \"netban.h\"\n\n\nint CEcon::NewClientCallback(int ClientID, void *pUser)\n{\n\tCEcon *pThis = (CEcon *)pUser;\n\n\tchar aAddrStr[NETADDR_MAXSTRSIZE];\n\tnet_addr_str(pThis->m_NetConsole.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true);\n\tchar aBuf[128];\n\tstr_format(aBuf, sizeof(aBuf), \"client accepted. cid=%d addr=%s'\", ClientID, aAddrStr);\n\tpThis->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"econ\", aBuf);\n\n\tpThis->m_aClients[ClientID].m_State = CClient::STATE_CONNECTED;\n\tpThis->m_aClients[ClientID].m_TimeConnected = time_get();\n\tpThis->m_aClients[ClientID].m_AuthTries = 0;\n\n\tpThis->m_NetConsole.Send(ClientID, \"Enter password:\");\n\treturn 0;\n}\n\nint CEcon::DelClientCallback(int ClientID, const char *pReason, void *pUser)\n{\n\tCEcon *pThis = (CEcon *)pUser;\n\n\tchar aAddrStr[NETADDR_MAXSTRSIZE];\n\tnet_addr_str(pThis->m_NetConsole.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true);\n\tchar aBuf[256];\n\tstr_format(aBuf, sizeof(aBuf), \"client dropped. cid=%d addr=%s reason='%s'\", ClientID, aAddrStr, pReason);\n\tpThis->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"econ\", aBuf);\n\n\tpThis->m_aClients[ClientID].m_State = CClient::STATE_EMPTY;\n\treturn 0;\n}\n\nvoid CEcon::SendLineCB(const char *pLine, void *pUserData)\n{\n\tstatic_cast<CEcon *>(pUserData)->Send(-1, pLine);\n}\n\nvoid CEcon::ConchainEconOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)\n{\n\tpfnCallback(pResult, pCallbackUserData);\n\tif(pResult->NumArguments() == 1)\n\t{\n\t\tCEcon *pThis = static_cast<CEcon *>(pUserData);\n\t\tpThis->Console()->SetPrintOutputLevel(pThis->m_PrintCBIndex, pResult->GetInteger(0));\n\t}\n}\n\nvoid CEcon::ConLogout(IConsole::IResult *pResult, void *pUserData)\n{\n\tCEcon *pThis = static_cast<CEcon *>(pUserData);\n\n\tif(pThis->m_UserClientID >= 0 && pThis->m_UserClientID < NET_MAX_CONSOLE_CLIENTS && pThis->m_aClients[pThis->m_UserClientID].m_State != CClient::STATE_EMPTY)\n\t\tpThis->m_NetConsole.Drop(pThis->m_UserClientID, \"Logout\");\n}\n\nvoid CEcon::Init(IConsole *pConsole, CNetBan *pNetBan)\n{\n\tm_pConsole = pConsole;\n\n\tfor(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++)\n\t\tm_aClients[i].m_State = CClient::STATE_EMPTY;\n\n\tm_Ready = false;\n\tm_UserClientID = -1;\n\n\tif(g_Config.m_EcPort == 0 || g_Config.m_EcPassword[0] == 0)\n\t\treturn;\n\n\tNETADDR BindAddr;\n\tif(g_Config.m_EcBindaddr[0] && net_host_lookup(g_Config.m_EcBindaddr, &BindAddr, NETTYPE_ALL) == 0)\n\t{\n\t\t// got bindaddr\n\t\tBindAddr.type = NETTYPE_ALL;\n\t\tBindAddr.port = g_Config.m_EcPort;\n\t}\n\telse\n\t{\n\t\tmem_zero(&BindAddr, sizeof(BindAddr));\n\t\tBindAddr.type = NETTYPE_ALL;\n\t\tBindAddr.port = g_Config.m_EcPort;\n\t}\n\n\tif(m_NetConsole.Open(BindAddr, pNetBan, 0))\n\t{\n\t\tm_NetConsole.SetCallbacks(NewClientCallback, DelClientCallback, this);\n\t\tm_Ready = true;\n\t\tchar aBuf[128];\n\t\tstr_format(aBuf, sizeof(aBuf), \"bound to %s:%d\", g_Config.m_EcBindaddr, g_Config.m_EcPort);\n\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD,\"econ\", aBuf);\n\n\t\tConsole()->Chain(\"ec_output_level\", ConchainEconOutputLevelUpdate, this);\n\t\tm_PrintCBIndex = Console()->RegisterPrintCallback(g_Config.m_EcOutputLevel, SendLineCB, this);\n\n\t\tConsole()->Register(\"logout\", \"\", CFGFLAG_ECON, ConLogout, this, \"Logout of econ\");\n\t}\n\telse\n\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD,\"econ\", \"couldn't open socket. port might already be in use\");\n}\n\nvoid CEcon::Update()\n{\n\tif(!m_Ready)\n\t\treturn;\n\n\tm_NetConsole.Update();\n\n\tchar aBuf[NET_MAX_PACKETSIZE];\n\tint ClientID;\n\n\twhile(m_NetConsole.Recv(aBuf, (int)(sizeof(aBuf))-1, &ClientID))\n\t{\n\t\tdbg_assert(m_aClients[ClientID].m_State != CClient::STATE_EMPTY, \"got message from empty slot\");\n\t\tif(m_aClients[ClientID].m_State == CClient::STATE_CONNECTED)\n\t\t{\n\t\t\tif(str_comp(aBuf, g_Config.m_EcPassword) == 0)\n\t\t\t{\n\t\t\t\tm_aClients[ClientID].m_State = CClient::STATE_AUTHED;\n\t\t\t\tm_NetConsole.Send(ClientID, \"Authentication successful. External console access granted.\");\n\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"cid=%d authed\", ClientID);\n\t\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"econ\", aBuf);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_aClients[ClientID].m_AuthTries++;\n\t\t\t\tchar aMsg[128];\n\t\t\t\tstr_format(aMsg, sizeof(aMsg), \"Wrong password %d/%d.\", m_aClients[ClientID].m_AuthTries, MAX_AUTH_TRIES);\n\t\t\t\tm_NetConsole.Send(ClientID, aMsg);\n\t\t\t\tif(m_aClients[ClientID].m_AuthTries >= MAX_AUTH_TRIES)\n\t\t\t\t{\n\t\t\t\t\tif(!g_Config.m_EcBantime)\n\t\t\t\t\t\tm_NetConsole.Drop(ClientID, \"Too many authentication tries\");\n\t\t\t\t\telse\n\t\t\t\t\t\tm_NetConsole.NetBan()->BanAddr(m_NetConsole.ClientAddr(ClientID), g_Config.m_EcBantime*60, \"Too many authentication tries\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if(m_aClients[ClientID].m_State == CClient::STATE_AUTHED)\n\t\t{\n\t\t\tchar aFormatted[256];\n\t\t\tstr_format(aFormatted, sizeof(aFormatted), \"cid=%d cmd='%s'\", ClientID, aBuf);\n\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"server\", aFormatted);\n\t\t\tm_UserClientID = ClientID;\n\t\t\tConsole()->ExecuteLine(aBuf);\n\t\t\tm_UserClientID = -1;\n\t\t}\n\t}\n\n\tfor(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; ++i)\n\t{\n\t\tif(m_aClients[i].m_State == CClient::STATE_CONNECTED &&\n\t\t\ttime_get() > m_aClients[i].m_TimeConnected + g_Config.m_EcAuthTimeout * time_freq())\n\t\t\tm_NetConsole.Drop(i, \"authentication timeout\");\n\t}\n}\n\nvoid CEcon::Send(int ClientID, const char *pLine)\n{\n\tif(!m_Ready)\n\t\treturn;\n\n\tif(ClientID == -1)\n\t{\n\t\tfor(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++)\n\t\t{\n\t\t\tif(m_aClients[i].m_State == CClient::STATE_AUTHED)\n\t\t\t\tm_NetConsole.Send(i, pLine);\n\t\t}\n\t}\n\telse if(ClientID >= 0 && ClientID < NET_MAX_CONSOLE_CLIENTS && m_aClients[ClientID].m_State == CClient::STATE_AUTHED)\n\t\tm_NetConsole.Send(ClientID, pLine);\n}\n\nvoid CEcon::Shutdown()\n{\n\tif(!m_Ready)\n\t\treturn;\n\n\tm_NetConsole.Close();\n}\n"
  },
  {
    "path": "src/engine/shared/econ.h",
    "content": "#ifndef ENGINE_SHARED_ECON_H\n#define ENGINE_SHARED_ECON_H\n\n#include \"network.h\"\n\n\nclass CEcon\n{\n\tenum\n\t{\n\t\tMAX_AUTH_TRIES=3,\n\t};\n\n\tclass CClient\n\t{\n\tpublic:\n\t\tenum\n\t\t{\n\t\t\tSTATE_EMPTY=0,\n\t\t\tSTATE_CONNECTED,\n\t\t\tSTATE_AUTHED,\n\t\t};\n\n\t\tint m_State;\n\t\tint64 m_TimeConnected;\n\t\tint m_AuthTries;\n\t};\n\tCClient m_aClients[NET_MAX_CONSOLE_CLIENTS];\n\n\tIConsole *m_pConsole;\n\tCNetConsole m_NetConsole;\n\n\tbool m_Ready;\n\tint m_PrintCBIndex;\n\tint m_UserClientID;\n\n\tstatic void SendLineCB(const char *pLine, void *pUserData);\n\tstatic void ConchainEconOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData);\n\tstatic void ConLogout(IConsole::IResult *pResult, void *pUserData);\n\n\tstatic int NewClientCallback(int ClientID, void *pUser);\n\tstatic int DelClientCallback(int ClientID, const char *pReason, void *pUser);\n\npublic:\n\tIConsole *Console() { return m_pConsole; }\n\n\tvoid Init(IConsole *pConsole, class CNetBan *pNetBan);\n\tvoid Update();\n\tvoid Send(int ClientID, const char *pLine);\n\tvoid Shutdown();\n};\n\n#endif\n"
  },
  {
    "path": "src/engine/shared/engine.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n\n#include <base/system.h>\n\n#include <engine/console.h>\n#include <engine/engine.h>\n#include <engine/storage.h>\n#include <engine/shared/config.h>\n#include <engine/shared/network.h>\n\n\nstatic int HostLookupThread(void *pUser)\n{\n\tCHostLookup *pLookup = (CHostLookup *)pUser;\n\treturn net_host_lookup(pLookup->m_aHostname, &pLookup->m_Addr, pLookup->m_Nettype);\n}\n\nclass CEngine : public IEngine\n{\npublic:\n\tIConsole *m_pConsole;\n\tIStorage *m_pStorage;\n\tbool m_Logging;\n\n\tstatic void Con_DbgDumpmem(IConsole::IResult *pResult, void *pUserData)\n\t{\n\t\tCEngine *pEngine = static_cast<CEngine *>(pUserData);\n\t\tchar aBuf[32];\n\t\tstr_timestamp(aBuf, sizeof(aBuf));\n\t\tchar aFilename[128];\n\t\tstr_format(aFilename, sizeof(aFilename), \"dumps/memory_%s.txt\", aBuf);\n\t\tmem_debug_dump(pEngine->m_pStorage->OpenFile(aFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE));\n\t}\n\n\tstatic void Con_DbgLognetwork(IConsole::IResult *pResult, void *pUserData)\n\t{\n\t\tCEngine *pEngine = static_cast<CEngine *>(pUserData);\n\n\t\tif(pEngine->m_Logging)\n\t\t{\n\t\t\tCNetBase::CloseLog();\n\t\t\tpEngine->m_Logging = false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tchar aBuf[32];\n\t\t\tstr_timestamp(aBuf, sizeof(aBuf));\n\t\t\tchar aFilenameSent[128], aFilenameRecv[128];\n\t\t\tstr_format(aFilenameSent, sizeof(aFilenameSent), \"dumps/network_sent_%s.txt\", aBuf);\n\t\t\tstr_format(aFilenameRecv, sizeof(aFilenameRecv), \"dumps/network_recv_%s.txt\", aBuf);\n\t\t\tCNetBase::OpenLog(pEngine->m_pStorage->OpenFile(aFilenameSent, IOFLAG_WRITE, IStorage::TYPE_SAVE),\n\t\t\t\t\t\t\t\tpEngine->m_pStorage->OpenFile(aFilenameRecv, IOFLAG_WRITE, IStorage::TYPE_SAVE));\n\t\t\tpEngine->m_Logging = true;\n\t\t}\n\t}\n\n\tCEngine(const char *pAppname)\n\t{\n\t\tdbg_logger_stdout();\n\t\tdbg_logger_debugger();\n\n\t\t//\n\t\tdbg_msg(\"engine\", \"running on %s-%s-%s\", CONF_FAMILY_STRING, CONF_PLATFORM_STRING, CONF_ARCH_STRING);\n\t#ifdef CONF_ARCH_ENDIAN_LITTLE\n\t\tdbg_msg(\"engine\", \"arch is little endian\");\n\t#elif defined(CONF_ARCH_ENDIAN_BIG)\n\t\tdbg_msg(\"engine\", \"arch is big endian\");\n\t#else\n\t\tdbg_msg(\"engine\", \"unknown endian\");\n\t#endif\n\n\t\t// init the network\n\t\tnet_init();\n\t\tCNetBase::Init();\n\n\t\tm_JobPool.Init(1);\n\n\t\tm_Logging = false;\n\t}\n\n\tvoid Init()\n\t{\n\t\tm_pConsole = Kernel()->RequestInterface<IConsole>();\n\t\tm_pStorage = Kernel()->RequestInterface<IStorage>();\n\n\t\tif(!m_pConsole || !m_pStorage)\n\t\t\treturn;\n\n\t\tm_pConsole->Register(\"dbg_dumpmem\", \"\", CFGFLAG_SERVER|CFGFLAG_CLIENT, Con_DbgDumpmem, this, \"Dump the memory\");\n\t\tm_pConsole->Register(\"dbg_lognetwork\", \"\", CFGFLAG_SERVER|CFGFLAG_CLIENT, Con_DbgLognetwork, this, \"Log the network\");\n\t}\n\n\tvoid InitLogfile()\n\t{\n\t\t// open logfile if needed\n\t\tif(g_Config.m_Logfile[0])\n\t\t\tdbg_logger_file(g_Config.m_Logfile);\n\t}\n\n\tvoid HostLookup(CHostLookup *pLookup, const char *pHostname, int Nettype)\n\t{\n\t\tstr_copy(pLookup->m_aHostname, pHostname, sizeof(pLookup->m_aHostname));\n\t\tpLookup->m_Nettype = Nettype;\n\t\tAddJob(&pLookup->m_Job, HostLookupThread, pLookup);\n\t}\n\n\tvoid AddJob(CJob *pJob, JOBFUNC pfnFunc, void *pData)\n\t{\n\t\tif(g_Config.m_Debug)\n\t\t\tdbg_msg(\"engine\", \"job added\");\n\t\tm_JobPool.Add(pJob, pfnFunc, pData);\n\t}\n};\n\nIEngine *CreateEngine(const char *pAppname) { return new CEngine(pAppname); }\n"
  },
  {
    "path": "src/engine/shared/filecollection.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n\n#include <base/math.h>\n\n#include <engine/storage.h>\n\n#include \"filecollection.h\"\n\nbool CFileCollection::IsFilenameValid(const char *pFilename)\n{\n\tif(str_length(pFilename) != m_FileDescLength+TIMESTAMP_LENGTH+m_FileExtLength ||\n\t\tstr_comp_num(pFilename, m_aFileDesc, m_FileDescLength) ||\n\t\tstr_comp(pFilename+m_FileDescLength+TIMESTAMP_LENGTH, m_aFileExt))\n\t\treturn false;\n\n\tpFilename += m_FileDescLength;\n\tif(pFilename[0] == '_' &&\n\t\tpFilename[1] >= '0' && pFilename[1] <= '9' &&\n\t\tpFilename[2] >= '0' && pFilename[2] <= '9' &&\n\t\tpFilename[3] >= '0' && pFilename[3] <= '9' &&\n\t\tpFilename[4] >= '0' && pFilename[4] <= '9' &&\n\t\tpFilename[5] == '-' &&\n\t\tpFilename[6] >= '0' && pFilename[6] <= '9' &&\n\t\tpFilename[7] >= '0' && pFilename[7] <= '9' &&\n\t\tpFilename[8] == '-' &&\n\t\tpFilename[9] >= '0' && pFilename[9] <= '9' &&\n\t\tpFilename[10] >= '0' && pFilename[10] <= '9' &&\n\t\tpFilename[11] == '_' &&\n\t\tpFilename[12] >= '0' && pFilename[12] <= '9' &&\n\t\tpFilename[13] >= '0' && pFilename[13] <= '9' &&\n\t\tpFilename[14] == '-' &&\n\t\tpFilename[15] >= '0' && pFilename[15] <= '9' &&\n\t\tpFilename[16] >= '0' && pFilename[16] <= '9' &&\n\t\tpFilename[17] == '-' &&\n\t\tpFilename[18] >= '0' && pFilename[18] <= '9' &&\n\t\tpFilename[19] >= '0' && pFilename[19] <= '9')\n\t\treturn true;\n\n\treturn false;\n}\n\nint64 CFileCollection::ExtractTimestamp(const char *pTimestring)\n{\n\tint64 Timestamp = pTimestring[0]-'0'; Timestamp <<= 4;\n\tTimestamp += pTimestring[1]-'0'; Timestamp <<= 4;\n\tTimestamp += pTimestring[2]-'0'; Timestamp <<= 4;\n\tTimestamp += pTimestring[3]-'0'; Timestamp <<= 4;\n\tTimestamp += pTimestring[5]-'0'; Timestamp <<= 4;\n\tTimestamp += pTimestring[6]-'0'; Timestamp <<= 4;\n\tTimestamp += pTimestring[8]-'0'; Timestamp <<= 4;\n\tTimestamp += pTimestring[9]-'0'; Timestamp <<= 4;\n\tTimestamp += pTimestring[11]-'0'; Timestamp <<= 4;\n\tTimestamp += pTimestring[12]-'0'; Timestamp <<= 4;\n\tTimestamp += pTimestring[14]-'0'; Timestamp <<= 4;\n\tTimestamp += pTimestring[15]-'0'; Timestamp <<= 4;\n\tTimestamp += pTimestring[17]-'0'; Timestamp <<= 4;\n\tTimestamp += pTimestring[18]-'0';\n\n\treturn Timestamp;\n}\n\nvoid CFileCollection::BuildTimestring(int64 Timestamp, char *pTimestring)\n{\n\tpTimestring[19] = 0;\n\tpTimestring[18] = (Timestamp&0xF)+'0'; Timestamp >>= 4;\n\tpTimestring[17] = (Timestamp&0xF)+'0'; Timestamp >>= 4;\n\tpTimestring[16] = '-';\n\tpTimestring[15] = (Timestamp&0xF)+'0'; Timestamp >>= 4;\n\tpTimestring[14] = (Timestamp&0xF)+'0'; Timestamp >>= 4;\n\tpTimestring[13] = '-';\n\tpTimestring[12] = (Timestamp&0xF)+'0'; Timestamp >>= 4;\n\tpTimestring[11] = (Timestamp&0xF)+'0'; Timestamp >>= 4;\n\tpTimestring[10] = '_';\n\tpTimestring[9] = (Timestamp&0xF)+'0'; Timestamp >>= 4;\n\tpTimestring[8] = (Timestamp&0xF)+'0'; Timestamp >>= 4;\n\tpTimestring[7] = '-';\n\tpTimestring[6] = (Timestamp&0xF)+'0'; Timestamp >>= 4;\n\tpTimestring[5] = (Timestamp&0xF)+'0'; Timestamp >>= 4;\n\tpTimestring[4] = '-';\n\tpTimestring[3] = (Timestamp&0xF)+'0'; Timestamp >>= 4;\n\tpTimestring[2] = (Timestamp&0xF)+'0'; Timestamp >>= 4;\n\tpTimestring[1] = (Timestamp&0xF)+'0'; Timestamp >>= 4;\n\tpTimestring[0] = (Timestamp&0xF)+'0';\n}\n\nvoid CFileCollection::Init(IStorage *pStorage, const char *pPath, const char *pFileDesc, const char *pFileExt, int MaxEntries)\n{\n\tmem_zero(m_aTimestamps, sizeof(m_aTimestamps));\n\tm_NumTimestamps = 0;\n\tm_MaxEntries = clamp(MaxEntries, 1, static_cast<int>(MAX_ENTRIES));\n\tstr_copy(m_aFileDesc, pFileDesc, sizeof(m_aFileDesc));\n\tm_FileDescLength = str_length(m_aFileDesc);\n\tstr_copy(m_aFileExt, pFileExt, sizeof(m_aFileExt));\n\tm_FileExtLength = str_length(m_aFileExt);\n\tstr_copy(m_aPath, pPath, sizeof(m_aPath));\n\tm_pStorage = pStorage;\n\n\tm_pStorage->ListDirectory(IStorage::TYPE_SAVE, m_aPath, FilelistCallback, this);\n}\n\nvoid CFileCollection::AddEntry(int64 Timestamp)\n{\n\tif(m_NumTimestamps == 0)\n\t{\n\t\t// empty list\n\t\tm_aTimestamps[m_NumTimestamps++] = Timestamp;\n\t}\n\telse\n\t{\n\t\t// remove old file\n\t\tif(m_NumTimestamps == m_MaxEntries)\n\t\t{\n\t\t\tchar aBuf[512];\n\t\t\tchar aTimestring[TIMESTAMP_LENGTH];\n\t\t\tBuildTimestring(m_aTimestamps[0], aTimestring);\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"%s/%s_%s%s\", m_aPath, m_aFileDesc, aTimestring, m_aFileExt);\n\t\t\tm_pStorage->RemoveFile(aBuf, IStorage::TYPE_SAVE);\n\t\t}\n\n\t\t// add entry to the sorted list\n\t\tif(m_aTimestamps[0] > Timestamp)\n\t\t{\n\t\t\t// first entry\n\t\t\tif(m_NumTimestamps < m_MaxEntries)\n\t\t\t{\n\t\t\t\tmem_move(m_aTimestamps+1, m_aTimestamps, m_NumTimestamps*sizeof(int64));\n\t\t\t\tm_aTimestamps[0] = Timestamp;\n\t\t\t\t++m_NumTimestamps;\n\t\t\t}\n\t\t}\n\t\telse if(m_aTimestamps[m_NumTimestamps-1] <= Timestamp)\n\t\t{\n\t\t\t// last entry\n\t\t\tif(m_NumTimestamps == m_MaxEntries)\n\t\t\t{\n\t\t\t\tmem_move(m_aTimestamps, m_aTimestamps+1, (m_NumTimestamps-1)*sizeof(int64));\n\t\t\t\tm_aTimestamps[m_NumTimestamps-1] = Timestamp;\n\t\t\t}\n\t\t\telse\n\t\t\t\tm_aTimestamps[m_NumTimestamps++] = Timestamp;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// middle entry\n\t\t\tint Left = 0, Right = m_NumTimestamps-1;\n\t\t\twhile(Right-Left > 1)\n\t\t\t{\n\t\t\t\tint Mid = (Left+Right)/2;\n\t\t\t\tif(m_aTimestamps[Mid] > Timestamp)\n\t\t\t\t\tRight = Mid;\n\t\t\t\telse\n\t\t\t\t\tLeft = Mid;\n\t\t\t}\n\n\t\t\tif(m_NumTimestamps == m_MaxEntries)\n\t\t\t{\n\t\t\t\tmem_move(m_aTimestamps, m_aTimestamps+1, (Right-1)*sizeof(int64));\n\t\t\t\tm_aTimestamps[Right-1] = Timestamp;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tmem_move(m_aTimestamps+Right+1, m_aTimestamps+Right, (m_NumTimestamps-Right)*sizeof(int64));\n\t\t\t\tm_aTimestamps[Right] = Timestamp;\n\t\t\t\t++m_NumTimestamps;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint CFileCollection::FilelistCallback(const char *pFilename, int IsDir, int StorageType, void *pUser)\n{\n\tCFileCollection *pThis = static_cast<CFileCollection *>(pUser);\n\n\t// check for valid file name format\n\tif(IsDir || !pThis->IsFilenameValid(pFilename))\n\t\treturn 0;\n\n\t// extract the timestamp\n\tint64 Timestamp = pThis->ExtractTimestamp(pFilename+pThis->m_FileDescLength+1);\n\n\t// add the entry\n\tpThis->AddEntry(Timestamp);\n\n\treturn 0;\n}\n"
  },
  {
    "path": "src/engine/shared/filecollection.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SHARED_FILECOLLECTION_H\n#define ENGINE_SHARED_FILECOLLECTION_H\n\nclass CFileCollection\n{\n\tenum\n\t{\n\t\tMAX_ENTRIES=1000,\n\t\tTIMESTAMP_LENGTH=20,\t// _YYYY-MM-DD_HH-MM-SS\n\t};\n\n\tint64 m_aTimestamps[MAX_ENTRIES];\n\tint m_NumTimestamps;\n\tint m_MaxEntries;\n\tchar m_aFileDesc[128];\n\tint m_FileDescLength;\n\tchar m_aFileExt[32];\n\tint m_FileExtLength;\n\tchar m_aPath[512];\n\tIStorage *m_pStorage;\n\n\tbool IsFilenameValid(const char *pFilename);\n\tint64 ExtractTimestamp(const char *pTimestring);\n\tvoid BuildTimestring(int64 Timestamp, char *pTimestring);\n\npublic:\n\tvoid Init(IStorage *pStorage, const char *pPath, const char *pFileDesc, const char *pFileExt, int MaxEntries);\n\tvoid AddEntry(int64 Timestamp);\n\n\tstatic int FilelistCallback(const char *pFilename, int IsDir, int StorageType, void *pUser);\n};\n\n#endif\n"
  },
  {
    "path": "src/engine/shared/huffman.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n#include \"huffman.h\"\n\nstruct CHuffmanConstructNode\n{\n\tunsigned short m_NodeId;\n \tint m_Frequency;\n};\n\nvoid CHuffman::Setbits_r(CNode *pNode, int Bits, unsigned Depth)\n{\n\tif(pNode->m_aLeafs[1] != 0xffff)\n\t\tSetbits_r(&m_aNodes[pNode->m_aLeafs[1]], Bits|(1<<Depth), Depth+1);\n\tif(pNode->m_aLeafs[0] != 0xffff)\n\t\tSetbits_r(&m_aNodes[pNode->m_aLeafs[0]], Bits, Depth+1);\n\n\tif(pNode->m_NumBits)\n\t{\n\t\tpNode->m_Bits = Bits;\n\t\tpNode->m_NumBits = Depth;\n\t}\n}\n\n// TODO: this should be something faster, but it's enough for now\nstatic void BubbleSort(CHuffmanConstructNode **ppList, int Size)\n{\n\tint Changed = 1;\n\tCHuffmanConstructNode *pTemp;\n\n\twhile(Changed)\n\t{\n\t\tChanged = 0;\n\t\tfor(int i = 0; i < Size-1; i++)\n\t\t{\n\t\t\tif(ppList[i]->m_Frequency < ppList[i+1]->m_Frequency)\n\t\t\t{\n\t\t\t\tpTemp = ppList[i];\n\t\t\t\tppList[i] = ppList[i+1];\n\t\t\t\tppList[i+1] = pTemp;\n\t\t\t\tChanged = 1;\n\t\t\t}\n\t\t}\n\t\tSize--;\n\t}\n}\n\nvoid CHuffman::ConstructTree(const unsigned *pFrequencies)\n{\n\tCHuffmanConstructNode aNodesLeftStorage[HUFFMAN_MAX_SYMBOLS];\n\tCHuffmanConstructNode *apNodesLeft[HUFFMAN_MAX_SYMBOLS];\n\tint NumNodesLeft = HUFFMAN_MAX_SYMBOLS;\n\n\t// add the symbols\n\tfor(int i = 0; i < HUFFMAN_MAX_SYMBOLS; i++)\n\t{\n\t\tm_aNodes[i].m_NumBits = 0xFFFFFFFF;\n\t\tm_aNodes[i].m_Symbol = i;\n\t\tm_aNodes[i].m_aLeafs[0] = 0xffff;\n\t\tm_aNodes[i].m_aLeafs[1] = 0xffff;\n\n\t\tif(i == HUFFMAN_EOF_SYMBOL)\n\t\t\taNodesLeftStorage[i].m_Frequency = 1;\n\t\telse\n\t\t\taNodesLeftStorage[i].m_Frequency = pFrequencies[i];\n\t\taNodesLeftStorage[i].m_NodeId = i;\n\t\tapNodesLeft[i] = &aNodesLeftStorage[i];\n\n\t}\n\n\tm_NumNodes = HUFFMAN_MAX_SYMBOLS;\n\n\t// construct the table\n\twhile(NumNodesLeft > 1)\n\t{\n\t\t// we can't rely on stdlib's qsort for this, it can generate different results on different implementations\n\t\tBubbleSort(apNodesLeft, NumNodesLeft);\n\n\t\tm_aNodes[m_NumNodes].m_NumBits = 0;\n\t\tm_aNodes[m_NumNodes].m_aLeafs[0] = apNodesLeft[NumNodesLeft-1]->m_NodeId;\n\t\tm_aNodes[m_NumNodes].m_aLeafs[1] = apNodesLeft[NumNodesLeft-2]->m_NodeId;\n\t\tapNodesLeft[NumNodesLeft-2]->m_NodeId = m_NumNodes;\n\t\tapNodesLeft[NumNodesLeft-2]->m_Frequency = apNodesLeft[NumNodesLeft-1]->m_Frequency + apNodesLeft[NumNodesLeft-2]->m_Frequency;\n\n\t\tm_NumNodes++;\n\t\tNumNodesLeft--;\n\t}\n\n\t// set start node\n\tm_pStartNode = &m_aNodes[m_NumNodes-1];\n\n\t// build symbol bits\n\tSetbits_r(m_pStartNode, 0, 0);\n}\n\nvoid CHuffman::Init(const unsigned *pFrequencies)\n{\n\tint i;\n\n\t// make sure to cleanout every thing\n\tmem_zero(this, sizeof(*this));\n\n\t// construct the tree\n\tConstructTree(pFrequencies);\n\n\t// build decode LUT\n\tfor(i = 0; i < HUFFMAN_LUTSIZE; i++)\n\t{\n\t\tunsigned Bits = i;\n\t\tint k;\n\t\tCNode *pNode = m_pStartNode;\n\t\tfor(k = 0; k < HUFFMAN_LUTBITS; k++)\n\t\t{\n\t\t\tpNode = &m_aNodes[pNode->m_aLeafs[Bits&1]];\n\t\t\tBits >>= 1;\n\n\t\t\tif(!pNode)\n\t\t\t\tbreak;\n\n\t\t\tif(pNode->m_NumBits)\n\t\t\t{\n\t\t\t\tm_apDecodeLut[i] = pNode;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif(k == HUFFMAN_LUTBITS)\n\t\t\tm_apDecodeLut[i] = pNode;\n\t}\n\n}\n\n//***************************************************************\nint CHuffman::Compress(const void *pInput, int InputSize, void *pOutput, int OutputSize)\n{\n\t// this macro loads a symbol for a byte into bits and bitcount\n#define HUFFMAN_MACRO_LOADSYMBOL(Sym) \\\n\tBits |= m_aNodes[Sym].m_Bits << Bitcount; \\\n\tBitcount += m_aNodes[Sym].m_NumBits;\n\n\t// this macro writes the symbol stored in bits and bitcount to the dst pointer\n#define HUFFMAN_MACRO_WRITE() \\\n\twhile(Bitcount >= 8) \\\n\t{ \\\n\t\t*pDst++ = (unsigned char)(Bits&0xff); \\\n\t\tif(pDst == pDstEnd) \\\n\t\t\treturn -1; \\\n\t\tBits >>= 8; \\\n\t\tBitcount -= 8; \\\n\t}\n\n\t// setup buffer pointers\n\tconst unsigned char *pSrc = (const unsigned char *)pInput;\n\tconst unsigned char *pSrcEnd = pSrc + InputSize;\n\tunsigned char *pDst = (unsigned char *)pOutput;\n\tunsigned char *pDstEnd = pDst + OutputSize;\n\n\t// symbol variables\n\tunsigned Bits = 0;\n\tunsigned Bitcount = 0;\n\n\t// make sure that we have data that we want to compress\n\tif(InputSize)\n\t{\n\t\t// {A} load the first symbol\n\t\tint Symbol = *pSrc++;\n\n\t\twhile(pSrc != pSrcEnd)\n\t\t{\n\t\t\t// {B} load the symbol\n\t\t\tHUFFMAN_MACRO_LOADSYMBOL(Symbol)\n\n\t\t\t// {C} fetch next symbol, this is done here because it will reduce dependency in the code\n\t\t\tSymbol = *pSrc++;\n\n\t\t\t// {B} write the symbol loaded at\n\t\t\tHUFFMAN_MACRO_WRITE()\n\t\t}\n\n\t\t// write the last symbol loaded from {C} or {A} in the case of only 1 byte input buffer\n\t\tHUFFMAN_MACRO_LOADSYMBOL(Symbol)\n\t\tHUFFMAN_MACRO_WRITE()\n\t}\n\n\t// write EOF symbol\n\tHUFFMAN_MACRO_LOADSYMBOL(HUFFMAN_EOF_SYMBOL)\n\tHUFFMAN_MACRO_WRITE()\n\n\t// write out the last bits\n\t*pDst++ = Bits;\n\n\t// return the size of the output\n\treturn (int)(pDst - (const unsigned char *)pOutput);\n\n\t// remove macros\n#undef HUFFMAN_MACRO_LOADSYMBOL\n#undef HUFFMAN_MACRO_WRITE\n}\n\n//***************************************************************\nint CHuffman::Decompress(const void *pInput, int InputSize, void *pOutput, int OutputSize)\n{\n\t// setup buffer pointers\n\tunsigned char *pDst = (unsigned char *)pOutput;\n\tunsigned char *pSrc = (unsigned char *)pInput;\n\tunsigned char *pDstEnd = pDst + OutputSize;\n\tunsigned char *pSrcEnd = pSrc + InputSize;\n\n\tunsigned Bits = 0;\n\tunsigned Bitcount = 0;\n\n\tCNode *pEof = &m_aNodes[HUFFMAN_EOF_SYMBOL];\n\tCNode *pNode = 0;\n\n\twhile(1)\n\t{\n\t\t// {A} try to load a node now, this will reduce dependency at location {D}\n\t\tpNode = 0;\n\t\tif(Bitcount >= HUFFMAN_LUTBITS)\n\t\t\tpNode = m_apDecodeLut[Bits&HUFFMAN_LUTMASK];\n\n\t\t// {B} fill with new bits\n\t\twhile(Bitcount < 24 && pSrc != pSrcEnd)\n\t\t{\n\t\t\tBits |= (*pSrc++) << Bitcount;\n\t\t\tBitcount += 8;\n\t\t}\n\n\t\t// {C} load symbol now if we didn't that earlier at location {A}\n\t\tif(!pNode)\n\t\t\tpNode = m_apDecodeLut[Bits&HUFFMAN_LUTMASK];\n\n\t\tif(!pNode)\n\t\t\treturn -1;\n\n\t\t// {D} check if we hit a symbol already\n\t\tif(pNode->m_NumBits)\n\t\t{\n\t\t\t// remove the bits for that symbol\n\t\t\tBits >>= pNode->m_NumBits;\n\t\t\tBitcount -= pNode->m_NumBits;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// remove the bits that the lut checked up for us\n\t\t\tBits >>= HUFFMAN_LUTBITS;\n\t\t\tBitcount -= HUFFMAN_LUTBITS;\n\n\t\t\t// walk the tree bit by bit\n\t\t\twhile(1)\n\t\t\t{\n\t\t\t\t// traverse tree\n\t\t\t\tpNode = &m_aNodes[pNode->m_aLeafs[Bits&1]];\n\n\t\t\t\t// remove bit\n\t\t\t\tBitcount--;\n\t\t\t\tBits >>= 1;\n\n\t\t\t\t// check if we hit a symbol\n\t\t\t\tif(pNode->m_NumBits)\n\t\t\t\t\tbreak;\n\n\t\t\t\t// no more bits, decoding error\n\t\t\t\tif(Bitcount == 0)\n\t\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\n\t\t// check for eof\n\t\tif(pNode == pEof)\n\t\t\tbreak;\n\n\t\t// output character\n\t\tif(pDst == pDstEnd)\n\t\t\treturn -1;\n\t\t*pDst++ = pNode->m_Symbol;\n\t}\n\n\t// return the size of the decompressed buffer\n\treturn (int)(pDst - (const unsigned char *)pOutput);\n}\n"
  },
  {
    "path": "src/engine/shared/huffman.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SHARED_HUFFMAN_H\n#define ENGINE_SHARED_HUFFMAN_H\n\n\n\nclass CHuffman\n{\n\tenum\n\t{\n\t\tHUFFMAN_EOF_SYMBOL = 256,\n\n\t\tHUFFMAN_MAX_SYMBOLS=HUFFMAN_EOF_SYMBOL+1,\n\t\tHUFFMAN_MAX_NODES=HUFFMAN_MAX_SYMBOLS*2-1,\n\n\t\tHUFFMAN_LUTBITS = 10,\n\t\tHUFFMAN_LUTSIZE = (1<<HUFFMAN_LUTBITS),\n\t\tHUFFMAN_LUTMASK = (HUFFMAN_LUTSIZE-1)\n\t};\n\n\tstruct CNode\n\t{\n\t\t// symbol\n\t\tunsigned m_Bits;\n\t\tunsigned m_NumBits;\n\n\t\t// don't use pointers for this. shorts are smaller so we can fit more data into the cache\n\t\tunsigned short m_aLeafs[2];\n\n\t\t// what the symbol represents\n\t\tunsigned char m_Symbol;\n\t};\n\n\tCNode m_aNodes[HUFFMAN_MAX_NODES];\n\tCNode *m_apDecodeLut[HUFFMAN_LUTSIZE];\n\tCNode *m_pStartNode;\n\tint m_NumNodes;\n\n\tvoid Setbits_r(CNode *pNode, int Bits, unsigned Depth);\n\tvoid ConstructTree(const unsigned *pFrequencies);\n\npublic:\n\t/*\n\t\tFunction: huffman_init\n\t\t\tInits the compressor/decompressor.\n\n\t\tParameters:\n\t\t\thuff - Pointer to the state to init\n\t\t\tfrequencies - A pointer to an array of 256 entries of the frequencies of the bytes\n\n\t\tRemarks:\n\t\t\t- Does no allocation what so ever.\n\t\t\t- You don't have to call any cleanup functions when you are done with it\n\t*/\n\tvoid Init(const unsigned *pFrequencies);\n\n\t/*\n\t\tFunction: huffman_compress\n\t\t\tCompresses a buffer and outputs a compressed buffer.\n\n\t\tParameters:\n\t\t\thuff - Pointer to the huffman state\n\t\t\tinput - Buffer to compress\n\t\t\tinput_size - Size of the buffer to compress\n\t\t\toutput - Buffer to put the compressed data into\n\t\t\toutput_size - Size of the output buffer\n\n\t\tReturns:\n\t\t\tReturns the size of the compressed data. Negative value on failure.\n\t*/\n\tint Compress(const void *pInput, int InputSize, void *pOutput, int OutputSize);\n\n\t/*\n\t\tFunction: huffman_decompress\n\t\t\tDecompresses a buffer\n\n\t\tParameters:\n\t\t\thuff - Pointer to the huffman state\n\t\t\tinput - Buffer to decompress\n\t\t\tinput_size - Size of the buffer to decompress\n\t\t\toutput - Buffer to put the uncompressed data into\n\t\t\toutput_size - Size of the output buffer\n\n\t\tReturns:\n\t\t\tReturns the size of the uncompressed data. Negative value on failure.\n\t*/\n\tint Decompress(const void *pInput, int InputSize, void *pOutput, int OutputSize);\n\n};\n#endif // __HUFFMAN_HEADER__\n"
  },
  {
    "path": "src/engine/shared/jobs.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n#include \"jobs.h\"\n\nCJobPool::CJobPool()\n{\n\t// empty the pool\n\tm_NumThreads = 0;\n\tm_Shutdown = false;\n\tm_Lock = lock_create();\n\tm_pFirstJob = 0;\n\tm_pLastJob = 0;\n}\n\nCJobPool::~CJobPool()\n{\n\tm_Shutdown = true;\n\tfor(int i = 0; i < m_NumThreads; i++)\n\t{\n\t\tthread_wait(m_apThreads[i]);\n\t\tthread_destroy(m_apThreads[i]);\n\t}\n}\n\nvoid CJobPool::WorkerThread(void *pUser)\n{\n\tCJobPool *pPool = (CJobPool *)pUser;\n\n\twhile(!pPool->m_Shutdown)\n\t{\n\t\tCJob *pJob = 0;\n\n\t\t// fetch job from queue\n\t\tlock_wait(pPool->m_Lock);\n\t\tif(pPool->m_pFirstJob)\n\t\t{\n\t\t\tpJob = pPool->m_pFirstJob;\n\t\t\tpPool->m_pFirstJob = pPool->m_pFirstJob->m_pNext;\n\t\t\tif(pPool->m_pFirstJob)\n\t\t\t\tpPool->m_pFirstJob->m_pPrev = 0;\n\t\t\telse\n\t\t\t\tpPool->m_pLastJob = 0;\n\t\t}\n\t\tlock_release(pPool->m_Lock);\n\n\t\t// do the job if we have one\n\t\tif(pJob)\n\t\t{\n\t\t\tpJob->m_Status = CJob::STATE_RUNNING;\n\t\t\tpJob->m_Result = pJob->m_pfnFunc(pJob->m_pFuncData);\n\t\t\tpJob->m_Status = CJob::STATE_DONE;\n\t\t}\n\t\telse\n\t\t\tthread_sleep(10);\n\t}\n\n}\n\nint CJobPool::Init(int NumThreads)\n{\n\t// start threads\n\tm_NumThreads = NumThreads > MAX_THREADS ? MAX_THREADS : NumThreads;\n\tfor(int i = 0; i < m_NumThreads; i++)\n\t\tm_apThreads[i] = thread_create(WorkerThread, this);\n\treturn 0;\n}\n\nint CJobPool::Add(CJob *pJob, JOBFUNC pfnFunc, void *pData)\n{\n\tmem_zero(pJob, sizeof(CJob));\n\tpJob->m_pfnFunc = pfnFunc;\n\tpJob->m_pFuncData = pData;\n\n\tlock_wait(m_Lock);\n\n\t// add job to queue\n\tpJob->m_pPrev = m_pLastJob;\n\tif(m_pLastJob)\n\t\tm_pLastJob->m_pNext = pJob;\n\tm_pLastJob = pJob;\n\tif(!m_pFirstJob)\n\t\tm_pFirstJob = pJob;\n\n\tlock_release(m_Lock);\n\treturn 0;\n}\n\n"
  },
  {
    "path": "src/engine/shared/jobs.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SHARED_JOBS_H\n#define ENGINE_SHARED_JOBS_H\ntypedef int (*JOBFUNC)(void *pData);\n\nclass CJobPool;\n\nclass CJob\n{\n\tfriend class CJobPool;\n\n\tCJobPool *m_pPool;\n\tCJob *m_pPrev;\n\tCJob *m_pNext;\n\n\tvolatile int m_Status;\n\tvolatile int m_Result;\n\n\tJOBFUNC m_pfnFunc;\n\tvoid *m_pFuncData;\npublic:\n\tCJob()\n\t{\n\t\tm_Status = STATE_DONE;\n\t\tm_pFuncData = 0;\n\t}\n\n\tenum\n\t{\n\t\tSTATE_PENDING=0,\n\t\tSTATE_RUNNING,\n\t\tSTATE_DONE\n\t};\n\n\tint Status() const { return m_Status; }\n\tint Result() const {return m_Result; }\n};\n\nclass CJobPool\n{\n\tenum\n\t{\n\t\tMAX_THREADS=32\n\t};\n\tint m_NumThreads;\n\tvoid *m_apThreads[MAX_THREADS];\n\tvolatile bool m_Shutdown;\n\n\tLOCK m_Lock;\n\tCJob *m_pFirstJob;\n\tCJob *m_pLastJob;\n\n\tstatic void WorkerThread(void *pUser);\n\npublic:\n\tCJobPool();\n\t~CJobPool();\n\n\tint Init(int NumThreads);\n\tint Add(CJob *pJob, JOBFUNC pfnFunc, void *pData);\n};\n#endif\n"
  },
  {
    "path": "src/engine/shared/kernel.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n#include <engine/kernel.h>\n\nclass CKernel : public IKernel\n{\n\tenum\n\t{\n\t\tMAX_INTERFACES=32,\n\t};\n\n\tclass CInterfaceInfo\n\t{\n\tpublic:\n\t\tCInterfaceInfo()\n\t\t{\n\t\t\tm_aName[0] = 0;\n\t\t\tm_pInterface = 0x0;\n\t\t}\n\n\t\tchar m_aName[64];\n\t\tIInterface *m_pInterface;\n\t};\n\n\tCInterfaceInfo m_aInterfaces[MAX_INTERFACES];\n\tint m_NumInterfaces;\n\n\tCInterfaceInfo *FindInterfaceInfo(const char *pName)\n\t{\n\t\tfor(int i = 0; i < m_NumInterfaces; i++)\n\t\t{\n\t\t\tif(str_comp(pName, m_aInterfaces[i].m_aName) == 0)\n\t\t\t\treturn &m_aInterfaces[i];\n\t\t}\n\t\treturn 0x0;\n\t}\n\npublic:\n\n\tCKernel()\n\t{\n\t\tm_NumInterfaces = 0;\n\t}\n\n\n\tvirtual bool RegisterInterfaceImpl(const char *pName, IInterface *pInterface)\n\t{\n\t\t// TODO: More error checks here\n\t\tif(!pInterface)\n\t\t{\n\t\t\tdbg_msg(\"kernel\", \"ERROR: couldn't register interface %s. null pointer given\", pName);\n\t\t\treturn false;\n\t\t}\n\n\t\tif(m_NumInterfaces == MAX_INTERFACES)\n\t\t{\n\t\t\tdbg_msg(\"kernel\", \"ERROR: couldn't register interface '%s'. maximum of interfaces reached\", pName);\n\t\t\treturn false;\n\t\t}\n\n\t\tif(FindInterfaceInfo(pName) != 0)\n\t\t{\n\t\t\tdbg_msg(\"kernel\", \"ERROR: couldn't register interface '%s'. interface already exists\", pName);\n\t\t\treturn false;\n\t\t}\n\n\t\tpInterface->m_pKernel = this;\n\t\tm_aInterfaces[m_NumInterfaces].m_pInterface = pInterface;\n\t\tstr_copy(m_aInterfaces[m_NumInterfaces].m_aName, pName, sizeof(m_aInterfaces[m_NumInterfaces].m_aName));\n\t\tm_NumInterfaces++;\n\n\t\treturn true;\n\t}\n\n\tvirtual bool ReregisterInterfaceImpl(const char *pName, IInterface *pInterface)\n\t{\n\t\tif(FindInterfaceInfo(pName) == 0)\n\t\t{\n\t\t\tdbg_msg(\"kernel\", \"ERROR: couldn't reregister interface '%s'. interface doesn't exist\");\n\t\t\treturn false;\n\t\t}\n\n\t\tpInterface->m_pKernel = this;\n\n\t\treturn true;\n\t}\n\n\tvirtual IInterface *RequestInterfaceImpl(const char *pName)\n\t{\n\t\tCInterfaceInfo *pInfo = FindInterfaceInfo(pName);\n\t\tif(!pInfo)\n\t\t{\n\t\t\tdbg_msg(\"kernel\", \"failed to find interface with the name '%s'\", pName);\n\t\t\treturn 0;\n\t\t}\n\t\treturn pInfo->m_pInterface;\n\t}\n};\n\nIKernel *IKernel::Create() { return new CKernel; }\n"
  },
  {
    "path": "src/engine/shared/linereader.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include \"linereader.h\"\n\nvoid CLineReader::Init(IOHANDLE io)\n{\n\tm_BufferMaxSize = sizeof(m_aBuffer);\n\tm_BufferSize = 0;\n\tm_BufferPos = 0;\n\tm_IO = io;\n}\n\nchar *CLineReader::Get()\n{\n\tunsigned LineStart = m_BufferPos;\n\tbool CRLFBreak = false;\n\n\twhile(1)\n\t{\n\t\tif(m_BufferPos >= m_BufferSize)\n\t\t{\n\t\t\t// fetch more\n\n\t\t\t// move the remaining part to the front\n\t\t\tunsigned Read;\n\t\t\tunsigned Left = m_BufferSize - LineStart;\n\n\t\t\tif(LineStart > m_BufferSize)\n\t\t\t\tLeft = 0;\n\t\t\tif(Left)\n\t\t\t\tmem_move(m_aBuffer, &m_aBuffer[LineStart], Left);\n\t\t\tm_BufferPos = Left;\n\n\t\t\t// fill the buffer\n\t\t\tRead = io_read(m_IO, &m_aBuffer[m_BufferPos], m_BufferMaxSize-m_BufferPos);\n\t\t\tm_BufferSize = Left + Read;\n\t\t\tLineStart = 0;\n\n\t\t\tif(!Read)\n\t\t\t{\n\t\t\t\tif(Left)\n\t\t\t\t{\n\t\t\t\t\tm_aBuffer[Left] = 0; // return the last line\n\t\t\t\t\tm_BufferPos = Left;\n\t\t\t\t\tm_BufferSize = Left;\n\t\t\t\t\treturn m_aBuffer;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturn 0x0; // we are done!\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(m_aBuffer[m_BufferPos] == '\\n' || m_aBuffer[m_BufferPos] == '\\r')\n\t\t\t{\n\t\t\t\t// line found\n\t\t\t\tif(m_aBuffer[m_BufferPos] == '\\r')\n\t\t\t\t{\n\t\t\t\t\tif(m_BufferPos+1 >= m_BufferSize)\n\t\t\t\t\t{\n\t\t\t\t\t\t// read more to get the connected '\\n'\n\t\t\t\t\t\tCRLFBreak = true;\n\t\t\t\t\t\t++m_BufferPos;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\telse if(m_aBuffer[m_BufferPos+1] == '\\n')\n\t\t\t\t\t\tm_aBuffer[m_BufferPos++] = 0;\n\t\t\t\t}\n\t\t\t\tm_aBuffer[m_BufferPos++] = 0;\n\t\t\t\treturn &m_aBuffer[LineStart];\n\t\t\t}\n\t\t\telse if(CRLFBreak)\n\t\t\t{\n\t\t\t\tif(m_aBuffer[m_BufferPos] == '\\n')\n\t\t\t\t\tm_aBuffer[m_BufferPos++] = 0;\n\t\t\t\treturn &m_aBuffer[LineStart];\n\t\t\t}\n\t\t\telse\n\t\t\t\tm_BufferPos++;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "src/engine/shared/linereader.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SHARED_LINEREADER_H\n#define ENGINE_SHARED_LINEREADER_H\n#include <base/system.h>\n\n// buffered stream for reading lines, should perhaps be something smaller\nclass CLineReader\n{\n\tchar m_aBuffer[4*1024];\n\tunsigned m_BufferPos;\n\tunsigned m_BufferSize;\n\tunsigned m_BufferMaxSize;\n\tIOHANDLE m_IO;\npublic:\n\tvoid Init(IOHANDLE IoHandle);\n\tchar *Get();\n};\n#endif\n"
  },
  {
    "path": "src/engine/shared/map.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n#include <engine/map.h>\n#include <engine/storage.h>\n#include <game/mapitems.h>\n#include \"datafile.h\"\n\nclass CMap : public IEngineMap\n{\n\tCDataFileReader m_DataFile;\npublic:\n\tCMap() {}\n\n\tvirtual void *GetData(int Index) { return m_DataFile.GetData(Index); }\n\tvirtual void *GetDataSwapped(int Index) { return m_DataFile.GetDataSwapped(Index); }\n\tvirtual void UnloadData(int Index) { m_DataFile.UnloadData(Index); }\n\tvirtual void *GetItem(int Index, int *pType, int *pID) { return m_DataFile.GetItem(Index, pType, pID); }\n\tvirtual void GetType(int Type, int *pStart, int *pNum) { m_DataFile.GetType(Type, pStart, pNum); }\n\tvirtual void *FindItem(int Type, int ID) { return m_DataFile.FindItem(Type, ID); }\n\tvirtual int NumItems() { return m_DataFile.NumItems(); }\n\n\tvirtual void Unload()\n\t{\n\t\tm_DataFile.Close();\n\t}\n\n\tvirtual bool Load(const char *pMapName, IStorage *pStorage)\n\t{\n\t\tif(!pStorage)\n\t\t\tpStorage = Kernel()->RequestInterface<IStorage>();\n\t\tif(!pStorage)\n\t\t\treturn false;\n\t\tif(!m_DataFile.Open(pStorage, pMapName, IStorage::TYPE_ALL))\n\t\t\treturn false;\n\t\t// check version\n\t\tCMapItemVersion *pItem = (CMapItemVersion *)m_DataFile.FindItem(MAPITEMTYPE_VERSION, 0);\n\t\tif(!pItem || pItem->m_Version != CMapItemVersion::CURRENT_VERSION)\n\t\t\treturn false;\n\t\t\n\t\treturn true;\n\t}\n\n\tvirtual bool IsLoaded()\n\t{\n\t\treturn m_DataFile.IsOpen();\n\t}\n\n\tvirtual unsigned Crc()\n\t{\n\t\treturn m_DataFile.Crc();\n\t}\n};\n\nextern IEngineMap *CreateEngineMap() { return new CMap; }\n"
  },
  {
    "path": "src/engine/shared/mapchecker.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/math.h>\n#include <base/system.h>\n\n#include <engine/storage.h>\n\n#include <versionsrv/versionsrv.h>\n#include <versionsrv/mapversions.h>\n\n#include \"datafile.h\"\n#include \"memheap.h\"\n#include \"mapchecker.h\"\n\nCMapChecker::CMapChecker()\n{\n\tInit();\n\tSetDefaults();\n}\n\nvoid CMapChecker::Init()\n{\n\tm_Whitelist.Reset();\n\tm_pFirst = 0;\n\tm_RemoveDefaultList = false;\n}\n\nvoid CMapChecker::SetDefaults()\n{\n\tAddMaplist(s_aMapVersionList, s_NumMapVersionItems);\n\tm_RemoveDefaultList = true;\n}\n\nvoid CMapChecker::AddMaplist(CMapVersion *pMaplist, int Num)\n{\n\tif(m_RemoveDefaultList)\n\t\tInit();\n\n\tfor(int i = 0; i < Num; ++i)\n\t{\n\t\tCWhitelistEntry *pEntry = (CWhitelistEntry *)m_Whitelist.Allocate(sizeof(CWhitelistEntry));\n\t\tpEntry->m_pNext = m_pFirst;\n\t\tm_pFirst = pEntry;\n\n\t\tstr_copy(pEntry->m_aMapName, pMaplist[i].m_aName, sizeof(pEntry->m_aMapName));\n\t\tpEntry->m_MapCrc = (pMaplist[i].m_aCrc[0]<<24) | (pMaplist[i].m_aCrc[1]<<16) | (pMaplist[i].m_aCrc[2]<<8) | pMaplist[i].m_aCrc[3];\n\t\tpEntry->m_MapSize = (pMaplist[i].m_aSize[0]<<24) | (pMaplist[i].m_aSize[1]<<16) | (pMaplist[i].m_aSize[2]<<8) | pMaplist[i].m_aSize[3];\n\t}\n}\n\nbool CMapChecker::IsMapValid(const char *pMapName, unsigned MapCrc, unsigned MapSize)\n{\n\treturn true;\n\t/*bool StandardMap = false;\n\tfor(CWhitelistEntry *pCurrent = m_pFirst; pCurrent; pCurrent = pCurrent->m_pNext)\n\t{\n\t\tif(str_comp(pCurrent->m_aMapName, pMapName) == 0)\n\t\t{\n\t\t\tStandardMap = true;\n\t\t\tif(pCurrent->m_MapCrc == MapCrc && pCurrent->m_MapSize == MapSize)\n\t\t\t\treturn true;\n\t\t}\n\t}\n\treturn StandardMap?false:true;*/\n}\n\nbool CMapChecker::ReadAndValidateMap(IStorage *pStorage, const char *pFilename, int StorageType)\n{\n\treturn true;\n\t/*bool LoadedMapInfo = false;\n\tbool StandardMap = false;\n\tunsigned MapCrc = 0;\n\tunsigned MapSize = 0;\n\n\t// extract map name\n\tchar aMapName[MAX_MAP_LENGTH];\n\tconst char *pExtractedName = pFilename;\n\tconst char *pEnd = 0;\n\tfor(const char *pSrc = pFilename; *pSrc; ++pSrc)\n\t{\n\t\tif(*pSrc == '/' || *pSrc == '\\\\')\n\t\t\tpExtractedName = pSrc+1;\n\t\telse if(*pSrc == '.')\n\t\t\tpEnd = pSrc;\n\t}\n\tint Length = (int)(pEnd - pExtractedName);\n\tif(Length <= 0 || Length >= MAX_MAP_LENGTH)\n\t\treturn true;\n\tstr_copy(aMapName, pExtractedName, min((int)MAX_MAP_LENGTH, (int)(pEnd-pExtractedName+1)));\n\n\t// check for valid map\n\tfor(CWhitelistEntry *pCurrent = m_pFirst; pCurrent; pCurrent = pCurrent->m_pNext)\n\t{\n\t\tif(str_comp(pCurrent->m_aMapName, aMapName) == 0)\n\t\t{\n\t\t\tStandardMap = true;\n\t\t\tif(!LoadedMapInfo)\n\t\t\t{\n\t\t\t\tif(!CDataFileReader::GetCrcSize(pStorage, pFilename, StorageType, &MapCrc, &MapSize))\n\t\t\t\t\treturn true;\n\t\t\t\tLoadedMapInfo = true;\n\t\t\t}\n\n\t\t\tif(pCurrent->m_MapCrc == MapCrc && pCurrent->m_MapSize == MapSize)\n\t\t\t\treturn true;\n\t\t}\n\t}\n\treturn StandardMap?false:true;*/\n}\n"
  },
  {
    "path": "src/engine/shared/mapchecker.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SHARED_MAPCHECKER_H\n#define ENGINE_SHARED_MAPCHECKER_H\n\n#include \"memheap.h\"\n\nclass CMapChecker\n{\n\tenum\n\t{\n\t\tMAX_MAP_LENGTH=8,\n\t};\n\n\tstruct CWhitelistEntry\n\t{\n\t\tchar m_aMapName[MAX_MAP_LENGTH];\n\t\tunsigned m_MapCrc;\n\t\tunsigned m_MapSize;\n\t\tCWhitelistEntry *m_pNext;\n\t};\n\n\tclass CHeap m_Whitelist;\n\tCWhitelistEntry *m_pFirst;\n\n\tbool m_RemoveDefaultList;\n\n\tvoid Init();\n\tvoid SetDefaults();\n\npublic:\n\tCMapChecker();\n\tvoid AddMaplist(struct CMapVersion *pMaplist, int Num);\n\tbool IsMapValid(const char *pMapName, unsigned MapCrc, unsigned MapSize);\n\tbool ReadAndValidateMap(class IStorage *pStorage, const char *pFilename, int StorageType);\n};\n\n#endif\n"
  },
  {
    "path": "src/engine/shared/masterserver.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <stdio.h>\t// sscanf\n\n#include <base/system.h>\n\n#include <engine/engine.h>\n#include <engine/masterserver.h>\n#include <engine/storage.h>\n\n#include \"linereader.h\"\n\nclass CMasterServer : public IEngineMasterServer\n{\npublic:\n\t// master server functions\n\tstruct CMasterInfo\n\t{\n\t\tchar m_aHostname[128];\n\t\tNETADDR m_Addr;\n\t\tbool m_Valid;\n\n\t\tCHostLookup m_Lookup;\n\t};\n\n\tenum\n\t{\n\t\tSTATE_INIT,\n\t\tSTATE_UPDATE,\n\t\tSTATE_READY,\n\t};\n\n\tCMasterInfo m_aMasterServers[MAX_MASTERSERVERS];\n\tint m_State;\n\tIEngine *m_pEngine;\n\tIStorage *m_pStorage;\n\n\tCMasterServer()\n\t{\n\t\tSetDefault();\n\t\tm_State = STATE_INIT;\n\t\tm_pEngine = 0;\n\t\tm_pStorage = 0;\n\t}\n\n\tvirtual int RefreshAddresses(int Nettype)\n\t{\n\t\tif(m_State != STATE_INIT && m_State != STATE_READY)\n\t\t\treturn -1;\n\n\t\tdbg_msg(\"engine/mastersrv\", \"refreshing master server addresses\");\n\n\t\t// add lookup jobs\n\t\tfor(int i = 0; i < MAX_MASTERSERVERS; i++)\n\t\t{\n\t\t\tm_pEngine->HostLookup(&m_aMasterServers[i].m_Lookup, m_aMasterServers[i].m_aHostname, Nettype);\n\t\t\tm_aMasterServers[i].m_Valid = false;\n\t\t}\n\n\t\tm_State = STATE_UPDATE;\n\t\treturn 0;\n\t}\n\n\tvirtual void Update()\n\t{\n\t\t// check if we need to update\n\t\tif(m_State != STATE_UPDATE)\n\t\t\treturn;\n\t\tm_State = STATE_READY;\n\n\t\tfor(int i = 0; i < MAX_MASTERSERVERS; i++)\n\t\t{\n\t\t\tif(m_aMasterServers[i].m_Lookup.m_Job.Status() != CJob::STATE_DONE)\n\t\t\t\tm_State = STATE_UPDATE;\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(m_aMasterServers[i].m_Lookup.m_Job.Result() == 0)\n\t\t\t\t{\n\t\t\t\t\tm_aMasterServers[i].m_Addr = m_aMasterServers[i].m_Lookup.m_Addr;\n\t\t\t\t\tm_aMasterServers[i].m_Addr.port = 8300;\n\t\t\t\t\tm_aMasterServers[i].m_Valid = true;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tm_aMasterServers[i].m_Valid = false;\n\t\t\t}\n\t\t}\n\n\t\tif(m_State == STATE_READY)\n\t\t{\n\t\t\tdbg_msg(\"engine/mastersrv\", \"saving addresses\");\n\t\t\tSave();\n\t\t}\n\t}\n\n\tvirtual int IsRefreshing()\n\t{\n\t\treturn m_State != STATE_READY;\n\t}\n\n\tvirtual NETADDR GetAddr(int Index)\n\t{\n\t\treturn m_aMasterServers[Index].m_Addr;\n\t}\n\n\tvirtual const char *GetName(int Index)\n\t{\n\t\treturn m_aMasterServers[Index].m_aHostname;\n\t}\n\n\tvirtual bool IsValid(int Index)\n\t{\n\t\treturn m_aMasterServers[Index].m_Valid;\n\t}\n\n\tvirtual void Init()\n\t{\n\t\tm_pEngine = Kernel()->RequestInterface<IEngine>();\n\t\tm_pStorage = Kernel()->RequestInterface<IStorage>();\n\t}\n\n\tvirtual void SetDefault()\n\t{\n\t\tmem_zero(m_aMasterServers, sizeof(m_aMasterServers));\n\t\tfor(int i = 0; i < MAX_MASTERSERVERS; i++)\n\t\t\tstr_format(m_aMasterServers[i].m_aHostname, sizeof(m_aMasterServers[i].m_aHostname), \"master%d.teeworlds.com\", i+1);\n\t}\n\n\tvirtual int Load()\n\t{\n\t\tif(!m_pStorage)\n\t\t\treturn -1;\n\n\t\t// try to open file\n\t\tIOHANDLE File = m_pStorage->OpenFile(\"masters.cfg\", IOFLAG_READ, IStorage::TYPE_SAVE);\n\t\tif(!File)\n\t\t\treturn -1;\n\n\t\tCLineReader LineReader;\n\t\tLineReader.Init(File);\n\t\twhile(1)\n\t\t{\n\t\t\tCMasterInfo Info = {{0}};\n\t\t\tconst char *pLine = LineReader.Get();\n\t\t\tif(!pLine)\n\t\t\t\tbreak;\n\n\t\t\t// parse line\n\t\t\tchar aAddrStr[NETADDR_MAXSTRSIZE];\n\t\t\tif(sscanf(pLine, \"%127s %47s\", Info.m_aHostname, aAddrStr) == 2 && net_addr_from_str(&Info.m_Addr, aAddrStr) == 0)\n\t\t\t{\n\t\t\t\tInfo.m_Addr.port = 8300;\n\t\t\t\tbool Added = false;\n\t\t\t\tfor(int i = 0; i < MAX_MASTERSERVERS; ++i)\n\t\t\t\t\tif(str_comp(m_aMasterServers[i].m_aHostname, Info.m_aHostname) == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_aMasterServers[i] = Info;\n\t\t\t\t\t\tAdded = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\tif(!Added)\n\t\t\t\t{\n\t\t\t\t\tfor(int i = 0; i < MAX_MASTERSERVERS; ++i)\n\t\t\t\t\t\tif(m_aMasterServers[i].m_Addr.type == NETTYPE_INVALID)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tm_aMasterServers[i] = Info;\n\t\t\t\t\t\t\tAdded = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(!Added)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tio_close(File);\n\t\treturn 0;\n\t}\n\n\tvirtual int Save()\n\t{\n\t\tif(!m_pStorage)\n\t\t\treturn -1;\n\n\t\t// try to open file\n\t\tIOHANDLE File = m_pStorage->OpenFile(\"masters.cfg\", IOFLAG_WRITE, IStorage::TYPE_SAVE);\n\t\tif(!File)\n\t\t\treturn -1;\n\n\t\tfor(int i = 0; i < MAX_MASTERSERVERS; i++)\n\t\t{\n\t\t\tchar aAddrStr[NETADDR_MAXSTRSIZE];\n\t\t\tif(m_aMasterServers[i].m_Addr.type != NETTYPE_INVALID)\n\t\t\t\tnet_addr_str(&m_aMasterServers[i].m_Addr, aAddrStr, sizeof(aAddrStr), true);\n\t\t\telse\n\t\t\t\taAddrStr[0] = 0;\n\t\t\tchar aBuf[256];\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"%s %s\", m_aMasterServers[i].m_aHostname, aAddrStr);\n\t\t\tio_write(File, aBuf, str_length(aBuf));\n\t\t\tio_write_newline(File);\n\t\t}\n\n\t\tio_close(File);\n\t\treturn 0;\n\t}\n};\n\nIEngineMasterServer *CreateEngineMasterServer() { return new CMasterServer; }\n"
  },
  {
    "path": "src/engine/shared/memheap.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n#include \"memheap.h\"\n\n\n// allocates a new chunk to be used\nvoid CHeap::NewChunk()\n{\n\tCChunk *pChunk;\n\tchar *pMem;\n\n\t// allocate memory\n\tpMem = (char*)mem_alloc(sizeof(CChunk)+CHUNK_SIZE, 1);\n\tif(!pMem)\n\t\treturn;\n\n\t// the chunk structure is located in the begining of the chunk\n\t// init it and return the chunk\n\tpChunk = (CChunk*)pMem;\n\tpChunk->m_pMemory = (char*)(pChunk+1);\n\tpChunk->m_pCurrent = pChunk->m_pMemory;\n\tpChunk->m_pEnd = pChunk->m_pMemory + CHUNK_SIZE;\n\tpChunk->m_pNext = (CChunk *)0x0;\n\n\tpChunk->m_pNext = m_pCurrent;\n\tm_pCurrent = pChunk;\n}\n\n//****************\nvoid *CHeap::AllocateFromChunk(unsigned int Size)\n{\n\tchar *pMem;\n\n\t// check if we need can fit the allocation\n\tif(m_pCurrent->m_pCurrent + Size > m_pCurrent->m_pEnd)\n\t\treturn (void*)0x0;\n\n\t// get memory and move the pointer forward\n\tpMem = m_pCurrent->m_pCurrent;\n\tm_pCurrent->m_pCurrent += Size;\n\treturn pMem;\n}\n\n// creates a heap\nCHeap::CHeap()\n{\n\tm_pCurrent = 0x0;\n\tReset();\n}\n\nCHeap::~CHeap()\n{\n\tClear();\n}\n\nvoid CHeap::Reset()\n{\n\tClear();\n\tNewChunk();\n}\n\n// destroys the heap\nvoid CHeap::Clear()\n{\n\tCChunk *pChunk = m_pCurrent;\n\tCChunk *pNext;\n\n\twhile(pChunk)\n\t{\n\t\tpNext = pChunk->m_pNext;\n\t\tmem_free(pChunk);\n\t\tpChunk = pNext;\n\t}\n\n\tm_pCurrent = 0x0;\n}\n\n//\nvoid *CHeap::Allocate(unsigned Size)\n{\n\tchar *pMem;\n\n\t// try to allocate from current chunk\n\tpMem = (char *)AllocateFromChunk(Size);\n\tif(!pMem)\n\t{\n\t\t// allocate new chunk and add it to the heap\n\t\tNewChunk();\n\n\t\t// try to allocate again\n\t\tpMem = (char *)AllocateFromChunk(Size);\n\t}\n\n\treturn pMem;\n}\n"
  },
  {
    "path": "src/engine/shared/memheap.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SHARED_MEMHEAP_H\n#define ENGINE_SHARED_MEMHEAP_H\nclass CHeap\n{\n\tstruct CChunk\n\t{\n\t\tchar *m_pMemory;\n\t\tchar *m_pCurrent;\n\t\tchar *m_pEnd;\n\t\tCChunk *m_pNext;\n\t};\n\n\tenum\n\t{\n\t\t// how large each chunk should be\n\t\tCHUNK_SIZE = 1024*64,\n\t};\n\n\tCChunk *m_pCurrent;\n\n\n\tvoid Clear();\n\tvoid NewChunk();\n\tvoid *AllocateFromChunk(unsigned int Size);\n\npublic:\n\tCHeap();\n\t~CHeap();\n\tvoid Reset();\n\tvoid *Allocate(unsigned Size);\n};\n#endif\n"
  },
  {
    "path": "src/engine/shared/message.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SHARED_MESSAGE_H\n#define ENGINE_SHARED_MESSAGE_H\nclass CMessage\n{\npublic:\n\tvirtual bool Pack(void *pData, unsigned MaxDataSize);\n\tvirtual bool Unpack(const void *pData, unsigned DataSize);\n};\n#endif\n"
  },
  {
    "path": "src/engine/shared/netban.cpp",
    "content": "#include <base/math.h>\n\n#include <engine/console.h>\n#include <engine/storage.h>\n#include <engine/shared/config.h>\n\n#include \"netban.h\"\n\n\nbool CNetBan::StrAllnum(const char *pStr)\n{\n\twhile(*pStr)\n\t{\n\t\tif(!(*pStr >= '0' && *pStr <= '9'))\n\t\t\treturn false;\n\t\tpStr++;\n\t}\n\treturn true;\n}\n\n\nCNetBan::CNetHash::CNetHash(const NETADDR *pAddr)\n{\n\tif(pAddr->type==NETTYPE_IPV4)\n\t\tm_Hash = (pAddr->ip[0]+pAddr->ip[1]+pAddr->ip[2]+pAddr->ip[3])&0xFF;\n\telse\n\t\tm_Hash = (pAddr->ip[0]+pAddr->ip[1]+pAddr->ip[2]+pAddr->ip[3]+pAddr->ip[4]+pAddr->ip[5]+pAddr->ip[6]+pAddr->ip[7]+\n\t\t\tpAddr->ip[8]+pAddr->ip[9]+pAddr->ip[10]+pAddr->ip[11]+pAddr->ip[12]+pAddr->ip[13]+pAddr->ip[14]+pAddr->ip[15])&0xFF;\n\tm_HashIndex = 0;\n}\n\nCNetBan::CNetHash::CNetHash(const CNetRange *pRange)\n{\n\tm_Hash = 0;\n\tm_HashIndex = 0;\n\tfor(int i = 0; pRange->m_LB.ip[i] == pRange->m_UB.ip[i]; ++i)\n\t{\n\t\tm_Hash += pRange->m_LB.ip[i];\n\t\t++m_HashIndex;\n\t}\n\tm_Hash &= 0xFF;\n}\n\nint CNetBan::CNetHash::MakeHashArray(const NETADDR *pAddr, CNetHash aHash[17])\n{\n\tint Length = pAddr->type==NETTYPE_IPV4 ? 4 : 16;\n\taHash[0].m_Hash = 0;\n\taHash[0].m_HashIndex = 0;\n\tfor(int i = 1, Sum = 0; i <= Length; ++i)\n\t{\n\t\tSum += pAddr->ip[i-1];\n\t\taHash[i].m_Hash = Sum&0xFF;\n\t\taHash[i].m_HashIndex = i%Length;\n\t}\n\treturn Length;\n}\n\n\ntemplate<class T, int HashCount>\ntypename CNetBan::CBan<T> *CNetBan::CBanPool<T, HashCount>::Add(const T *pData, const CBanInfo *pInfo,  const CNetHash *pNetHash)\n{\n\tif(!m_pFirstFree)\n\t\treturn 0;\n\n\t// create new ban\n\tCBan<T> *pBan = m_pFirstFree;\n\tpBan->m_Data = *pData;\n\tpBan->m_Info = *pInfo;\n\tpBan->m_NetHash = *pNetHash;\n\tif(pBan->m_pNext)\n\t\tpBan->m_pNext->m_pPrev = pBan->m_pPrev;\n\tif(pBan->m_pPrev)\n\t\tpBan->m_pPrev->m_pNext = pBan->m_pNext;\n\telse\n\t\tm_pFirstFree = pBan->m_pNext;\n\n\t// add it to the hash list\n\tif(m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash])\n\t\tm_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash]->m_pHashPrev = pBan;\n\tpBan->m_pHashPrev = 0;\n\tpBan->m_pHashNext = m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash];\n\tm_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash] = pBan;\n\n\t// insert it into the used list\n\tif(m_pFirstUsed)\n\t{\n\t\tfor(CBan<T> *p = m_pFirstUsed; ; p = p->m_pNext)\n\t\t{\n\t\t\tif(p->m_Info.m_Expires == CBanInfo::EXPIRES_NEVER || (pInfo->m_Expires != CBanInfo::EXPIRES_NEVER && pInfo->m_Expires <= p->m_Info.m_Expires))\n\t\t\t{\n\t\t\t\t// insert before\n\t\t\t\tpBan->m_pNext = p;\n\t\t\t\tpBan->m_pPrev = p->m_pPrev;\n\t\t\t\tif(p->m_pPrev)\n\t\t\t\t\tp->m_pPrev->m_pNext = pBan;\n\t\t\t\telse\n\t\t\t\t\tm_pFirstUsed = pBan;\n\t\t\t\tp->m_pPrev = pBan;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif(!p->m_pNext)\n\t\t\t{\n\t\t\t\t// last entry\n\t\t\t\tp->m_pNext = pBan;\n\t\t\t\tpBan->m_pPrev = p;\n\t\t\t\tpBan->m_pNext = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tm_pFirstUsed = pBan;\n\t\tpBan->m_pNext = pBan->m_pPrev = 0;\n\t}\n\n\t// update ban count\n\t++m_CountUsed;\n\n\treturn pBan;\n}\n\ntemplate<class T, int HashCount>\nint CNetBan::CBanPool<T, HashCount>::Remove(CBan<T> *pBan)\n{\n\tif(pBan == 0)\n\t\treturn -1;\n\n\t// remove from hash list\n\tif(pBan->m_pHashNext)\n\t\tpBan->m_pHashNext->m_pHashPrev = pBan->m_pHashPrev;\n\tif(pBan->m_pHashPrev)\n\t\tpBan->m_pHashPrev->m_pHashNext = pBan->m_pHashNext;\n\telse\n\t\tm_paaHashList[pBan->m_NetHash.m_HashIndex][pBan->m_NetHash.m_Hash] = pBan->m_pHashNext;\n\tpBan->m_pHashNext = pBan->m_pHashPrev = 0;\n\n\t// remove from used list\n\tif(pBan->m_pNext)\n\t\tpBan->m_pNext->m_pPrev = pBan->m_pPrev;\n\tif(pBan->m_pPrev)\n\t\tpBan->m_pPrev->m_pNext = pBan->m_pNext;\n\telse\n\t\tm_pFirstUsed = pBan->m_pNext;\n\n\t// add to recycle list\n\tif(m_pFirstFree)\n\t\tm_pFirstFree->m_pPrev = pBan;\n\tpBan->m_pPrev = 0;\n\tpBan->m_pNext = m_pFirstFree;\n\tm_pFirstFree = pBan;\n\n\t// update ban count\n\t--m_CountUsed;\n\n\treturn 0;\n}\n\ntemplate<class T, int HashCount>\nvoid CNetBan::CBanPool<T, HashCount>::Update(CBan<CDataType> *pBan, const CBanInfo *pInfo)\n{\n\tpBan->m_Info = *pInfo;\n\n\t// remove from used list\n\tif(pBan->m_pNext)\n\t\tpBan->m_pNext->m_pPrev = pBan->m_pPrev;\n\tif(pBan->m_pPrev)\n\t\tpBan->m_pPrev->m_pNext = pBan->m_pNext;\n\telse\n\t\tm_pFirstUsed = pBan->m_pNext;\n\n\t// insert it into the used list\n\tif(m_pFirstUsed)\n\t{\n\t\tfor(CBan<T> *p = m_pFirstUsed; ; p = p->m_pNext)\n\t\t{\n\t\t\tif(p->m_Info.m_Expires == CBanInfo::EXPIRES_NEVER || (pInfo->m_Expires != CBanInfo::EXPIRES_NEVER && pInfo->m_Expires <= p->m_Info.m_Expires))\n\t\t\t{\n\t\t\t\t// insert before\n\t\t\t\tpBan->m_pNext = p;\n\t\t\t\tpBan->m_pPrev = p->m_pPrev;\n\t\t\t\tif(p->m_pPrev)\n\t\t\t\t\tp->m_pPrev->m_pNext = pBan;\n\t\t\t\telse\n\t\t\t\t\tm_pFirstUsed = pBan;\n\t\t\t\tp->m_pPrev = pBan;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif(!p->m_pNext)\n\t\t\t{\n\t\t\t\t// last entry\n\t\t\t\tp->m_pNext = pBan;\n\t\t\t\tpBan->m_pPrev = p;\n\t\t\t\tpBan->m_pNext = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tm_pFirstUsed = pBan;\n\t\tpBan->m_pNext = pBan->m_pPrev = 0;\n\t}\n}\n\ntemplate<class T, int HashCount>\nvoid CNetBan::CBanPool<T, HashCount>::Reset()\n{\n\tmem_zero(m_paaHashList, sizeof(m_paaHashList));\n\tmem_zero(m_aBans, sizeof(m_aBans));\n\tm_pFirstUsed = 0;\n\tm_CountUsed = 0;\n\n\tfor(int i = 1; i < MAX_BANS-1; ++i)\n\t{\n\t\tm_aBans[i].m_pNext = &m_aBans[i+1];\n\t\tm_aBans[i].m_pPrev = &m_aBans[i-1];\n\t}\n\n\tm_aBans[0].m_pNext = &m_aBans[1];\n\tm_aBans[MAX_BANS-1].m_pPrev = &m_aBans[MAX_BANS-2];\n\tm_pFirstFree = &m_aBans[0];\n}\n\ntemplate<class T, int HashCount>\ntypename CNetBan::CBan<T> *CNetBan::CBanPool<T, HashCount>::Get(int Index) const\n{\n\tif(Index < 0 || Index >= Num())\n\t\treturn 0;\n\n\tfor(CNetBan::CBan<T> *pBan = m_pFirstUsed; pBan; pBan = pBan->m_pNext, --Index)\n\t{\n\t\tif(Index == 0)\n\t\t\treturn pBan;\n\t}\n\n\treturn 0;\n}\n\n\ntemplate<class T>\nvoid CNetBan::MakeBanInfo(const CBan<T> *pBan, char *pBuf, unsigned BuffSize, int Type) const\n{\n\tif(pBan == 0 || pBuf == 0)\n\t{\n\t\tif(BuffSize > 0)\n\t\t\tpBuf[0] = 0;\n\t\treturn;\n\t}\n\t\n\t// build type based part\n\tchar aBuf[256];\n\tif(Type == MSGTYPE_PLAYER)\n\t\tstr_copy(aBuf, \"You have been banned\", sizeof(aBuf));\n\telse\n\t{\n\t\tchar aTemp[256];\n\t\tswitch(Type)\n\t\t{\n\t\tcase MSGTYPE_LIST:\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"%s banned\", NetToString(&pBan->m_Data, aTemp, sizeof(aTemp))); break;\n\t\tcase MSGTYPE_BANADD:\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"banned %s\", NetToString(&pBan->m_Data, aTemp, sizeof(aTemp))); break;\n\t\tcase MSGTYPE_BANREM:\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"unbanned %s\", NetToString(&pBan->m_Data, aTemp, sizeof(aTemp))); break;\n\t\tdefault:\n\t\t\taBuf[0] = 0;\n\t\t}\n\t}\n\n\t// add info part\n\tif(pBan->m_Info.m_Expires != CBanInfo::EXPIRES_NEVER)\n\t{\n\t\tint Mins = ((pBan->m_Info.m_Expires-time_timestamp()) + 59) / 60;\n\t\tif(Mins <= 1)\n\t\t\tstr_format(pBuf, BuffSize, \"%s for 1 minute (%s)\", aBuf, pBan->m_Info.m_aReason);\n\t\telse\n\t\t\tstr_format(pBuf, BuffSize, \"%s for %d minutes (%s)\", aBuf, Mins, pBan->m_Info.m_aReason);\n\t}\n\telse\n\t\tstr_format(pBuf, BuffSize, \"%s for life (%s)\", aBuf, pBan->m_Info.m_aReason);\n}\n\ntemplate<class T>\nint CNetBan::Ban(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason)\n{\n\t// do not ban localhost\n\tif(NetMatch(pData, &m_LocalhostIPV4) || NetMatch(pData, &m_LocalhostIPV6))\n\t{\n\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", \"ban failed (localhost)\");\n\t\treturn -1;\n\t}\n\n\tint Stamp = Seconds > 0 ? time_timestamp()+Seconds : CBanInfo::EXPIRES_NEVER;\n\n\t// set up info\n\tCBanInfo Info = {0};\n\tInfo.m_Expires = Stamp;\n\tstr_copy(Info.m_aReason, pReason, sizeof(Info.m_aReason));\n\n\t// check if it already exists\n\tCNetHash NetHash(pData);\n\tCBan<typename T::CDataType> *pBan = pBanPool->Find(pData, &NetHash);\n\tif(pBan)\n\t{\n\t\t// adjust the ban\n\t\tpBanPool->Update(pBan, &Info);\n\t\tchar aBuf[128];\n\t\tMakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_LIST);\n\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", aBuf);\n\t\treturn 1;\n\t}\n\n\t// add ban and print result\n\tpBan = pBanPool->Add(pData, &Info, &NetHash);\n\tif(pBan)\n\t{\n\t\tchar aBuf[128];\n\t\tMakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_BANADD);\n\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", aBuf);\n\t\treturn 0;\n\t}\n\telse\n\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", \"ban failed (full banlist)\");\n\treturn -1;\n}\n\ntemplate<class T>\nint CNetBan::Unban(T *pBanPool, const typename T::CDataType *pData)\n{\n\tCNetHash NetHash(pData);\n\tCBan<typename T::CDataType> *pBan = pBanPool->Find(pData, &NetHash);\n\tif(pBan)\n\t{\n\t\tchar aBuf[256];\n\t\tMakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_BANREM);\n\t\tpBanPool->Remove(pBan);\n\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", aBuf);\n\t\treturn 0;\n\t}\n\telse\n\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", \"unban failed (invalid entry)\");\n\treturn -1;\n}\n\nvoid CNetBan::Init(IConsole *pConsole, IStorage *pStorage)\n{\n\tm_pConsole = pConsole;\n\tm_pStorage = pStorage;\n\tm_BanAddrPool.Reset();\n\tm_BanRangePool.Reset();\n\n\tnet_host_lookup(\"localhost\", &m_LocalhostIPV4, NETTYPE_IPV4);\n\tnet_host_lookup(\"localhost\", &m_LocalhostIPV6, NETTYPE_IPV6);\n\n\tConsole()->Register(\"ban\", \"s?ir\", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBan, this, \"Ban ip for x minutes for any reason\");\n\tConsole()->Register(\"ban_range\", \"ss?ir\", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBanRange, this, \"Ban ip range for x minutes for any reason\");\n\tConsole()->Register(\"unban\", \"s\", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConUnban, this, \"Unban ip/banlist entry\");\n\tConsole()->Register(\"unban_range\", \"ss\", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConUnbanRange, this, \"Unban ip range\");\n\tConsole()->Register(\"unban_all\", \"\", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConUnbanAll, this, \"Unban all entries\");\n\tConsole()->Register(\"bans\", \"\", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBans, this, \"Show banlist\");\n\tConsole()->Register(\"bans_save\", \"s\", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBansSave, this, \"Save banlist in a file\");\n}\n\nvoid CNetBan::Update()\n{\n\tint Now = time_timestamp();\n\n\t// remove expired bans\n\tchar aBuf[256], aNetStr[256];\n\twhile(m_BanAddrPool.First() && m_BanAddrPool.First()->m_Info.m_Expires != CBanInfo::EXPIRES_NEVER && m_BanAddrPool.First()->m_Info.m_Expires < Now)\n\t{\n\t\tstr_format(aBuf, sizeof(aBuf), \"ban %s expired\", NetToString(&m_BanAddrPool.First()->m_Data, aNetStr, sizeof(aNetStr)));\n\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", aBuf);\n\t\tm_BanAddrPool.Remove(m_BanAddrPool.First());\n\t}\n\twhile(m_BanRangePool.First() && m_BanRangePool.First()->m_Info.m_Expires != CBanInfo::EXPIRES_NEVER && m_BanRangePool.First()->m_Info.m_Expires < Now)\n\t{\n\t\tstr_format(aBuf, sizeof(aBuf), \"ban %s expired\", NetToString(&m_BanRangePool.First()->m_Data, aNetStr, sizeof(aNetStr)));\n\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", aBuf);\n\t\tm_BanRangePool.Remove(m_BanRangePool.First());\n\t}\n}\n\nint CNetBan::BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason)\n{\n\treturn Ban(&m_BanAddrPool, pAddr, Seconds, pReason);\n}\n\nint CNetBan::BanRange(const CNetRange *pRange, int Seconds, const char *pReason)\n{\n\tif(pRange->IsValid())\n\t\treturn Ban(&m_BanRangePool, pRange, Seconds, pReason);\n\n\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", \"ban failed (invalid range)\");\n\treturn -1;\n}\n\nint CNetBan::UnbanByAddr(const NETADDR *pAddr)\n{\n\treturn Unban(&m_BanAddrPool, pAddr);\n}\n\nint CNetBan::UnbanByRange(const CNetRange *pRange)\n{\n\tif(pRange->IsValid())\n\t\treturn Unban(&m_BanRangePool, pRange);\n\t\n\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", \"ban failed (invalid range)\");\n\treturn -1;\n}\n\nint CNetBan::UnbanByIndex(int Index)\n{\n\tint Result;\n\tchar aBuf[256];\n\tCBanAddr *pBan = m_BanAddrPool.Get(Index);\n\tif(pBan)\n\t{\n\t\tNetToString(&pBan->m_Data, aBuf, sizeof(aBuf));\n\t\tResult = m_BanAddrPool.Remove(pBan);\n\t}\n\telse\n\t{\n\t\tCBanRange *pBan = m_BanRangePool.Get(Index-m_BanAddrPool.Num());\n\t\tif(pBan)\n\t\t{\n\t\t\tNetToString(&pBan->m_Data, aBuf, sizeof(aBuf));\n\t\t\tResult = m_BanRangePool.Remove(pBan);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", \"unban failed (invalid index)\");\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tchar aMsg[256];\n\tstr_format(aMsg, sizeof(aMsg), \"unbanned index %i (%s)\", Index, aBuf);\n\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", aMsg);\n\treturn Result;\n}\n\nbool CNetBan::IsBanned(const NETADDR *pAddr, char *pBuf, unsigned BufferSize) const\n{\n\tCNetHash aHash[17];\n\tint Length = CNetHash::MakeHashArray(pAddr, aHash);\n\n\t// check ban adresses\n\tCBanAddr *pBan = m_BanAddrPool.Find(pAddr, &aHash[Length]);\n\tif(pBan)\n\t{\n\t\tMakeBanInfo(pBan, pBuf, BufferSize, MSGTYPE_PLAYER);\n\t\treturn true;\n\t}\n\n\t// check ban ranges\n\tfor(int i = Length-1; i >= 0; --i)\n\t{\n\t\tfor(CBanRange *pBan = m_BanRangePool.First(&aHash[i]); pBan; pBan = pBan->m_pHashNext)\n\t\t{\n\t\t\tif(NetMatch(&pBan->m_Data, pAddr, i, Length))\n\t\t\t{\n\t\t\t\tMakeBanInfo(pBan, pBuf, BufferSize, MSGTYPE_PLAYER);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn false;\n}\n\nvoid CNetBan::ConBan(IConsole::IResult *pResult, void *pUser)\n{\n\tCNetBan *pThis = static_cast<CNetBan *>(pUser);\n\n\tconst char *pStr = pResult->GetString(0);\n\tint Minutes = pResult->NumArguments()>1 ? clamp(pResult->GetInteger(1), 0, 44640) : 30;\n\tconst char *pReason = pResult->NumArguments()>2 ? pResult->GetString(2) : \"No reason given\";\n\n\tNETADDR Addr;\n\tif(net_addr_from_str(&Addr, pStr) == 0)\n\t\tpThis->BanAddr(&Addr, Minutes*60, pReason);\n\telse\n\t\tpThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", \"ban error (invalid network address)\");\n}\n\nvoid CNetBan::ConBanRange(IConsole::IResult *pResult, void *pUser)\n{\n\tCNetBan *pThis = static_cast<CNetBan *>(pUser);\n\n\tconst char *pStr1 = pResult->GetString(0);\n\tconst char *pStr2 = pResult->GetString(1);\n\tint Minutes = pResult->NumArguments()>2 ? clamp(pResult->GetInteger(2), 0, 44640) : 30;\n\tconst char *pReason = pResult->NumArguments()>3 ? pResult->GetString(3) : \"No reason given\";\n\n\tCNetRange Range;\n\tif(net_addr_from_str(&Range.m_LB, pStr1) == 0 && net_addr_from_str(&Range.m_UB, pStr2) == 0)\n\t\tpThis->BanRange(&Range, Minutes*60, pReason);\n\telse\n\t\tpThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", \"ban error (invalid range)\");\n}\n\nvoid CNetBan::ConUnban(IConsole::IResult *pResult, void *pUser)\n{\n\tCNetBan *pThis = static_cast<CNetBan *>(pUser);\n\n\tconst char *pStr = pResult->GetString(0);\n\tif(StrAllnum(pStr))\n\t\tpThis->UnbanByIndex(str_toint(pStr));\n\telse\n\t{\n\t\tNETADDR Addr;\n\t\tif(net_addr_from_str(&Addr, pStr) == 0)\n\t\t\tpThis->UnbanByAddr(&Addr);\n\t\telse\n\t\t\tpThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", \"unban error (invalid network address)\");\n\t}\n}\n\nvoid CNetBan::ConUnbanRange(IConsole::IResult *pResult, void *pUser)\n{\n\tCNetBan *pThis = static_cast<CNetBan *>(pUser);\n\n\tconst char *pStr1 = pResult->GetString(0);\n\tconst char *pStr2 = pResult->GetString(1);\n\n\tCNetRange Range;\n\tif(net_addr_from_str(&Range.m_LB, pStr1) == 0 && net_addr_from_str(&Range.m_UB, pStr2) == 0)\n\t\tpThis->UnbanByRange(&Range);\n\telse\n\t\tpThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", \"unban error (invalid range)\");\n}\n\nvoid CNetBan::ConUnbanAll(IConsole::IResult *pResult, void *pUser)\n{\n\tCNetBan *pThis = static_cast<CNetBan *>(pUser);\n\n\tpThis->UnbanAll();\n\tpThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", \"unbanned all entries\");\n}\n\nvoid CNetBan::ConBans(IConsole::IResult *pResult, void *pUser)\n{\n\tCNetBan *pThis = static_cast<CNetBan *>(pUser);\n\n\tint Count = 0;\n\tchar aBuf[256], aMsg[256];\n\tfor(CBanAddr *pBan = pThis->m_BanAddrPool.First(); pBan; pBan = pBan->m_pNext)\n\t{\n\t\tpThis->MakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_LIST);\n\t\tstr_format(aMsg, sizeof(aMsg), \"#%i %s\", Count++, aBuf);\n\t\tpThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", aMsg);\n\t}\n\tfor(CBanRange *pBan = pThis->m_BanRangePool.First(); pBan; pBan = pBan->m_pNext)\n\t{\n\t\tpThis->MakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_LIST);\n\t\tstr_format(aMsg, sizeof(aMsg), \"#%i %s\", Count++, aBuf);\n\t\tpThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", aMsg);\n\t}\n\tstr_format(aMsg, sizeof(aMsg), \"%d %s\", Count, Count==1?\"ban\":\"bans\");\n\tpThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", aMsg);\n}\n\nvoid CNetBan::ConBansSave(IConsole::IResult *pResult, void *pUser)\n{\n\tCNetBan *pThis = static_cast<CNetBan *>(pUser);\n\n\tchar aBuf[256];\n\tIOHANDLE File = pThis->Storage()->OpenFile(pResult->GetString(0), IOFLAG_WRITE, IStorage::TYPE_SAVE);\n\tif(!File)\n\t{\n\t\tstr_format(aBuf, sizeof(aBuf), \"failed to save banlist to '%s'\", pResult->GetString(0));\n\t\tpThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", aBuf);\n\t\treturn;\n\t}\n\n\tint Now = time_timestamp();\n\tchar aAddrStr1[NETADDR_MAXSTRSIZE], aAddrStr2[NETADDR_MAXSTRSIZE];\n\tfor(CBanAddr *pBan = pThis->m_BanAddrPool.First(); pBan; pBan = pBan->m_pNext)\n\t{\n\t\tint Min = pBan->m_Info.m_Expires>-1 ? (pBan->m_Info.m_Expires-Now+59)/60 : -1;\n\t\tnet_addr_str(&pBan->m_Data, aAddrStr1, sizeof(aAddrStr1), false);\n\t\tstr_format(aBuf, sizeof(aBuf), \"ban %s %i %s\", aAddrStr1, Min, pBan->m_Info.m_aReason);\n\t\tio_write(File, aBuf, str_length(aBuf));\n\t\tio_write_newline(File);\n\t}\n\tfor(CBanRange *pBan = pThis->m_BanRangePool.First(); pBan; pBan = pBan->m_pNext)\n\t{\n\t\tint Min = pBan->m_Info.m_Expires>-1 ? (pBan->m_Info.m_Expires-Now+59)/60 : -1;\n\t\tnet_addr_str(&pBan->m_Data.m_LB, aAddrStr1, sizeof(aAddrStr1), false);\n\t\tnet_addr_str(&pBan->m_Data.m_UB, aAddrStr2, sizeof(aAddrStr2), false);\n\t\tstr_format(aBuf, sizeof(aBuf), \"ban_range %s %s %i %s\", aAddrStr1, aAddrStr2, Min, pBan->m_Info.m_aReason);\n\t\tio_write(File, aBuf, str_length(aBuf));\n\t\tio_write_newline(File);\n\t}\n\n\tio_close(File);\n\tstr_format(aBuf, sizeof(aBuf), \"saved banlist to '%s'\", pResult->GetString(0));\n\tpThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"net_ban\", aBuf);\n}\n"
  },
  {
    "path": "src/engine/shared/netban.h",
    "content": "#ifndef ENGINE_SHARED_NETBAN_H\n#define ENGINE_SHARED_NETBAN_H\n\n#include <base/system.h>\n\n\ninline int NetComp(const NETADDR *pAddr1, const NETADDR *pAddr2)\n{\n\treturn mem_comp(pAddr1, pAddr2, pAddr1->type==NETTYPE_IPV4 ? 8 : 20);\n}\n\nclass CNetRange\n{\npublic:\n\tNETADDR m_LB;\n\tNETADDR m_UB;\n\n\tbool IsValid() const { return m_LB.type == m_UB.type && NetComp(&m_LB, &m_UB) < 0; }\n};\n\ninline int NetComp(const CNetRange *pRange1, const CNetRange *pRange2)\n{\n\treturn NetComp(&pRange1->m_LB, &pRange2->m_LB) || NetComp(&pRange1->m_UB, &pRange2->m_UB);\n}\n\n\nclass CNetBan\n{\nprotected:\n\tbool NetMatch(const NETADDR *pAddr1, const NETADDR *pAddr2) const\n\t{\n\t\treturn NetComp(pAddr1, pAddr2) == 0;\n\t}\n\n\tbool NetMatch(const CNetRange *pRange, const NETADDR *pAddr, int Start, int Length) const\n\t{\n\t\treturn pRange->m_LB.type == pAddr->type && (Start == 0 || mem_comp(&pRange->m_LB.ip[0], &pAddr->ip[0], Start) == 0) &&\n\t\t\tmem_comp(&pRange->m_LB.ip[Start], &pAddr->ip[Start], Length-Start) <= 0 && mem_comp(&pRange->m_UB.ip[Start], &pAddr->ip[Start], Length-Start) >= 0;\n\t}\n\n\tbool NetMatch(const CNetRange *pRange, const NETADDR *pAddr) const\n\t{\n\t\treturn NetMatch(pRange, pAddr, 0,  pRange->m_LB.type==NETTYPE_IPV4 ? 4 : 16);\n\t}\n\n\tconst char *NetToString(const NETADDR *pData, char *pBuffer, unsigned BufferSize) const\n\t{\n\t\tchar aAddrStr[NETADDR_MAXSTRSIZE];\n\t\tnet_addr_str(pData, aAddrStr, sizeof(aAddrStr), false);\n\t\tstr_format(pBuffer, BufferSize, \"'%s'\", aAddrStr);\n\t\treturn pBuffer;\n\t}\n\n\tconst char *NetToString(const CNetRange *pData, char *pBuffer, unsigned BufferSize) const\n\t{\n\t\tchar aAddrStr1[NETADDR_MAXSTRSIZE], aAddrStr2[NETADDR_MAXSTRSIZE];\n\t\tnet_addr_str(&pData->m_LB, aAddrStr1, sizeof(aAddrStr1), false);\n\t\tnet_addr_str(&pData->m_UB, aAddrStr2, sizeof(aAddrStr2), false);\n\t\tstr_format(pBuffer, BufferSize, \"'%s' - '%s'\", aAddrStr1, aAddrStr2);\n\t\treturn pBuffer;\n\t}\n\n\t// todo: move?\n\tstatic bool StrAllnum(const char *pStr);\n\n\tclass CNetHash\n\t{\n\tpublic:\n\t\tint m_Hash;\n\t\tint m_HashIndex;\t// matching parts for ranges, 0 for addr\n\n\t\tCNetHash() {}\t\n\t\tCNetHash(const NETADDR *pAddr);\n\t\tCNetHash(const CNetRange *pRange);\n\n\t\tstatic int MakeHashArray(const NETADDR *pAddr, CNetHash aHash[17]);\n\t};\n\n\tstruct CBanInfo\n\t{\n\t\tenum\n\t\t{\n\t\t\tEXPIRES_NEVER=-1,\n\t\t\tREASON_LENGTH=64,\n\t\t};\n\t\tint m_Expires;\n\t\tchar m_aReason[REASON_LENGTH];\n\t};\n\n\ttemplate<class T> struct CBan\n\t{\n\t\tT m_Data;\n\t\tCBanInfo m_Info;\n\t\tCNetHash m_NetHash;\n\n\t\t// hash list\n\t\tCBan *m_pHashNext;\n\t\tCBan *m_pHashPrev;\n\n\t\t// used or free list\n\t\tCBan *m_pNext;\n\t\tCBan *m_pPrev;\n\t};\n\n\ttemplate<class T, int HashCount> class CBanPool\n\t{\n\tpublic:\n\t\ttypedef T CDataType;\n\n\t\tCBan<CDataType> *Add(const CDataType *pData, const CBanInfo *pInfo, const CNetHash *pNetHash);\n\t\tint Remove(CBan<CDataType> *pBan);\n\t\tvoid Update(CBan<CDataType> *pBan, const CBanInfo *pInfo);\n\t\tvoid Reset();\n\t\n\t\tint Num() const { return m_CountUsed; }\n\t\tbool IsFull() const { return m_CountUsed == MAX_BANS; }\n\n\t\tCBan<CDataType> *First() const { return m_pFirstUsed; }\n\t\tCBan<CDataType> *First(const CNetHash *pNetHash) const { return m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash]; }\n\t\tCBan<CDataType> *Find(const CDataType *pData, const CNetHash *pNetHash) const\n\t\t{\n\t\t\tfor(CBan<CDataType> *pBan = m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash]; pBan; pBan = pBan->m_pHashNext)\n\t\t\t{\n\t\t\t\tif(NetComp(&pBan->m_Data, pData) == 0)\n\t\t\t\t\treturn pBan;\n\t\t\t}\n\n\t\t\treturn 0;\n\t\t}\n\t\tCBan<CDataType> *Get(int Index) const;\n\n\tprivate:\n\t\tenum\n\t\t{\n\t\t\tMAX_BANS=1024,\n\t\t};\n\n\t\tCBan<CDataType> *m_paaHashList[HashCount][256];\n\t\tCBan<CDataType> m_aBans[MAX_BANS];\n\t\tCBan<CDataType> *m_pFirstFree;\n\t\tCBan<CDataType> *m_pFirstUsed;\n\t\tint m_CountUsed;\n\t};\n\n\ttypedef CBanPool<NETADDR, 1> CBanAddrPool;\n\ttypedef CBanPool<CNetRange, 16> CBanRangePool;\n\ttypedef CBan<NETADDR> CBanAddr;\n\ttypedef CBan<CNetRange> CBanRange;\n\t\n\ttemplate<class T> void MakeBanInfo(const CBan<T> *pBan, char *pBuf, unsigned BuffSize, int Type) const;\n\ttemplate<class T> int Ban(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason);\n\ttemplate<class T> int Unban(T *pBanPool, const typename T::CDataType *pData);\n\n\tclass IConsole *m_pConsole;\n\tclass IStorage *m_pStorage;\n\tCBanAddrPool m_BanAddrPool;\n\tCBanRangePool m_BanRangePool;\n\tNETADDR m_LocalhostIPV4, m_LocalhostIPV6;\n\npublic:\n\tenum\n\t{\n\t\tMSGTYPE_PLAYER=0,\n\t\tMSGTYPE_LIST,\n\t\tMSGTYPE_BANADD,\n\t\tMSGTYPE_BANREM,\n\t};\n\n\tclass IConsole *Console() const { return m_pConsole; }\n\tclass IStorage *Storage() const { return m_pStorage; }\n\n\tvirtual ~CNetBan() {}\n\tvoid Init(class IConsole *pConsole, class IStorage *pStorage);\n\tvoid Update();\n\n\tvirtual int BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason);\n\tvirtual int BanRange(const CNetRange *pRange, int Seconds, const char *pReason);\n\tint UnbanByAddr(const NETADDR *pAddr);\n\tint UnbanByRange(const CNetRange *pRange);\n\tint UnbanByIndex(int Index);\n\tvoid UnbanAll() { m_BanAddrPool.Reset(); m_BanRangePool.Reset(); }\n\tbool IsBanned(const NETADDR *pAddr, char *pBuf, unsigned BufferSize) const;\n\n\tstatic void ConBan(class IConsole::IResult *pResult, void *pUser);\n\tstatic void ConBanRange(class IConsole::IResult *pResult, void *pUser);\n\tstatic void ConUnban(class IConsole::IResult *pResult, void *pUser);\n\tstatic void ConUnbanRange(class IConsole::IResult *pResult, void *pUser);\n\tstatic void ConUnbanAll(class IConsole::IResult *pResult, void *pUser);\n\tstatic void ConBans(class IConsole::IResult *pResult, void *pUser);\n\tstatic void ConBansSave(class IConsole::IResult *pResult, void *pUser);\n};\n\n#endif\n"
  },
  {
    "path": "src/engine/shared/network.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n\n\n#include \"config.h\"\n#include \"network.h\"\n#include \"huffman.h\"\n\nvoid CNetRecvUnpacker::Clear()\n{\n\tm_Valid = false;\n}\n\nvoid CNetRecvUnpacker::Start(const NETADDR *pAddr, CNetConnection *pConnection, int ClientID)\n{\n\tm_Addr = *pAddr;\n\tm_pConnection = pConnection;\n\tm_ClientID = ClientID;\n\tm_CurrentChunk = 0;\n\tm_Valid = true;\n}\n\n// TODO: rename this function\nint CNetRecvUnpacker::FetchChunk(CNetChunk *pChunk)\n{\n\tCNetChunkHeader Header;\n\tunsigned char *pEnd = m_Data.m_aChunkData + m_Data.m_DataSize;\n\n\twhile(1)\n\t{\n\t\tunsigned char *pData = m_Data.m_aChunkData;\n\n\t\t// check for old data to unpack\n\t\tif(!m_Valid || m_CurrentChunk >= m_Data.m_NumChunks)\n\t\t{\n\t\t\tClear();\n\t\t\treturn 0;\n\t\t}\n\n\t\t// TODO: add checking here so we don't read too far\n\t\tfor(int i = 0; i < m_CurrentChunk; i++)\n\t\t{\n\t\t\tpData = Header.Unpack(pData);\n\t\t\tpData += Header.m_Size;\n\t\t}\n\n\t\t// unpack the header\n\t\tpData = Header.Unpack(pData);\n\t\tm_CurrentChunk++;\n\n\t\tif(pData+Header.m_Size > pEnd)\n\t\t{\n\t\t\tClear();\n\t\t\treturn 0;\n\t\t}\n\n\t\t// handle sequence stuff\n\t\tif(m_pConnection && (Header.m_Flags&NET_CHUNKFLAG_VITAL))\n\t\t{\n\t\t\tif(Header.m_Sequence == (m_pConnection->m_Ack+1)%NET_MAX_SEQUENCE)\n\t\t\t{\n\t\t\t\t// in sequence\n\t\t\t\tm_pConnection->m_Ack = (m_pConnection->m_Ack+1)%NET_MAX_SEQUENCE;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// old packet that we already got\n\t\t\t\tif(CNetBase::IsSeqInBackroom(Header.m_Sequence, m_pConnection->m_Ack))\n\t\t\t\t\tcontinue;\n\n\t\t\t\t// out of sequence, request resend\n\t\t\t\tif(g_Config.m_Debug)\n\t\t\t\t\tdbg_msg(\"conn\", \"asking for resend %d %d\", Header.m_Sequence, (m_pConnection->m_Ack+1)%NET_MAX_SEQUENCE);\n\t\t\t\tm_pConnection->SignalResend();\n\t\t\t\tcontinue; // take the next chunk in the packet\n\t\t\t}\n\t\t}\n\n\t\t// fill in the info\n\t\tpChunk->m_ClientID = m_ClientID;\n\t\tpChunk->m_Address = m_Addr;\n\t\tpChunk->m_Flags = 0;\n\t\tpChunk->m_DataSize = Header.m_Size;\n\t\tpChunk->m_pData = pData;\n\t\treturn 1;\n\t}\n}\n\n// packs the data tight and sends it\nvoid CNetBase::SendPacketConnless(NETSOCKET Socket, NETADDR *pAddr, const void *pData, int DataSize)\n{\n\tunsigned char aBuffer[NET_MAX_PACKETSIZE];\n\taBuffer[0] = 0xff;\n\taBuffer[1] = 0xff;\n\taBuffer[2] = 0xff;\n\taBuffer[3] = 0xff;\n\taBuffer[4] = 0xff;\n\taBuffer[5] = 0xff;\n\tmem_copy(&aBuffer[6], pData, DataSize);\n\tnet_udp_send(Socket, pAddr, aBuffer, 6+DataSize);\n}\n\nvoid CNetBase::SendPacket(NETSOCKET Socket, NETADDR *pAddr, CNetPacketConstruct *pPacket)\n{\n\tunsigned char aBuffer[NET_MAX_PACKETSIZE];\n\tint CompressedSize = -1;\n\tint FinalSize = -1;\n\n\t// log the data\n\tif(ms_DataLogSent)\n\t{\n\t\tint Type = 1;\n\t\tio_write(ms_DataLogSent, &Type, sizeof(Type));\n\t\tio_write(ms_DataLogSent, &pPacket->m_DataSize, sizeof(pPacket->m_DataSize));\n\t\tio_write(ms_DataLogSent, &pPacket->m_aChunkData, pPacket->m_DataSize);\n\t\tio_flush(ms_DataLogSent);\n\t}\n\n\t// compress\n\tCompressedSize = ms_Huffman.Compress(pPacket->m_aChunkData, pPacket->m_DataSize, &aBuffer[3], NET_MAX_PACKETSIZE-4);\n\n\t// check if the compression was enabled, successful and good enough\n\tif(CompressedSize > 0 && CompressedSize < pPacket->m_DataSize)\n\t{\n\t\tFinalSize = CompressedSize;\n\t\tpPacket->m_Flags |= NET_PACKETFLAG_COMPRESSION;\n\t}\n\telse\n\t{\n\t\t// use uncompressed data\n\t\tFinalSize = pPacket->m_DataSize;\n\t\tmem_copy(&aBuffer[3], pPacket->m_aChunkData, pPacket->m_DataSize);\n\t\tpPacket->m_Flags &= ~NET_PACKETFLAG_COMPRESSION;\n\t}\n\n\t// set header and send the packet if all things are good\n\tif(FinalSize >= 0)\n\t{\n\t\tFinalSize += NET_PACKETHEADERSIZE;\n\t\taBuffer[0] = ((pPacket->m_Flags<<4)&0xf0)|((pPacket->m_Ack>>8)&0xf);\n\t\taBuffer[1] = pPacket->m_Ack&0xff;\n\t\taBuffer[2] = pPacket->m_NumChunks;\n\t\tnet_udp_send(Socket, pAddr, aBuffer, FinalSize);\n\n\t\t// log raw socket data\n\t\tif(ms_DataLogSent)\n\t\t{\n\t\t\tint Type = 0;\n\t\t\tio_write(ms_DataLogSent, &Type, sizeof(Type));\n\t\t\tio_write(ms_DataLogSent, &FinalSize, sizeof(FinalSize));\n\t\t\tio_write(ms_DataLogSent, aBuffer, FinalSize);\n\t\t\tio_flush(ms_DataLogSent);\n\t\t}\n\t}\n}\n\n// TODO: rename this function\nint CNetBase::UnpackPacket(unsigned char *pBuffer, int Size, CNetPacketConstruct *pPacket)\n{\n\t// check the size\n\tif(Size < NET_PACKETHEADERSIZE || Size > NET_MAX_PACKETSIZE)\n\t{\n\t\tif(g_Config.m_Debug)\n\t\t\tdbg_msg(\"network\", \"packet too small, %d\", Size);\n\t\treturn -1;\n\t}\n\n\t// log the data\n\tif(ms_DataLogRecv)\n\t{\n\t\tint Type = 0;\n\t\tio_write(ms_DataLogRecv, &Type, sizeof(Type));\n\t\tio_write(ms_DataLogRecv, &Size, sizeof(Size));\n\t\tio_write(ms_DataLogRecv, pBuffer, Size);\n\t\tio_flush(ms_DataLogRecv);\n\t}\n\n\t// read the packet\n\tpPacket->m_Flags = pBuffer[0]>>4;\n\tif(pPacket->m_Flags&NET_PACKETFLAG_CONNLESS)\n\t{\n\t\tif(Size < 6)\n\t\t{\n\t\t\tif(g_Config.m_Debug)\n\t\t\t\tdbg_msg(\"network\", \"connection less packet too small, %d\", Size);\n\t\t\treturn -1;\n\t\t}\n\n\t\tpPacket->m_Flags = NET_PACKETFLAG_CONNLESS;\n\t\tpPacket->m_Ack = 0;\n\t\tpPacket->m_NumChunks = 0;\n\t\tpPacket->m_DataSize = Size - 6;\n\t\tmem_copy(pPacket->m_aChunkData, &pBuffer[6], pPacket->m_DataSize);\n\t}\n\telse\n\t{\n\t\tif(Size-NET_PACKETHEADERSIZE > NET_MAX_PAYLOAD)\n\t\t{\n\t\t\tif(g_Config.m_Debug)\n\t\t\t\tdbg_msg(\"network\", \"packet too big, %d\", Size);\n\t\t\treturn -1;\n\t\t}\n\n\t\tpPacket->m_Ack = ((pBuffer[0]&0xf)<<8) | pBuffer[1];\n\t\tpPacket->m_NumChunks = pBuffer[2];\n\t\tpPacket->m_DataSize = Size - NET_PACKETHEADERSIZE;\n\t\tif(pPacket->m_Flags&NET_PACKETFLAG_COMPRESSION)\n\t\t\tpPacket->m_DataSize = ms_Huffman.Decompress(&pBuffer[3], pPacket->m_DataSize, pPacket->m_aChunkData, sizeof(pPacket->m_aChunkData));\n\t\telse\n\t\t\tmem_copy(pPacket->m_aChunkData, &pBuffer[3], pPacket->m_DataSize);\n\t}\n\n\t// check for errors\n\tif(pPacket->m_DataSize < 0)\n\t{\n\t\tif(g_Config.m_Debug)\n\t\t\tdbg_msg(\"network\", \"error during packet decoding\");\n\t\treturn -1;\n\t}\n\n\t// log the data\n\tif(ms_DataLogRecv)\n\t{\n\t\tint Type = 1;\n\t\tio_write(ms_DataLogRecv, &Type, sizeof(Type));\n\t\tio_write(ms_DataLogRecv, &pPacket->m_DataSize, sizeof(pPacket->m_DataSize));\n\t\tio_write(ms_DataLogRecv, pPacket->m_aChunkData, pPacket->m_DataSize);\n\t\tio_flush(ms_DataLogRecv);\n\t}\n\n\t// return success\n\treturn 0;\n}\n\n\nvoid CNetBase::SendControlMsg(NETSOCKET Socket, NETADDR *pAddr, int Ack, int ControlMsg, const void *pExtra, int ExtraSize)\n{\n\tCNetPacketConstruct Construct;\n\tConstruct.m_Flags = NET_PACKETFLAG_CONTROL;\n\tConstruct.m_Ack = Ack;\n\tConstruct.m_NumChunks = 0;\n\tConstruct.m_DataSize = 1+ExtraSize;\n\tConstruct.m_aChunkData[0] = ControlMsg;\n\tmem_copy(&Construct.m_aChunkData[1], pExtra, ExtraSize);\n\n\t// send the control message\n\tCNetBase::SendPacket(Socket, pAddr, &Construct);\n}\n\n\n\nunsigned char *CNetChunkHeader::Pack(unsigned char *pData)\n{\n\tpData[0] = ((m_Flags&0x03)<<6) | ((m_Size>>6)&0x3F);\n\tpData[1] = (m_Size&0x3F);\n\tif(m_Flags&NET_CHUNKFLAG_VITAL)\n\t{\n\t\tpData[1] |= (m_Sequence>>2)&0xC0;\n\t\tpData[2] = m_Sequence&0xFF;\n\t\treturn pData + 3;\n\t}\n\treturn pData + 2;\n}\n\nunsigned char *CNetChunkHeader::Unpack(unsigned char *pData)\n{\n\tm_Flags = (pData[0]>>6)&0x03;\n\tm_Size = ((pData[0]&0x3F)<<6) | (pData[1]&0x3F);\n\tm_Sequence = -1;\n\tif(m_Flags&NET_CHUNKFLAG_VITAL)\n\t{\n\t\tm_Sequence = ((pData[1]&0xC0)<<2) | pData[2];\n\t\treturn pData + 3;\n\t}\n\treturn pData + 2;\n}\n\n\nint CNetBase::IsSeqInBackroom(int Seq, int Ack)\n{\n\tint Bottom = (Ack-NET_MAX_SEQUENCE/2);\n\tif(Bottom < 0)\n\t{\n\t\tif(Seq <= Ack)\n\t\t\treturn 1;\n\t\tif(Seq >= (Bottom + NET_MAX_SEQUENCE))\n\t\t\treturn 1;\n\t}\n\telse\n\t{\n\t\tif(Seq <= Ack && Seq >= Bottom)\n\t\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n\nIOHANDLE CNetBase::ms_DataLogSent = 0;\nIOHANDLE CNetBase::ms_DataLogRecv = 0;\nCHuffman CNetBase::ms_Huffman;\n\n\nvoid CNetBase::OpenLog(IOHANDLE DataLogSent, IOHANDLE DataLogRecv)\n{\n\tif(DataLogSent)\n\t{\n\t\tms_DataLogSent = DataLogSent;\n\t\tdbg_msg(\"network\", \"logging sent packages\");\n\t}\n\telse\n\t\tdbg_msg(\"network\", \"failed to start logging sent packages\");\n\n\tif(DataLogRecv)\n\t{\n\t\tms_DataLogRecv = DataLogRecv;\n\t\tdbg_msg(\"network\", \"logging recv packages\");\n\t}\n\telse\n\t\tdbg_msg(\"network\", \"failed to start logging recv packages\");\n}\n\nvoid CNetBase::CloseLog()\n{\n\tif(ms_DataLogSent)\n\t{\n\t\tdbg_msg(\"network\", \"stopped logging sent packages\");\n\t\tio_close(ms_DataLogSent);\n\t\tms_DataLogSent = 0;\n\t}\n\n\tif(ms_DataLogRecv)\n\t{\n\t\tdbg_msg(\"network\", \"stopped logging recv packages\");\n\t\tio_close(ms_DataLogRecv);\n\t\tms_DataLogRecv = 0;\n\t}\n}\n\nint CNetBase::Compress(const void *pData, int DataSize, void *pOutput, int OutputSize)\n{\n\treturn ms_Huffman.Compress(pData, DataSize, pOutput, OutputSize);\n}\n\nint CNetBase::Decompress(const void *pData, int DataSize, void *pOutput, int OutputSize)\n{\n\treturn ms_Huffman.Decompress(pData, DataSize, pOutput, OutputSize);\n}\n\n\nstatic const unsigned gs_aFreqTable[256+1] = {\n\t1<<30,4545,2657,431,1950,919,444,482,2244,617,838,542,715,1814,304,240,754,212,647,186,\n\t283,131,146,166,543,164,167,136,179,859,363,113,157,154,204,108,137,180,202,176,\n\t872,404,168,134,151,111,113,109,120,126,129,100,41,20,16,22,18,18,17,19,\n\t16,37,13,21,362,166,99,78,95,88,81,70,83,284,91,187,77,68,52,68,\n\t59,66,61,638,71,157,50,46,69,43,11,24,13,19,10,12,12,20,14,9,\n\t20,20,10,10,15,15,12,12,7,19,15,14,13,18,35,19,17,14,8,5,\n\t15,17,9,15,14,18,8,10,2173,134,157,68,188,60,170,60,194,62,175,71,\n\t148,67,167,78,211,67,156,69,1674,90,174,53,147,89,181,51,174,63,163,80,\n\t167,94,128,122,223,153,218,77,200,110,190,73,174,69,145,66,277,143,141,60,\n\t136,53,180,57,142,57,158,61,166,112,152,92,26,22,21,28,20,26,30,21,\n\t32,27,20,17,23,21,30,22,22,21,27,25,17,27,23,18,39,26,15,21,\n\t12,18,18,27,20,18,15,19,11,17,33,12,18,15,19,18,16,26,17,18,\n\t9,10,25,22,22,17,20,16,6,16,15,20,14,18,24,335,1517};\n\nvoid CNetBase::Init()\n{\n\tms_Huffman.Init(gs_aFreqTable);\n}\n"
  },
  {
    "path": "src/engine/shared/network.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SHARED_NETWORK_H\n#define ENGINE_SHARED_NETWORK_H\n\n#include \"ringbuffer.h\"\n#include \"huffman.h\"\n\n/*\n\nCURRENT:\n\tpacket header: 3 bytes\n\t\tunsigned char flags_ack; // 4bit flags, 4bit ack\n\t\tunsigned char ack; // 8 bit ack\n\t\tunsigned char num_chunks; // 8 bit chunks\n\n\t\t(unsigned char padding[3])\t// 24 bit extra incase it's a connection less packet\n\t\t\t\t\t\t\t\t\t// this is to make sure that it's compatible with the\n\t\t\t\t\t\t\t\t\t// old protocol\n\n\tchunk header: 2-3 bytes\n\t\tunsigned char flags_size; // 2bit flags, 6 bit size\n\t\tunsigned char size_seq; // 6bit size, 2bit seq\n\t\t(unsigned char seq;) // 8bit seq, if vital flag is set\n*/\n\nenum\n{\n\tNETFLAG_ALLOWSTATELESS=1,\n\tNETSENDFLAG_VITAL=1,\n\tNETSENDFLAG_CONNLESS=2,\n\tNETSENDFLAG_FLUSH=4,\n\n\tNETSTATE_OFFLINE=0,\n\tNETSTATE_CONNECTING,\n\tNETSTATE_ONLINE,\n\n\tNETBANTYPE_SOFT=1,\n\tNETBANTYPE_DROP=2\n};\n\n\nenum\n{\n\tNET_VERSION = 2,\n\n\tNET_MAX_PACKETSIZE = 1400,\n\tNET_MAX_PAYLOAD = NET_MAX_PACKETSIZE-6,\n\tNET_MAX_CHUNKHEADERSIZE = 3,\n\tNET_PACKETHEADERSIZE = 3,\n\tNET_MAX_CLIENTS = 16,\n\tNET_MAX_CONSOLE_CLIENTS = 4,\n\tNET_MAX_SEQUENCE = 1<<10,\n\tNET_SEQUENCE_MASK = NET_MAX_SEQUENCE-1,\n\n\tNET_CONNSTATE_OFFLINE=0,\n\tNET_CONNSTATE_CONNECT=1,\n\tNET_CONNSTATE_PENDING=2,\n\tNET_CONNSTATE_ONLINE=3,\n\tNET_CONNSTATE_ERROR=4,\n\n\tNET_PACKETFLAG_CONTROL=1,\n\tNET_PACKETFLAG_CONNLESS=2,\n\tNET_PACKETFLAG_RESEND=4,\n\tNET_PACKETFLAG_COMPRESSION=8,\n\n\tNET_CHUNKFLAG_VITAL=1,\n\tNET_CHUNKFLAG_RESEND=2,\n\n\tNET_CTRLMSG_KEEPALIVE=0,\n\tNET_CTRLMSG_CONNECT=1,\n\tNET_CTRLMSG_CONNECTACCEPT=2,\n\tNET_CTRLMSG_ACCEPT=3,\n\tNET_CTRLMSG_CLOSE=4,\n\n\tNET_CONN_BUFFERSIZE=1024*32,\n\n\tNET_ENUM_TERMINATOR\n};\n\n\ntypedef int (*NETFUNC_DELCLIENT)(int ClientID, const char* pReason, void *pUser);\ntypedef int (*NETFUNC_NEWCLIENT)(int ClientID, void *pUser);\n\nstruct CNetChunk\n{\n\t// -1 means that it's a stateless packet\n\t// 0 on the client means the server\n\tint m_ClientID;\n\tNETADDR m_Address; // only used when client_id == -1\n\tint m_Flags;\n\tint m_DataSize;\n\tconst void *m_pData;\n};\n\nclass CNetChunkHeader\n{\npublic:\n\tint m_Flags;\n\tint m_Size;\n\tint m_Sequence;\n\n\tunsigned char *Pack(unsigned char *pData);\n\tunsigned char *Unpack(unsigned char *pData);\n};\n\nclass CNetChunkResend\n{\npublic:\n\tint m_Flags;\n\tint m_DataSize;\n\tunsigned char *m_pData;\n\n\tint m_Sequence;\n\tint64 m_LastSendTime;\n\tint64 m_FirstSendTime;\n};\n\nclass CNetPacketConstruct\n{\npublic:\n\tint m_Flags;\n\tint m_Ack;\n\tint m_NumChunks;\n\tint m_DataSize;\n\tunsigned char m_aChunkData[NET_MAX_PAYLOAD];\n};\n\n\nclass CNetConnection\n{\n\t// TODO: is this needed because this needs to be aware of\n\t// the ack sequencing number and is also responible for updating\n\t// that. this should be fixed.\n\tfriend class CNetRecvUnpacker;\nprivate:\n\tunsigned short m_Sequence;\n\tunsigned short m_Ack;\n\tunsigned m_State;\n\n\tint m_Token;\n\tint m_RemoteClosed;\n\tbool m_BlockCloseMsg;\n\n\tTStaticRingBuffer<CNetChunkResend, NET_CONN_BUFFERSIZE> m_Buffer;\n\n\tint64 m_LastUpdateTime;\n\tint64 m_LastRecvTime;\n\tint64 m_LastSendTime;\n\n\tchar m_ErrorString[256];\n\n\tCNetPacketConstruct m_Construct;\n\n\tNETADDR m_PeerAddr;\n\tNETSOCKET m_Socket;\n\tNETSTATS m_Stats;\n\n\t//\n\tvoid Reset();\n\tvoid ResetStats();\n\tvoid SetError(const char *pString);\n\tvoid AckChunks(int Ack);\n\n\tint QueueChunkEx(int Flags, int DataSize, const void *pData, int Sequence);\n\tvoid SendControl(int ControlMsg, const void *pExtra, int ExtraSize);\n\tvoid ResendChunk(CNetChunkResend *pResend);\n\tvoid Resend();\n\npublic:\n\tvoid Init(NETSOCKET Socket, bool BlockCloseMsg);\n\tint Connect(NETADDR *pAddr);\n\tvoid Disconnect(const char *pReason);\n\n\tint Update();\n\tint Flush();\n\n\tint Feed(CNetPacketConstruct *pPacket, NETADDR *pAddr);\n\tint QueueChunk(int Flags, int DataSize, const void *pData);\n\n\tconst char *ErrorString();\n\tvoid SignalResend();\n\tint State() const { return m_State; }\n\tconst NETADDR *PeerAddress() const { return &m_PeerAddr; }\n\n\tvoid ResetErrorString() { m_ErrorString[0] = 0; }\n\tconst char *ErrorString() const { return m_ErrorString; }\n\n\t// Needed for GotProblems in NetClient\n\tint64 LastRecvTime() const { return m_LastRecvTime; }\n\n\tint AckSequence() const { return m_Ack; }\n};\n\nclass CConsoleNetConnection\n{\nprivate:\n\tint m_State;\n\n\tNETADDR m_PeerAddr;\n\tNETSOCKET m_Socket;\n\n\tchar m_aBuffer[NET_MAX_PACKETSIZE];\n\tint m_BufferOffset;\n\n\tchar m_aErrorString[256];\n\n\tbool m_LineEndingDetected;\n\tchar m_aLineEnding[3];\n\npublic:\n\tvoid Init(NETSOCKET Socket, const NETADDR *pAddr);\n\tvoid Disconnect(const char *pReason);\n\n\tint State() const { return m_State; }\n\tconst NETADDR *PeerAddress() const { return &m_PeerAddr; }\n\tconst char *ErrorString() const { return m_aErrorString; }\n\n\tvoid Reset();\n\tint Update();\n\tint Send(const char *pLine);\n\tint Recv(char *pLine, int MaxLength);\n};\n\nclass CNetRecvUnpacker\n{\npublic:\n\tbool m_Valid;\n\n\tNETADDR m_Addr;\n\tCNetConnection *m_pConnection;\n\tint m_CurrentChunk;\n\tint m_ClientID;\n\tCNetPacketConstruct m_Data;\n\tunsigned char m_aBuffer[NET_MAX_PACKETSIZE];\n\n\tCNetRecvUnpacker() { Clear(); }\n\tvoid Clear();\n\tvoid Start(const NETADDR *pAddr, CNetConnection *pConnection, int ClientID);\n\tint FetchChunk(CNetChunk *pChunk);\n};\n\n// server side\nclass CNetServer\n{\n\tstruct CSlot\n\t{\n\tpublic:\n\t\tCNetConnection m_Connection;\n\t};\n\n\tNETSOCKET m_Socket;\n\tclass CNetBan *m_pNetBan;\n\tCSlot m_aSlots[NET_MAX_CLIENTS];\n\tint m_MaxClients;\n\tint m_MaxClientsPerIP;\n\n\tNETFUNC_NEWCLIENT m_pfnNewClient;\n\tNETFUNC_DELCLIENT m_pfnDelClient;\n\tvoid *m_UserPtr;\n\n\tCNetRecvUnpacker m_RecvUnpacker;\n\npublic:\n\tint SetCallbacks(NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_DELCLIENT pfnDelClient, void *pUser);\n\n\t//\n\tbool Open(NETADDR BindAddr, class CNetBan *pNetBan, int MaxClients, int MaxClientsPerIP, int Flags);\n\tint Close();\n\n\t//\n\tint Recv(CNetChunk *pChunk);\n\tint Send(CNetChunk *pChunk);\n\tint Update();\n\n\t//\n\tint Drop(int ClientID, const char *pReason);\n\n\t// status requests\n\tconst NETADDR *ClientAddr(int ClientID) const { return m_aSlots[ClientID].m_Connection.PeerAddress(); }\n\tNETSOCKET Socket() const { return m_Socket; }\n\tclass CNetBan *NetBan() const { return m_pNetBan; }\n\tint NetType() const { return m_Socket.type; }\n\tint MaxClients() const { return m_MaxClients; }\n\n\t//\n\tvoid SetMaxClientsPerIP(int Max);\n};\n\nclass CNetConsole\n{\n\tstruct CSlot\n\t{\n\t\tCConsoleNetConnection m_Connection;\n\t};\n\n\tNETSOCKET m_Socket;\n\tclass CNetBan *m_pNetBan;\n\tCSlot m_aSlots[NET_MAX_CONSOLE_CLIENTS];\n\n\tNETFUNC_NEWCLIENT m_pfnNewClient;\n\tNETFUNC_DELCLIENT m_pfnDelClient;\n\tvoid *m_UserPtr;\n\n\tCNetRecvUnpacker m_RecvUnpacker;\n\npublic:\n\tvoid SetCallbacks(NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_DELCLIENT pfnDelClient, void *pUser);\n\n\t//\n\tbool Open(NETADDR BindAddr, class CNetBan *pNetBan, int Flags);\n\tint Close();\n\n\t//\n\tint Recv(char *pLine, int MaxLength, int *pClientID = 0);\n\tint Send(int ClientID, const char *pLine);\n\tint Update();\n\n\t//\n\tint AcceptClient(NETSOCKET Socket, const NETADDR *pAddr);\n\tint Drop(int ClientID, const char *pReason);\n\n\t// status requests\n\tconst NETADDR *ClientAddr(int ClientID) const { return m_aSlots[ClientID].m_Connection.PeerAddress(); }\n\tclass CNetBan *NetBan() const { return m_pNetBan; }\n};\n\n\n\n// client side\nclass CNetClient\n{\n\tNETADDR m_ServerAddr;\n\tCNetConnection m_Connection;\n\tCNetRecvUnpacker m_RecvUnpacker;\n\tNETSOCKET m_Socket;\npublic:\n\t// openness\n\tbool Open(NETADDR BindAddr, int Flags);\n\tint Close();\n\n\t// connection state\n\tint Disconnect(const char *Reason);\n\tint Connect(NETADDR *Addr);\n\n\t// communication\n\tint Recv(CNetChunk *Chunk);\n\tint Send(CNetChunk *Chunk);\n\n\t// pumping\n\tint Update();\n\tint Flush();\n\n\tint ResetErrorString();\n\n\t// error and state\n\tint NetType() const { return m_Socket.type; }\n\tint State();\n\tint GotProblems();\n\tconst char *ErrorString();\n};\n\n\n\n// TODO: both, fix these. This feels like a junk class for stuff that doesn't fit anywere\nclass CNetBase\n{\n\tstatic IOHANDLE ms_DataLogSent;\n\tstatic IOHANDLE ms_DataLogRecv;\n\tstatic CHuffman ms_Huffman;\npublic:\n\tstatic void OpenLog(IOHANDLE DataLogSent, IOHANDLE DataLogRecv);\n\tstatic void CloseLog();\n\tstatic void Init();\n\tstatic int Compress(const void *pData, int DataSize, void *pOutput, int OutputSize);\n\tstatic int Decompress(const void *pData, int DataSize, void *pOutput, int OutputSize);\n\n\tstatic void SendControlMsg(NETSOCKET Socket, NETADDR *pAddr, int Ack, int ControlMsg, const void *pExtra, int ExtraSize);\n\tstatic void SendPacketConnless(NETSOCKET Socket, NETADDR *pAddr, const void *pData, int DataSize);\n\tstatic void SendPacket(NETSOCKET Socket, NETADDR *pAddr, CNetPacketConstruct *pPacket);\n\tstatic int UnpackPacket(unsigned char *pBuffer, int Size, CNetPacketConstruct *pPacket);\n\n\t// The backroom is ack-NET_MAX_SEQUENCE/2. Used for knowing if we acked a packet or not\n\tstatic int IsSeqInBackroom(int Seq, int Ack);\n};\n\n\n#endif\n"
  },
  {
    "path": "src/engine/shared/network_client.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n#include \"network.h\"\n\nbool CNetClient::Open(NETADDR BindAddr, int Flags)\n{\n\t// open socket\n\tNETSOCKET Socket;\n\tSocket = net_udp_create(BindAddr);\n\tif(!Socket.type)\n\t\treturn false;\n\n\t// clean it\n\tmem_zero(this, sizeof(*this));\n\n\t// init\n\tm_Socket = Socket;\n\tm_Connection.Init(m_Socket, false);\n\treturn true;\n}\n\nint CNetClient::Close()\n{\n\t// TODO: implement me\n\treturn 0;\n}\n\n\nint CNetClient::Disconnect(const char *pReason)\n{\n\t//dbg_msg(\"netclient\", \"disconnected. reason=\\\"%s\\\"\", pReason);\n\tm_Connection.Disconnect(pReason);\n\treturn 0;\n}\n\nint CNetClient::Update()\n{\n\tm_Connection.Update();\n\tif(m_Connection.State() == NET_CONNSTATE_ERROR)\n\t\tDisconnect(m_Connection.ErrorString());\n\treturn 0;\n}\n\nint CNetClient::Connect(NETADDR *pAddr)\n{\n\tm_Connection.Connect(pAddr);\n\treturn 0;\n}\n\nint CNetClient::ResetErrorString()\n{\n\tm_Connection.ResetErrorString();\n\treturn 0;\n}\n\nint CNetClient::Recv(CNetChunk *pChunk)\n{\n\twhile(1)\n\t{\n\t\t// check for a chunk\n\t\tif(m_RecvUnpacker.FetchChunk(pChunk))\n\t\t\treturn 1;\n\n\t\t// TODO: empty the recvinfo\n\t\tNETADDR Addr;\n\t\tint Bytes = net_udp_recv(m_Socket, &Addr, m_RecvUnpacker.m_aBuffer, NET_MAX_PACKETSIZE);\n\n\t\t// no more packets for now\n\t\tif(Bytes <= 0)\n\t\t\tbreak;\n\n\t\tif(CNetBase::UnpackPacket(m_RecvUnpacker.m_aBuffer, Bytes, &m_RecvUnpacker.m_Data) == 0)\n\t\t{\n\t\t\tif(m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_CONNLESS)\n\t\t\t{\n\t\t\t\tpChunk->m_Flags = NETSENDFLAG_CONNLESS;\n\t\t\t\tpChunk->m_ClientID = -1;\n\t\t\t\tpChunk->m_Address = Addr;\n\t\t\t\tpChunk->m_DataSize = m_RecvUnpacker.m_Data.m_DataSize;\n\t\t\t\tpChunk->m_pData = m_RecvUnpacker.m_Data.m_aChunkData;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(m_Connection.Feed(&m_RecvUnpacker.m_Data, &Addr))\n\t\t\t\t\tm_RecvUnpacker.Start(&Addr, &m_Connection, 0);\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n\nint CNetClient::Send(CNetChunk *pChunk)\n{\n\tif(pChunk->m_Flags&NETSENDFLAG_CONNLESS)\n\t{\n\t\tif(pChunk->m_DataSize >= NET_MAX_PAYLOAD)\n\t\t{\n\t\t\tdbg_msg(\"netserver\", \"packet payload too big. %d. dropping packet\", pChunk->m_DataSize);\n\t\t\treturn -1;\n\t\t}\n\n\t\t// send connectionless packet\n\t\tCNetBase::SendPacketConnless(m_Socket, &pChunk->m_Address, pChunk->m_pData, pChunk->m_DataSize);\n\t}\n\telse\n\t{\n\t\tif(pChunk->m_DataSize+NET_MAX_CHUNKHEADERSIZE >= NET_MAX_PAYLOAD)\n\t\t{\n\t\t\tdbg_msg(\"netclient\", \"chunk payload too big. %d. dropping chunk\", pChunk->m_DataSize);\n\t\t\treturn -1;\n\t\t}\n\n\t\tint Flags = 0;\n\t\tdbg_assert(pChunk->m_ClientID == 0, \"errornous client id\");\n\n\t\tif(pChunk->m_Flags&NETSENDFLAG_VITAL)\n\t\t\tFlags = NET_CHUNKFLAG_VITAL;\n\n\t\tm_Connection.QueueChunk(Flags, pChunk->m_DataSize, pChunk->m_pData);\n\n\t\tif(pChunk->m_Flags&NETSENDFLAG_FLUSH)\n\t\t\tm_Connection.Flush();\n\t}\n\treturn 0;\n}\n\nint CNetClient::State()\n{\n\tif(m_Connection.State() == NET_CONNSTATE_ONLINE)\n\t\treturn NETSTATE_ONLINE;\n\tif(m_Connection.State() == NET_CONNSTATE_OFFLINE)\n\t\treturn NETSTATE_OFFLINE;\n\treturn NETSTATE_CONNECTING;\n}\n\nint CNetClient::Flush()\n{\n\treturn m_Connection.Flush();\n}\n\nint CNetClient::GotProblems()\n{\n\tif(time_get() - m_Connection.LastRecvTime() > time_freq())\n\t\treturn 1;\n\treturn 0;\n}\n\nconst char *CNetClient::ErrorString()\n{\n\treturn m_Connection.ErrorString();\n}\n"
  },
  {
    "path": "src/engine/shared/network_conn.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n#include \"config.h\"\n#include \"network.h\"\n\nvoid CNetConnection::ResetStats()\n{\n\tmem_zero(&m_Stats, sizeof(m_Stats));\n}\n\nvoid CNetConnection::Reset()\n{\n\tm_Sequence = 0;\n\tm_Ack = 0;\n\tm_RemoteClosed = 0;\n\n\tm_State = NET_CONNSTATE_OFFLINE;\n\tm_LastSendTime = 0;\n\tm_LastRecvTime = 0;\n\tm_LastUpdateTime = 0;\n\tm_Token = -1;\n\tmem_zero(&m_PeerAddr, sizeof(m_PeerAddr));\n\n\tm_Buffer.Init();\n\n\tmem_zero(&m_Construct, sizeof(m_Construct));\n}\n\nconst char *CNetConnection::ErrorString()\n{\n\treturn m_ErrorString;\n}\n\nvoid CNetConnection::SetError(const char *pString)\n{\n\tstr_copy(m_ErrorString, pString, sizeof(m_ErrorString));\n}\n\nvoid CNetConnection::Init(NETSOCKET Socket, bool BlockCloseMsg)\n{\n\tReset();\n\tResetStats();\n\n\tm_Socket = Socket;\n\tm_BlockCloseMsg = BlockCloseMsg;\n\tmem_zero(m_ErrorString, sizeof(m_ErrorString));\n}\n\nvoid CNetConnection::AckChunks(int Ack)\n{\n\twhile(1)\n\t{\n\t\tCNetChunkResend *pResend = m_Buffer.First();\n\t\tif(!pResend)\n\t\t\tbreak;\n\n\t\tif(CNetBase::IsSeqInBackroom(pResend->m_Sequence, Ack))\n\t\t\tm_Buffer.PopFirst();\n\t\telse\n\t\t\tbreak;\n\t}\n}\n\nvoid CNetConnection::SignalResend()\n{\n\tm_Construct.m_Flags |= NET_PACKETFLAG_RESEND;\n}\n\nint CNetConnection::Flush()\n{\n\tint NumChunks = m_Construct.m_NumChunks;\n\tif(!NumChunks && !m_Construct.m_Flags)\n\t\treturn 0;\n\n\t// send of the packets\n\tm_Construct.m_Ack = m_Ack;\n\tCNetBase::SendPacket(m_Socket, &m_PeerAddr, &m_Construct);\n\n\t// update send times\n\tm_LastSendTime = time_get();\n\n\t// clear construct so we can start building a new package\n\tmem_zero(&m_Construct, sizeof(m_Construct));\n\treturn NumChunks;\n}\n\nint CNetConnection::QueueChunkEx(int Flags, int DataSize, const void *pData, int Sequence)\n{\n\tunsigned char *pChunkData;\n\n\t// check if we have space for it, if not, flush the connection\n\tif(m_Construct.m_DataSize + DataSize + NET_MAX_CHUNKHEADERSIZE > (int)sizeof(m_Construct.m_aChunkData))\n\t\tFlush();\n\n\t// pack all the data\n\tCNetChunkHeader Header;\n\tHeader.m_Flags = Flags;\n\tHeader.m_Size = DataSize;\n\tHeader.m_Sequence = Sequence;\n\tpChunkData = &m_Construct.m_aChunkData[m_Construct.m_DataSize];\n\tpChunkData = Header.Pack(pChunkData);\n\tmem_copy(pChunkData, pData, DataSize);\n\tpChunkData += DataSize;\n\n\t//\n\tm_Construct.m_NumChunks++;\n\tm_Construct.m_DataSize = (int)(pChunkData-m_Construct.m_aChunkData);\n\n\t// set packet flags aswell\n\n\tif(Flags&NET_CHUNKFLAG_VITAL && !(Flags&NET_CHUNKFLAG_RESEND))\n\t{\n\t\t// save packet if we need to resend\n\t\tCNetChunkResend *pResend = m_Buffer.Allocate(sizeof(CNetChunkResend)+DataSize);\n\t\tif(pResend)\n\t\t{\n\t\t\tpResend->m_Sequence = Sequence;\n\t\t\tpResend->m_Flags = Flags;\n\t\t\tpResend->m_DataSize = DataSize;\n\t\t\tpResend->m_pData = (unsigned char *)(pResend+1);\n\t\t\tpResend->m_FirstSendTime = time_get();\n\t\t\tpResend->m_LastSendTime = pResend->m_FirstSendTime;\n\t\t\tmem_copy(pResend->m_pData, pData, DataSize);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// out of buffer\n\t\t\tDisconnect(\"too weak connection (out of buffer)\");\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nint CNetConnection::QueueChunk(int Flags, int DataSize, const void *pData)\n{\n\tif(Flags&NET_CHUNKFLAG_VITAL)\n\t\tm_Sequence = (m_Sequence+1)%NET_MAX_SEQUENCE;\n\treturn QueueChunkEx(Flags, DataSize, pData, m_Sequence);\n}\n\nvoid CNetConnection::SendControl(int ControlMsg, const void *pExtra, int ExtraSize)\n{\n\t// send the control message\n\tm_LastSendTime = time_get();\n\tCNetBase::SendControlMsg(m_Socket, &m_PeerAddr, m_Ack, ControlMsg, pExtra, ExtraSize);\n}\n\nvoid CNetConnection::ResendChunk(CNetChunkResend *pResend)\n{\n\tQueueChunkEx(pResend->m_Flags|NET_CHUNKFLAG_RESEND, pResend->m_DataSize, pResend->m_pData, pResend->m_Sequence);\n\tpResend->m_LastSendTime = time_get();\n}\n\nvoid CNetConnection::Resend()\n{\n\tfor(CNetChunkResend *pResend = m_Buffer.First(); pResend; pResend = m_Buffer.Next(pResend))\n\t\tResendChunk(pResend);\n}\n\nint CNetConnection::Connect(NETADDR *pAddr)\n{\n\tif(State() != NET_CONNSTATE_OFFLINE)\n\t\treturn -1;\n\n\t// init connection\n\tReset();\n\tm_PeerAddr = *pAddr;\n\tmem_zero(m_ErrorString, sizeof(m_ErrorString));\n\tm_State = NET_CONNSTATE_CONNECT;\n\tSendControl(NET_CTRLMSG_CONNECT, 0, 0);\n\treturn 0;\n}\n\nvoid CNetConnection::Disconnect(const char *pReason)\n{\n\tif(State() == NET_CONNSTATE_OFFLINE)\n\t\treturn;\n\n\tif(m_RemoteClosed == 0)\n\t{\n\t\tif(pReason)\n\t\t\tSendControl(NET_CTRLMSG_CLOSE, pReason, str_length(pReason)+1);\n\t\telse\n\t\t\tSendControl(NET_CTRLMSG_CLOSE, 0, 0);\n\n\t\tm_ErrorString[0] = 0;\n\t\tif(pReason)\n\t\t\tstr_copy(m_ErrorString, pReason, sizeof(m_ErrorString));\n\t}\n\n\tReset();\n}\n\nint CNetConnection::Feed(CNetPacketConstruct *pPacket, NETADDR *pAddr)\n{\n\tint64 Now = time_get();\n\n\t// check if resend is requested\n\tif(pPacket->m_Flags&NET_PACKETFLAG_RESEND)\n\t\tResend();\n\n\t//\n\tif(pPacket->m_Flags&NET_PACKETFLAG_CONTROL)\n\t{\n\t\tint CtrlMsg = pPacket->m_aChunkData[0];\n\n\t\tif(CtrlMsg == NET_CTRLMSG_CLOSE)\n\t\t{\n\t\t\tif(net_addr_comp(&m_PeerAddr, pAddr) == 0)\n\t\t\t{\n\t\t\t\tm_State = NET_CONNSTATE_ERROR;\n\t\t\t\tm_RemoteClosed = 1;\n\n\t\t\t\tchar Str[128] = {0};\n\t\t\t\tif(pPacket->m_DataSize > 1)\n\t\t\t\t{\n\t\t\t\t\t// make sure to sanitize the error string form the other party\n\t\t\t\t\tif(pPacket->m_DataSize < 128)\n\t\t\t\t\t\tstr_copy(Str, (char *)&pPacket->m_aChunkData[1], pPacket->m_DataSize);\n\t\t\t\t\telse\n\t\t\t\t\t\tstr_copy(Str, (char *)&pPacket->m_aChunkData[1], sizeof(Str));\n\t\t\t\t\tstr_sanitize_strong(Str);\n\t\t\t\t}\n\n\t\t\t\tif(!m_BlockCloseMsg)\n\t\t\t\t{\n\t\t\t\t\t// set the error string\n\t\t\t\t\tSetError(Str);\n\t\t\t\t}\n\n\t\t\t\tif(g_Config.m_Debug)\n\t\t\t\t\tdbg_msg(\"conn\", \"closed reason='%s'\", Str);\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(State() == NET_CONNSTATE_OFFLINE)\n\t\t\t{\n\t\t\t\tif(CtrlMsg == NET_CTRLMSG_CONNECT)\n\t\t\t\t{\n\t\t\t\t\t// send response and init connection\n\t\t\t\t\tReset();\n\t\t\t\t\tm_State = NET_CONNSTATE_PENDING;\n\t\t\t\t\tm_PeerAddr = *pAddr;\n\t\t\t\t\tmem_zero(m_ErrorString, sizeof(m_ErrorString));\n\t\t\t\t\tm_LastSendTime = Now;\n\t\t\t\t\tm_LastRecvTime = Now;\n\t\t\t\t\tm_LastUpdateTime = Now;\n\t\t\t\t\tSendControl(NET_CTRLMSG_CONNECTACCEPT, 0, 0);\n\t\t\t\t\tif(g_Config.m_Debug)\n\t\t\t\t\t\tdbg_msg(\"connection\", \"got connection, sending connect+accept\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(State() == NET_CONNSTATE_CONNECT)\n\t\t\t{\n\t\t\t\t// connection made\n\t\t\t\tif(CtrlMsg == NET_CTRLMSG_CONNECTACCEPT)\n\t\t\t\t{\n\t\t\t\t\tm_LastRecvTime = Now;\n\t\t\t\t\tSendControl(NET_CTRLMSG_ACCEPT, 0, 0);\n\t\t\t\t\tm_State = NET_CONNSTATE_ONLINE;\n\t\t\t\t\tif(g_Config.m_Debug)\n\t\t\t\t\t\tdbg_msg(\"connection\", \"got connect+accept, sending accept. connection online\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(State() == NET_CONNSTATE_PENDING)\n\t\t{\n\t\t\tm_LastRecvTime = Now;\n\t\t\tm_State = NET_CONNSTATE_ONLINE;\n\t\t\tif(g_Config.m_Debug)\n\t\t\t\tdbg_msg(\"connection\", \"connecting online\");\n\t\t}\n\t}\n\n\tif(State() == NET_CONNSTATE_ONLINE)\n\t{\n\t\tm_LastRecvTime = Now;\n\t\tAckChunks(pPacket->m_Ack);\n\t}\n\n\treturn 1;\n}\n\nint CNetConnection::Update()\n{\n\tint64 Now = time_get();\n\n\tif(State() == NET_CONNSTATE_OFFLINE || State() == NET_CONNSTATE_ERROR)\n\t\treturn 0;\n\n\t// check for timeout\n\tif(State() != NET_CONNSTATE_OFFLINE &&\n\t\tState() != NET_CONNSTATE_CONNECT &&\n\t\t(Now-m_LastRecvTime) > time_freq()*10)\n\t{\n\t\tm_State = NET_CONNSTATE_ERROR;\n\t\tSetError(\"Timeout\");\n\t}\n\n\t// fix resends\n\tif(m_Buffer.First())\n\t{\n\t\tCNetChunkResend *pResend = m_Buffer.First();\n\n\t\t// check if we have some really old stuff laying around and abort if not acked\n\t\tif(Now-pResend->m_FirstSendTime > time_freq()*10)\n\t\t{\n\t\t\tm_State = NET_CONNSTATE_ERROR;\n\t\t\tSetError(\"Too weak connection (not acked for 10 seconds)\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// resend packet if we havn't got it acked in 1 second\n\t\t\tif(Now-pResend->m_LastSendTime > time_freq())\n\t\t\t\tResendChunk(pResend);\n\t\t}\n\t}\n\n\t// send keep alives if nothing has happend for 250ms\n\tif(State() == NET_CONNSTATE_ONLINE)\n\t{\n\t\tif(time_get()-m_LastSendTime > time_freq()/2) // flush connection after 500ms if needed\n\t\t{\n\t\t\tint NumFlushedChunks = Flush();\n\t\t\tif(NumFlushedChunks && g_Config.m_Debug)\n\t\t\t\tdbg_msg(\"connection\", \"flushed connection due to timeout. %d chunks.\", NumFlushedChunks);\n\t\t}\n\n\t\tif(time_get()-m_LastSendTime > time_freq())\n\t\t\tSendControl(NET_CTRLMSG_KEEPALIVE, 0, 0);\n\t}\n\telse if(State() == NET_CONNSTATE_CONNECT)\n\t{\n\t\tif(time_get()-m_LastSendTime > time_freq()/2) // send a new connect every 500ms\n\t\t\tSendControl(NET_CTRLMSG_CONNECT, 0, 0);\n\t}\n\telse if(State() == NET_CONNSTATE_PENDING)\n\t{\n\t\tif(time_get()-m_LastSendTime > time_freq()/2) // send a new connect/accept every 500ms\n\t\t\tSendControl(NET_CTRLMSG_CONNECTACCEPT, 0, 0);\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "src/engine/shared/network_console.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n\n#include <engine/console.h>\n\n#include \"netban.h\"\n#include \"network.h\"\n\n\nbool CNetConsole::Open(NETADDR BindAddr, CNetBan *pNetBan, int Flags)\n{\n\t// zero out the whole structure\n\tmem_zero(this, sizeof(*this));\n\tm_Socket.type = NETTYPE_INVALID;\n\tm_Socket.ipv4sock = -1;\n\tm_Socket.ipv6sock = -1;\n\tm_pNetBan = pNetBan;\n\n\t// open socket\n\tm_Socket = net_tcp_create(BindAddr);\n\tif(!m_Socket.type)\n\t\treturn false;\n\tif(net_tcp_listen(m_Socket, NET_MAX_CONSOLE_CLIENTS))\n\t\treturn false;\n\tnet_set_non_blocking(m_Socket);\n\n\tfor(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++)\n\t\tm_aSlots[i].m_Connection.Reset();\n\n\treturn true;\n}\n\nvoid CNetConsole::SetCallbacks(NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_DELCLIENT pfnDelClient, void *pUser)\n{\n\tm_pfnNewClient = pfnNewClient;\n\tm_pfnDelClient = pfnDelClient;\n\tm_UserPtr = pUser;\n}\n\nint CNetConsole::Close()\n{\n\tfor(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++)\n\t\tm_aSlots[i].m_Connection.Disconnect(\"closing console\");\n\n\tnet_tcp_close(m_Socket);\n\n\treturn 0;\n}\n\nint CNetConsole::Drop(int ClientID, const char *pReason)\n{\n\tif(m_pfnDelClient)\n\t\tm_pfnDelClient(ClientID, pReason, m_UserPtr);\n\n\tm_aSlots[ClientID].m_Connection.Disconnect(pReason);\n\n\treturn 0;\n}\n\nint CNetConsole::AcceptClient(NETSOCKET Socket, const NETADDR *pAddr)\n{\n\tchar aError[256] = { 0 };\n\tint FreeSlot = -1;\n\n\t// look for free slot or multiple client\n\tfor(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++)\n\t{\n\t\tif(FreeSlot == -1 && m_aSlots[i].m_Connection.State() == NET_CONNSTATE_OFFLINE)\n\t\t\tFreeSlot = i;\n\t\tif(m_aSlots[i].m_Connection.State() != NET_CONNSTATE_OFFLINE)\n\t\t{\n\t\t\tif(net_addr_comp(pAddr, m_aSlots[i].m_Connection.PeerAddress()) == 0)\n\t\t\t{\n\t\t\t\tstr_copy(aError, \"only one client per IP allowed\", sizeof(aError));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t// accept client\n\tif(!aError[0] && FreeSlot != -1)\n\t{\n\t\tm_aSlots[FreeSlot].m_Connection.Init(Socket, pAddr);\n\t\tif(m_pfnNewClient)\n\t\t\tm_pfnNewClient(FreeSlot, m_UserPtr);\n\t\treturn 0;\n\t}\n\n\t// reject client\n\tif(!aError[0])\n\t\tstr_copy(aError, \"no free slot available\", sizeof(aError));\n\n\tnet_tcp_send(Socket, aError, str_length(aError));\n\tnet_tcp_close(Socket);\n\n\treturn -1;\n}\n\nint CNetConsole::Update()\n{\n\tNETSOCKET Socket;\n\tNETADDR Addr;\n\n\tif(net_tcp_accept(m_Socket, &Socket, &Addr) > 0)\n\t{\n\t\t// check if we just should drop the packet\n\t\tchar aBuf[128];\n\t\tif(NetBan() && NetBan()->IsBanned(&Addr, aBuf, sizeof(aBuf)))\n\t\t{\n\t\t\t// banned, reply with a message and drop\n\t\t\tnet_tcp_send(Socket, aBuf, str_length(aBuf));\n\t\t\tnet_tcp_close(Socket);\n\t\t}\n\t\telse\n\t\t\tAcceptClient(Socket, &Addr);\n\t}\n\n\tfor(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++)\n\t{\n\t\tif(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_ONLINE)\n\t\t\tm_aSlots[i].m_Connection.Update();\n\t\tif(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_ERROR)\n\t\t\tDrop(i, m_aSlots[i].m_Connection.ErrorString());\n\t}\n\n\treturn 0;\n}\n\nint CNetConsole::Recv(char *pLine, int MaxLength, int *pClientID)\n{\n\tfor(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++)\n\t{\n\t\tif(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_ONLINE && m_aSlots[i].m_Connection.Recv(pLine, MaxLength))\n\t\t{\n\t\t\tif(pClientID)\n\t\t\t\t*pClientID = i;\n\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nint CNetConsole::Send(int ClientID, const char *pLine)\n{\n\tif(m_aSlots[ClientID].m_Connection.State() == NET_CONNSTATE_ONLINE)\n\t\treturn m_aSlots[ClientID].m_Connection.Send(pLine);\n\telse\n\t\treturn -1;\n}\n"
  },
  {
    "path": "src/engine/shared/network_console_conn.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n#include \"network.h\"\n\nvoid CConsoleNetConnection::Reset()\n{\n\tm_State = NET_CONNSTATE_OFFLINE;\n\tmem_zero(&m_PeerAddr, sizeof(m_PeerAddr));\n\tm_aErrorString[0] = 0;\n\n\tm_Socket.type = NETTYPE_INVALID;\n\tm_Socket.ipv4sock = -1;\n\tm_Socket.ipv6sock = -1;\n\tm_aBuffer[0] = 0;\n\tm_BufferOffset = 0;\n\n\tm_LineEndingDetected = false;\n\t#if defined(CONF_FAMILY_WINDOWS)\n\t\tm_aLineEnding[0] = '\\r';\n\t\tm_aLineEnding[1] = '\\n';\n\t\tm_aLineEnding[2] = 0;\n\t#else\n\t\tm_aLineEnding[0] = '\\n';\n\t\tm_aLineEnding[1] = 0;\n\t\tm_aLineEnding[2] = 0;\n\t#endif\n}\n\nvoid CConsoleNetConnection::Init(NETSOCKET Socket, const NETADDR *pAddr)\n{\n\tReset();\n\n\tm_Socket = Socket;\n\tnet_set_non_blocking(m_Socket);\n\n\tm_PeerAddr = *pAddr;\n\tm_State = NET_CONNSTATE_ONLINE;\n}\n\nvoid CConsoleNetConnection::Disconnect(const char *pReason)\n{\n\tif(State() == NET_CONNSTATE_OFFLINE)\n\t\treturn;\n\n\tif(pReason && pReason[0])\n\t\tSend(pReason);\n\n\tnet_tcp_close(m_Socket);\n\n\tReset();\n}\n\nint CConsoleNetConnection::Update()\n{\n\tif(State() == NET_CONNSTATE_ONLINE)\n\t{\n\t\tif((int)(sizeof(m_aBuffer)) <= m_BufferOffset)\n\t\t{\n\t\t\tm_State = NET_CONNSTATE_ERROR;\n\t\t\tstr_copy(m_aErrorString, \"too weak connection (out of buffer)\", sizeof(m_aErrorString));\n\t\t\treturn -1;\n\t\t}\n\n\t\tint Bytes = net_tcp_recv(m_Socket, m_aBuffer+m_BufferOffset, (int)(sizeof(m_aBuffer))-m_BufferOffset);\n\n\t\tif(Bytes > 0)\n\t\t{\n\t\t\tm_BufferOffset += Bytes;\n\t\t}\n\t\telse if(Bytes < 0)\n\t\t{\n\t\t\tif(net_would_block()) // no data received\n\t\t\t\treturn 0;\n\n\t\t\tm_State = NET_CONNSTATE_ERROR; // error\n\t\t\tstr_copy(m_aErrorString, \"connection failure\", sizeof(m_aErrorString));\n\t\t\treturn -1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_State = NET_CONNSTATE_ERROR;\n\t\t\tstr_copy(m_aErrorString, \"remote end closed the connection\", sizeof(m_aErrorString));\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nint CConsoleNetConnection::Recv(char *pLine, int MaxLength)\n{\n\tif(State() == NET_CONNSTATE_ONLINE)\n\t{\n\t\tif(m_BufferOffset)\n\t\t{\n\t\t\t// find message start\n\t\t\tint StartOffset = 0;\n\t\t\twhile(m_aBuffer[StartOffset] == '\\r' || m_aBuffer[StartOffset] == '\\n')\n\t\t\t{\n\t\t\t\t// detect clients line ending format\n\t\t\t\tif(!m_LineEndingDetected)\n\t\t\t\t{\n\t\t\t\t\tm_aLineEnding[0] = m_aBuffer[StartOffset];\n\t\t\t\t\tif(StartOffset+1 < m_BufferOffset && (m_aBuffer[StartOffset+1] == '\\r' || m_aBuffer[StartOffset+1] == '\\n') &&\n\t\t\t\t\t\tm_aBuffer[StartOffset] != m_aBuffer[StartOffset+1])\n\t\t\t\t\t\tm_aLineEnding[1] = m_aBuffer[StartOffset+1];\n\t\t\t\t\tm_LineEndingDetected = true;\n\t\t\t\t}\n\n\t\t\t\tif(++StartOffset >= m_BufferOffset)\n\t\t\t\t{\n\t\t\t\t\tm_BufferOffset = 0;\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// find message end\n\t\t\tint EndOffset = StartOffset;\n\t\t\twhile(m_aBuffer[EndOffset] != '\\r' && m_aBuffer[EndOffset] != '\\n')\n\t\t\t{\n\t\t\t\tif(++EndOffset >= m_BufferOffset)\n\t\t\t\t{\n\t\t\t\t\tif(StartOffset > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tmem_move(m_aBuffer, m_aBuffer+StartOffset, m_BufferOffset-StartOffset);\n\t\t\t\t\t\tm_BufferOffset -= StartOffset;\n\t\t\t\t\t}\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// extract message and update buffer\n\t\t\tif(MaxLength-1 < EndOffset-StartOffset)\n\t\t\t{\n\t\t\t\tif(StartOffset > 0)\n\t\t\t\t{\n\t\t\t\t\tmem_move(m_aBuffer, m_aBuffer+StartOffset, m_BufferOffset-StartOffset);\n\t\t\t\t\tm_BufferOffset -= StartOffset;\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tmem_copy(pLine, m_aBuffer+StartOffset, EndOffset-StartOffset);\n\t\t\tpLine[EndOffset-StartOffset] = 0;\n\t\t\tstr_sanitize_cc(pLine);\n\t\t\tmem_move(m_aBuffer, m_aBuffer+EndOffset, m_BufferOffset-EndOffset);\n\t\t\tm_BufferOffset -= EndOffset;\n\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nint CConsoleNetConnection::Send(const char *pLine)\n{\n\tif(State() != NET_CONNSTATE_ONLINE)\n\t\treturn -1;\n\n\tchar aBuf[1024];\n\tstr_copy(aBuf, pLine, (int)(sizeof(aBuf))-2);\n\tint Length = str_length(aBuf);\n\taBuf[Length] = m_aLineEnding[0];\n\taBuf[Length+1] = m_aLineEnding[1];\n\taBuf[Length+2] = m_aLineEnding[2];\n\tLength += 3;\n\tconst char *pData = aBuf;\n\n\twhile(true)\n\t{\n\t\tint Send = net_tcp_send(m_Socket, pData, Length);\n\t\tif(Send < 0)\n\t\t{\n\t\t\tm_State = NET_CONNSTATE_ERROR;\n\t\t\tstr_copy(m_aErrorString, \"failed to send packet\", sizeof(m_aErrorString));\n\t\t\treturn -1;\n\t\t}\n\n\t\tif(Send >= Length)\n\t\t\tbreak;\n\n\t\tpData += Send;\n\t\tLength -= Send;\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "src/engine/shared/network_server.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n\n#include <engine/console.h>\n\n#include \"netban.h\"\n#include \"network.h\"\n\n\nbool CNetServer::Open(NETADDR BindAddr, CNetBan *pNetBan, int MaxClients, int MaxClientsPerIP, int Flags)\n{\n\t// zero out the whole structure\n\tmem_zero(this, sizeof(*this));\n\n\t// open socket\n\tm_Socket = net_udp_create(BindAddr);\n\tif(!m_Socket.type)\n\t\treturn false;\n\n\tm_pNetBan = pNetBan;\n\n\t// clamp clients\n\tm_MaxClients = MaxClients;\n\tif(m_MaxClients > NET_MAX_CLIENTS)\n\t\tm_MaxClients = NET_MAX_CLIENTS;\n\tif(m_MaxClients < 1)\n\t\tm_MaxClients = 1;\n\n\tm_MaxClientsPerIP = MaxClientsPerIP;\n\n\tfor(int i = 0; i < NET_MAX_CLIENTS; i++)\n\t\tm_aSlots[i].m_Connection.Init(m_Socket, true);\n\n\treturn true;\n}\n\nint CNetServer::SetCallbacks(NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_DELCLIENT pfnDelClient, void *pUser)\n{\n\tm_pfnNewClient = pfnNewClient;\n\tm_pfnDelClient = pfnDelClient;\n\tm_UserPtr = pUser;\n\treturn 0;\n}\n\nint CNetServer::Close()\n{\n\t// TODO: implement me\n\treturn 0;\n}\n\nint CNetServer::Drop(int ClientID, const char *pReason)\n{\n\t// TODO: insert lots of checks here\n\t/*NETADDR Addr = ClientAddr(ClientID);\n\n\tdbg_msg(\"net_server\", \"client dropped. cid=%d ip=%d.%d.%d.%d reason=\\\"%s\\\"\",\n\t\tClientID,\n\t\tAddr.ip[0], Addr.ip[1], Addr.ip[2], Addr.ip[3],\n\t\tpReason\n\t\t);*/\n\tif(m_pfnDelClient)\n\t\tm_pfnDelClient(ClientID, pReason, m_UserPtr);\n\n\tm_aSlots[ClientID].m_Connection.Disconnect(pReason);\n\n\treturn 0;\n}\n\nint CNetServer::Update()\n{\n\tfor(int i = 0; i < MaxClients(); i++)\n\t{\n\t\tm_aSlots[i].m_Connection.Update();\n\t\tif(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_ERROR)\n\t\t\tDrop(i, m_aSlots[i].m_Connection.ErrorString());\n\t}\n\n\treturn 0;\n}\n\n/*\n\tTODO: chopp up this function into smaller working parts\n*/\nint CNetServer::Recv(CNetChunk *pChunk)\n{\n\twhile(1)\n\t{\n\t\tNETADDR Addr;\n\n\t\t// check for a chunk\n\t\tif(m_RecvUnpacker.FetchChunk(pChunk))\n\t\t\treturn 1;\n\n\t\t// TODO: empty the recvinfo\n\t\tint Bytes = net_udp_recv(m_Socket, &Addr, m_RecvUnpacker.m_aBuffer, NET_MAX_PACKETSIZE);\n\n\t\t// no more packets for now\n\t\tif(Bytes <= 0)\n\t\t\tbreak;\n\n\t\tif(CNetBase::UnpackPacket(m_RecvUnpacker.m_aBuffer, Bytes, &m_RecvUnpacker.m_Data) == 0)\n\t\t{\n\t\t\t// check if we just should drop the packet\n\t\t\tchar aBuf[128];\n\t\t\tif(NetBan() && NetBan()->IsBanned(&Addr, aBuf, sizeof(aBuf)))\n\t\t\t{\n\t\t\t\t// banned, reply with a message\n\t\t\t\tCNetBase::SendControlMsg(m_Socket, &Addr, 0, NET_CTRLMSG_CLOSE, aBuf, str_length(aBuf)+1);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif(m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_CONNLESS)\n\t\t\t{\n\t\t\t\tpChunk->m_Flags = NETSENDFLAG_CONNLESS;\n\t\t\t\tpChunk->m_ClientID = -1;\n\t\t\t\tpChunk->m_Address = Addr;\n\t\t\t\tpChunk->m_DataSize = m_RecvUnpacker.m_Data.m_DataSize;\n\t\t\t\tpChunk->m_pData = m_RecvUnpacker.m_Data.m_aChunkData;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// TODO: check size here\n\t\t\t\tif(m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_CONTROL && m_RecvUnpacker.m_Data.m_aChunkData[0] == NET_CTRLMSG_CONNECT)\n\t\t\t\t{\n\t\t\t\t\tbool Found = false;\n\n\t\t\t\t\t// check if we already got this client\n\t\t\t\t\tfor(int i = 0; i < MaxClients(); i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(m_aSlots[i].m_Connection.State() != NET_CONNSTATE_OFFLINE &&\n\t\t\t\t\t\t\tnet_addr_comp(m_aSlots[i].m_Connection.PeerAddress(), &Addr) == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tFound = true; // silent ignore.. we got this client already\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// client that wants to connect\n\t\t\t\t\tif(!Found)\n\t\t\t\t\t{\n\t\t\t\t\t\t// only allow a specific number of players with the same ip\n\t\t\t\t\t\tNETADDR ThisAddr = Addr, OtherAddr;\n\t\t\t\t\t\tint FoundAddr = 1;\n\t\t\t\t\t\tThisAddr.port = 0;\n\t\t\t\t\t\tfor(int i = 0; i < MaxClients(); ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_OFFLINE)\n\t\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\t\tOtherAddr = *m_aSlots[i].m_Connection.PeerAddress();\n\t\t\t\t\t\t\tOtherAddr.port = 0;\n\t\t\t\t\t\t\tif(!net_addr_comp(&ThisAddr, &OtherAddr))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif(FoundAddr++ >= m_MaxClientsPerIP)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tchar aBuf[128];\n\t\t\t\t\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"Only %d players with the same IP are allowed\", m_MaxClientsPerIP);\n\t\t\t\t\t\t\t\t\tCNetBase::SendControlMsg(m_Socket, &Addr, 0, NET_CTRLMSG_CLOSE, aBuf, sizeof(aBuf));\n\t\t\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor(int i = 0; i < MaxClients(); i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_OFFLINE)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tFound = true;\n\t\t\t\t\t\t\t\tm_aSlots[i].m_Connection.Feed(&m_RecvUnpacker.m_Data, &Addr);\n\t\t\t\t\t\t\t\tif(m_pfnNewClient)\n\t\t\t\t\t\t\t\t\tm_pfnNewClient(i, m_UserPtr);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif(!Found)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst char FullMsg[] = \"This server is full\";\n\t\t\t\t\t\t\tCNetBase::SendControlMsg(m_Socket, &Addr, 0, NET_CTRLMSG_CLOSE, FullMsg, sizeof(FullMsg));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// normal packet, find matching slot\n\t\t\t\t\tfor(int i = 0; i < MaxClients(); i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(net_addr_comp(m_aSlots[i].m_Connection.PeerAddress(), &Addr) == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(m_aSlots[i].m_Connection.Feed(&m_RecvUnpacker.m_Data, &Addr))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif(m_RecvUnpacker.m_Data.m_DataSize)\n\t\t\t\t\t\t\t\t\tm_RecvUnpacker.Start(&Addr, &m_aSlots[i].m_Connection, i);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n\nint CNetServer::Send(CNetChunk *pChunk)\n{\n\tif(pChunk->m_Flags&NETSENDFLAG_CONNLESS)\n\t{\n\t\tif(pChunk->m_DataSize >= NET_MAX_PAYLOAD)\n\t\t{\n\t\t\tdbg_msg(\"netserver\", \"packet payload too big. %d. dropping packet\", pChunk->m_DataSize);\n\t\t\treturn -1;\n\t\t}\n\n\t\t// send connectionless packet\n\t\tCNetBase::SendPacketConnless(m_Socket, &pChunk->m_Address, pChunk->m_pData, pChunk->m_DataSize);\n\t}\n\telse\n\t{\n\t\tif(pChunk->m_DataSize+NET_MAX_CHUNKHEADERSIZE >= NET_MAX_PAYLOAD)\n\t\t{\n\t\t\tdbg_msg(\"netclient\", \"chunk payload too big. %d. dropping chunk\", pChunk->m_DataSize);\n\t\t\treturn -1;\n\t\t}\n\n\t\tint Flags = 0;\n\t\tdbg_assert(pChunk->m_ClientID >= 0, \"errornous client id\");\n\t\tdbg_assert(pChunk->m_ClientID < MaxClients(), \"errornous client id\");\n\n\t\tif(pChunk->m_Flags&NETSENDFLAG_VITAL)\n\t\t\tFlags = NET_CHUNKFLAG_VITAL;\n\n\t\tif(m_aSlots[pChunk->m_ClientID].m_Connection.QueueChunk(Flags, pChunk->m_DataSize, pChunk->m_pData) == 0)\n\t\t{\n\t\t\tif(pChunk->m_Flags&NETSENDFLAG_FLUSH)\n\t\t\t\tm_aSlots[pChunk->m_ClientID].m_Connection.Flush();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tDrop(pChunk->m_ClientID, \"Error sending data\");\n\t\t}\n\t}\n\treturn 0;\n}\n\nvoid CNetServer::SetMaxClientsPerIP(int Max)\n{\n\t// clamp\n\tif(Max < 1)\n\t\tMax = 1;\n\telse if(Max > NET_MAX_CLIENTS)\n\t\tMax = NET_MAX_CLIENTS;\n\n\tm_MaxClientsPerIP = Max;\n}\n"
  },
  {
    "path": "src/engine/shared/packer.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n\n#include \"packer.h\"\n#include \"compression.h\"\n#include \"config.h\"\n\nvoid CPacker::Reset()\n{\n\tm_Error = 0;\n\tm_pCurrent = m_aBuffer;\n\tm_pEnd = m_pCurrent + PACKER_BUFFER_SIZE;\n}\n\nvoid CPacker::AddInt(int i)\n{\n\tif(m_Error)\n\t\treturn;\n\n\t// make sure that we have space enough\n\tif(m_pEnd - m_pCurrent < 6)\n\t{\n\t\tdbg_break();\n\t\tm_Error = 1;\n\t}\n\telse\n\t\tm_pCurrent = CVariableInt::Pack(m_pCurrent, i);\n}\n\nvoid CPacker::AddString(const char *pStr, int Limit)\n{\n\tif(m_Error)\n\t\treturn;\n\n\t//\n\tif(Limit > 0)\n\t{\n\t\twhile(*pStr && Limit != 0)\n\t\t{\n\t\t\t*m_pCurrent++ = *pStr++;\n\t\t\tLimit--;\n\n\t\t\tif(m_pCurrent >= m_pEnd)\n\t\t\t{\n\t\t\t\tm_Error = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t*m_pCurrent++ = 0;\n\t}\n\telse\n\t{\n\t\twhile(*pStr)\n\t\t{\n\t\t\t*m_pCurrent++ = *pStr++;\n\n\t\t\tif(m_pCurrent >= m_pEnd)\n\t\t\t{\n\t\t\t\tm_Error = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t*m_pCurrent++ = 0;\n\t}\n}\n\nvoid CPacker::AddRaw(const void *pData, int Size)\n{\n\tif(m_Error)\n\t\treturn;\n\n\tif(m_pCurrent+Size >= m_pEnd)\n\t{\n\t\tm_Error = 1;\n\t\treturn;\n\t}\n\n\tconst unsigned char *pSrc = (const unsigned char *)pData;\n\twhile(Size)\n\t{\n\t\t*m_pCurrent++ = *pSrc++;\n\t\tSize--;\n\t}\n}\n\n\nvoid CUnpacker::Reset(const void *pData, int Size)\n{\n\tm_Error = 0;\n\tm_pStart = (const unsigned char *)pData;\n\tm_pEnd = m_pStart + Size;\n\tm_pCurrent = m_pStart;\n}\n\nint CUnpacker::GetInt()\n{\n\tif(m_Error)\n\t\treturn 0;\n\n\tif(m_pCurrent >= m_pEnd)\n\t{\n\t\tm_Error = 1;\n\t\treturn 0;\n\t}\n\n\tint i;\n\tm_pCurrent = CVariableInt::Unpack(m_pCurrent, &i);\n\tif(m_pCurrent > m_pEnd)\n\t{\n\t\tm_Error = 1;\n\t\treturn 0;\n\t}\n\treturn i;\n}\n\nconst char *CUnpacker::GetString(int SanitizeType)\n{\n\tif(m_Error || m_pCurrent >= m_pEnd)\n\t\treturn \"\";\n\n\tchar *pPtr = (char *)m_pCurrent;\n\twhile(*m_pCurrent) // skip the string\n\t{\n\t\tm_pCurrent++;\n\t\tif(m_pCurrent == m_pEnd)\n\t\t{\n\t\t\tm_Error = 1;;\n\t\t\treturn \"\";\n\t\t}\n\t}\n\tm_pCurrent++;\n\n\t// sanitize all strings\n\tif(SanitizeType&SANITIZE)\n\t\tstr_sanitize(pPtr);\n\telse if(SanitizeType&SANITIZE_CC)\n\t\tstr_sanitize_cc(pPtr);\n\treturn SanitizeType&SKIP_START_WHITESPACES ? str_skip_whitespaces(pPtr) : pPtr;\n}\n\nconst unsigned char *CUnpacker::GetRaw(int Size)\n{\n\tconst unsigned char *pPtr = m_pCurrent;\n\tif(m_Error)\n\t\treturn 0;\n\n\t// check for nasty sizes\n\tif(Size < 0 || m_pCurrent+Size > m_pEnd)\n\t{\n\t\tm_Error = 1;\n\t\treturn 0;\n\t}\n\n\t// \"unpack\" the data\n\tm_pCurrent += Size;\n\treturn pPtr;\n}\n"
  },
  {
    "path": "src/engine/shared/packer.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SHARED_PACKER_H\n#define ENGINE_SHARED_PACKER_H\n\n\n\nclass CPacker\n{\n\tenum\n\t{\n\t\tPACKER_BUFFER_SIZE=1024*2\n\t};\n\n\tunsigned char m_aBuffer[PACKER_BUFFER_SIZE];\n\tunsigned char *m_pCurrent;\n\tunsigned char *m_pEnd;\n\tint m_Error;\npublic:\n\tvoid Reset();\n\tvoid AddInt(int i);\n\tvoid AddString(const char *pStr, int Limit);\n\tvoid AddRaw(const void *pData, int Size);\n\n\tint Size() const { return (int)(m_pCurrent-m_aBuffer); }\n\tconst unsigned char *Data() const { return m_aBuffer; }\n\tbool Error() const { return m_Error; }\n};\n\nclass CUnpacker\n{\n\tconst unsigned char *m_pStart;\n\tconst unsigned char *m_pCurrent;\n\tconst unsigned char *m_pEnd;\n\tint m_Error;\npublic:\n\tenum\n\t{\n\t\tSANITIZE=1,\n\t\tSANITIZE_CC=2,\n\t\tSKIP_START_WHITESPACES=4\n\t};\n\n\tvoid Reset(const void *pData, int Size);\n\tint GetInt();\n\tconst char *GetString(int SanitizeType = SANITIZE);\n\tconst unsigned char *GetRaw(int Size);\n\tbool Error() const { return m_Error; }\n};\n\n#endif\n"
  },
  {
    "path": "src/engine/shared/protocol.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SHARED_PROTOCOL_H\n#define ENGINE_SHARED_PROTOCOL_H\n\n#include <base/system.h>\n\n/*\n\tConnection diagram - How the initilization works.\n\n\tClient -> INFO -> Server\n\t\tContains version info, name, and some other info.\n\n\tClient <- MAP <- Server\n\t\tContains current map.\n\n\tClient -> READY -> Server\n\t\tThe client has loaded the map and is ready to go,\n\t\tbut the mod needs to send it's information aswell.\n\t\tmodc_connected is called on the client and\n\t\tmods_connected is called on the server.\n\t\tThe client should call client_entergame when the\n\t\tmod has done it's initilization.\n\n\tClient -> ENTERGAME -> Server\n\t\tTells the server to start sending snapshots.\n\t\tclient_entergame and server_client_enter is called.\n*/\n\n\nenum\n{\n\tNETMSG_NULL=0,\n\n\t// the first thing sent by the client\n\t// contains the version info for the client\n\tNETMSG_INFO=1,\n\n\t// sent by server\n\tNETMSG_MAP_CHANGE,\t\t// sent when client should switch map\n\tNETMSG_MAP_DATA,\t\t// map transfer, contains a chunk of the map file\n\tNETMSG_CON_READY,\t\t// connection is ready, client should send start info\n\tNETMSG_SNAP,\t\t\t// normal snapshot, multiple parts\n\tNETMSG_SNAPEMPTY,\t\t// empty snapshot\n\tNETMSG_SNAPSINGLE,\t\t// ?\n\tNETMSG_SNAPSMALL,\t\t//\n\tNETMSG_INPUTTIMING,\t\t// reports how off the input was\n\tNETMSG_RCON_AUTH_ON,\t// rcon authentication enabled\n\tNETMSG_RCON_AUTH_OFF,\t// rcon authentication disabled\n\tNETMSG_RCON_LINE,\t\t// line that should be printed to the remote console\n\tNETMSG_RCON_CMD_ADD,\n\tNETMSG_RCON_CMD_REM,\n\n\tNETMSG_AUTH_CHALLANGE,\t//\n\tNETMSG_AUTH_RESULT,\t\t//\n\n\t// sent by client\n\tNETMSG_READY,\t\t\t//\n\tNETMSG_ENTERGAME,\n\tNETMSG_INPUT,\t\t\t// contains the inputdata from the client\n\tNETMSG_RCON_CMD,\t\t//\n\tNETMSG_RCON_AUTH,\t\t//\n\tNETMSG_REQUEST_MAP_DATA,//\n\n\tNETMSG_AUTH_START,\t\t//\n\tNETMSG_AUTH_RESPONSE,\t//\n\n\t// sent by both\n\tNETMSG_PING,\n\tNETMSG_PING_REPLY,\n\tNETMSG_ERROR,\n};\n\n// this should be revised\nenum\n{\n\tSERVER_TICK_SPEED=50,\n\tSERVERINFO_FLAG_PASSWORD = 0x1,\n\tSERVERINFO_LEVEL_MIN=0,\n\tSERVERINFO_LEVEL_MAX=2,\n\n\tMAX_CLIENTS=16,\n\n\tMAX_INPUT_SIZE=128,\n\tMAX_SNAPSHOT_PACKSIZE=900,\n\n\tMAX_NAME_LENGTH=16,\n\tMAX_CLAN_LENGTH=12,\n\n\t// message packing\n\tMSGFLAG_VITAL=1,\n\tMSGFLAG_FLUSH=2,\n\tMSGFLAG_NORECORD=4,\n\tMSGFLAG_RECORD=8,\n\tMSGFLAG_NOSEND=16\n};\n\n#endif\n"
  },
  {
    "path": "src/engine/shared/ringbuffer.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n\n#include \"ringbuffer.h\"\n\nCRingBufferBase::CItem *CRingBufferBase::NextBlock(CItem *pItem)\n{\n\tif(pItem->m_pNext)\n\t\treturn pItem->m_pNext;\n\treturn m_pFirst;\n}\n\nCRingBufferBase::CItem *CRingBufferBase::PrevBlock(CItem *pItem)\n{\n\tif(pItem->m_pPrev)\n\t\treturn pItem->m_pPrev;\n\treturn m_pLast;\n}\n\nCRingBufferBase::CItem *CRingBufferBase::MergeBack(CItem *pItem)\n{\n\t// make sure that this block and previous block is free\n\tif(!pItem->m_Free || !pItem->m_pPrev || !pItem->m_pPrev->m_Free)\n\t\treturn pItem;\n\n\t// merge the blocks\n\tpItem->m_pPrev->m_Size += pItem->m_Size;\n\tpItem->m_pPrev->m_pNext = pItem->m_pNext;\n\n\t// fixup pointers\n\tif(pItem->m_pNext)\n\t\tpItem->m_pNext->m_pPrev = pItem->m_pPrev;\n\telse\n\t\tm_pLast = pItem->m_pPrev;\n\n\tif(pItem == m_pProduce)\n\t\tm_pProduce = pItem->m_pPrev;\n\n\tif(pItem == m_pConsume)\n\t\tm_pConsume = pItem->m_pPrev;\n\n\t// return the current block\n\treturn pItem->m_pPrev;\n}\n\nvoid CRingBufferBase::Init(void *pMemory, int Size, int Flags)\n{\n\tmem_zero(pMemory, Size);\n\tm_Size = (Size)/sizeof(CItem)*sizeof(CItem);\n\tm_pFirst = (CItem *)pMemory;\n\tm_pFirst->m_Free = 1;\n\tm_pFirst->m_Size = m_Size;\n\tm_pLast = m_pFirst;\n\tm_pProduce = m_pFirst;\n\tm_pConsume = m_pFirst;\n\tm_Flags = Flags;\n\n}\n\nvoid *CRingBufferBase::Allocate(int Size)\n{\n\tint WantedSize = (Size+sizeof(CItem)+sizeof(CItem)-1)/sizeof(CItem)*sizeof(CItem);\n\tCItem *pBlock = 0;\n\n\t// check if we even can fit this block\n\tif(WantedSize > m_Size)\n\t\treturn 0;\n\n\twhile(1)\n\t{\n\t\t// check for space\n\t\tif(m_pProduce->m_Free)\n\t\t{\n\t\t\tif(m_pProduce->m_Size >= WantedSize)\n\t\t\t\tpBlock = m_pProduce;\n\t\t\telse\n\t\t\t{\n\t\t\t\t// wrap around to try to find a block\n\t\t\t\tif(m_pFirst->m_Free && m_pFirst->m_Size >= WantedSize)\n\t\t\t\t\tpBlock = m_pFirst;\n\t\t\t}\n\t\t}\n\n\t\tif(pBlock)\n\t\t\tbreak;\n\t\telse\n\t\t{\n\t\t\t// we have no block, check our policy and see what todo\n\t\t\tif(m_Flags&FLAG_RECYCLE)\n\t\t\t{\n\t\t\t\tif(!PopFirst())\n\t\t\t\t\treturn 0;\n\t\t\t}\n\t\t\telse\n\t\t\t\treturn 0;\n\t\t}\n\t}\n\n\t// okey, we have our block\n\n\t// split the block if needed\n\tif(pBlock->m_Size > WantedSize+(int)sizeof(CItem))\n\t{\n\t\tCItem *pNewItem = (CItem *)((char *)pBlock + WantedSize);\n\t\tpNewItem->m_pPrev = pBlock;\n\t\tpNewItem->m_pNext = pBlock->m_pNext;\n\t\tif(pNewItem->m_pNext)\n\t\t\tpNewItem->m_pNext->m_pPrev = pNewItem;\n\t\tpBlock->m_pNext = pNewItem;\n\n\t\tpNewItem->m_Free = 1;\n\t\tpNewItem->m_Size = pBlock->m_Size - WantedSize;\n\t\tpBlock->m_Size = WantedSize;\n\n\t\tif(!pNewItem->m_pNext)\n\t\t\tm_pLast = pNewItem;\n\t}\n\n\n\t// set next block\n\tm_pProduce = NextBlock(pBlock);\n\n\t// set as used and return the item pointer\n\tpBlock->m_Free = 0;\n\treturn (void *)(pBlock+1);\n}\n\nint CRingBufferBase::PopFirst()\n{\n\tif(m_pConsume->m_Free)\n\t\treturn 0;\n\n\t// set the free flag\n\tm_pConsume->m_Free = 1;\n\n\t// previous block is also free, merge them\n\tm_pConsume = MergeBack(m_pConsume);\n\n\t// advance the consume pointer\n\tm_pConsume = NextBlock(m_pConsume);\n\twhile(m_pConsume->m_Free && m_pConsume != m_pProduce)\n\t{\n\t\tm_pConsume = MergeBack(m_pConsume);\n\t\tm_pConsume = NextBlock(m_pConsume);\n\t}\n\n\t// in the case that we have catched up with the produce pointer\n\t// we might stand on a free block so merge em\n\tMergeBack(m_pConsume);\n\treturn 1;\n}\n\n\nvoid *CRingBufferBase::Prev(void *pCurrent)\n{\n\tCItem *pItem = ((CItem *)pCurrent) - 1;\n\n\twhile(1)\n\t{\n\t\tpItem = PrevBlock(pItem);\n\t\tif(pItem == m_pProduce)\n\t\t\treturn 0;\n\t\tif(!pItem->m_Free)\n\t\t\treturn pItem+1;\n\t}\n}\n\nvoid *CRingBufferBase::Next(void *pCurrent)\n{\n\tCItem *pItem = ((CItem *)pCurrent) - 1;\n\n\twhile(1)\n\t{\n\t\tpItem = NextBlock(pItem);\n\t\tif(pItem == m_pProduce)\n\t\t\treturn 0;\n\t\tif(!pItem->m_Free)\n\t\t\treturn pItem+1;\n\t}\n}\n\nvoid *CRingBufferBase::First()\n{\n\tif(m_pConsume->m_Free)\n\t\treturn 0;\n\treturn (void *)(m_pConsume+1);\n}\n\nvoid *CRingBufferBase::Last()\n{\n\treturn Prev(m_pProduce+1);\n}\n\n"
  },
  {
    "path": "src/engine/shared/ringbuffer.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SHARED_RINGBUFFER_H\n#define ENGINE_SHARED_RINGBUFFER_H\n\ntypedef struct RINGBUFFER RINGBUFFER;\n\nclass CRingBufferBase\n{\n\tclass CItem\n\t{\n\tpublic:\n\t\tCItem *m_pPrev;\n\t\tCItem *m_pNext;\n\t\tint m_Free;\n\t\tint m_Size;\n\t};\n\n\tCItem *m_pProduce;\n\tCItem *m_pConsume;\n\n\tCItem *m_pFirst;\n\tCItem *m_pLast;\n\n\tvoid *m_pMemory;\n\tint m_Size;\n\tint m_Flags;\n\n\tCItem *NextBlock(CItem *pItem);\n\tCItem *PrevBlock(CItem *pItem);\n\tCItem *MergeBack(CItem *pItem);\nprotected:\n\tvoid *Allocate(int Size);\n\n\tvoid *Prev(void *pCurrent);\n\tvoid *Next(void *pCurrent);\n\tvoid *First();\n\tvoid *Last();\n\n\tvoid Init(void *pMemory, int Size, int Flags);\n\tint PopFirst();\npublic:\n\tenum\n\t{\n\t\t// Will start to destroy items to try to fit the next one\n\t\tFLAG_RECYCLE=1\n\t};\n};\n\ntemplate<typename T, int TSIZE, int TFLAGS=0>\nclass TStaticRingBuffer : public CRingBufferBase\n{\n\tunsigned char m_aBuffer[TSIZE];\npublic:\n\tTStaticRingBuffer() { Init(); }\n\n\tvoid Init() { CRingBufferBase::Init(m_aBuffer, TSIZE, TFLAGS); }\n\n\tT *Allocate(int Size) { return (T*)CRingBufferBase::Allocate(Size); }\n\tint PopFirst() { return CRingBufferBase::PopFirst(); }\n\n\tT *Prev(T *pCurrent) { return (T*)CRingBufferBase::Prev(pCurrent); }\n\tT *Next(T *pCurrent) { return (T*)CRingBufferBase::Next(pCurrent); }\n\tT *First() { return (T*)CRingBufferBase::First(); }\n\tT *Last() { return (T*)CRingBufferBase::Last(); }\n};\n\n#endif\n"
  },
  {
    "path": "src/engine/shared/snapshot.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include \"snapshot.h\"\n#include \"compression.h\"\n\n// CSnapshot\n\nCSnapshotItem *CSnapshot::GetItem(int Index)\n{\n\treturn (CSnapshotItem *)(DataStart() + Offsets()[Index]);\n}\n\nint CSnapshot::GetItemSize(int Index)\n{\n\tif(Index == m_NumItems-1)\n\t\treturn (m_DataSize - Offsets()[Index]) - sizeof(CSnapshotItem);\n\treturn (Offsets()[Index+1] - Offsets()[Index]) - sizeof(CSnapshotItem);\n}\n\nint CSnapshot::GetItemIndex(int Key)\n{\n\t// TODO: OPT: this should not be a linear search. very bad\n\tfor(int i = 0; i < m_NumItems; i++)\n\t{\n\t\tif(GetItem(i)->Key() == Key)\n\t\t\treturn i;\n\t}\n\treturn -1;\n}\n\nint CSnapshot::Crc()\n{\n\tint Crc = 0;\n\n\tfor(int i = 0; i < m_NumItems; i++)\n\t{\n\t\tCSnapshotItem *pItem = GetItem(i);\n\t\tint Size = GetItemSize(i);\n\n\t\tfor(int b = 0; b < Size/4; b++)\n\t\t\tCrc += pItem->Data()[b];\n\t}\n\treturn Crc;\n}\n\nvoid CSnapshot::DebugDump()\n{\n\tdbg_msg(\"snapshot\", \"data_size=%d num_items=%d\", m_DataSize, m_NumItems);\n\tfor(int i = 0; i < m_NumItems; i++)\n\t{\n\t\tCSnapshotItem *pItem = GetItem(i);\n\t\tint Size = GetItemSize(i);\n\t\tdbg_msg(\"snapshot\", \"\\ttype=%d id=%d\", pItem->Type(), pItem->ID());\n\t\tfor(int b = 0; b < Size/4; b++)\n\t\t\tdbg_msg(\"snapshot\", \"\\t\\t%3d %12d\\t%08x\", b, pItem->Data()[b], pItem->Data()[b]);\n\t}\n}\n\n\n// CSnapshotDelta\n\nstruct CItemList\n{\n\tint m_Num;\n\tint m_aKeys[64];\n\tint m_aIndex[64];\n};\n\nenum\n{\n\tHASHLIST_SIZE = 256,\n};\n\nstatic void GenerateHash(CItemList *pHashlist, CSnapshot *pSnapshot)\n{\n\tfor(int i = 0; i < HASHLIST_SIZE; i++)\n\t\tpHashlist[i].m_Num = 0;\n\n\tfor(int i = 0; i < pSnapshot->NumItems(); i++)\n\t{\n\t\tint Key = pSnapshot->GetItem(i)->Key();\n\t\tint HashID = ((Key>>12)&0xf0) | (Key&0xf);\n\t\tif(pHashlist[HashID].m_Num != 64)\n\t\t{\n\t\t\tpHashlist[HashID].m_aIndex[pHashlist[HashID].m_Num] = i;\n\t\t\tpHashlist[HashID].m_aKeys[pHashlist[HashID].m_Num] = Key;\n\t\t\tpHashlist[HashID].m_Num++;\n\t\t}\n\t}\n}\n\nstatic int GetItemIndexHashed(int Key, const CItemList *pHashlist)\n{\n\t\tint HashID = ((Key>>12)&0xf0) | (Key&0xf);\n\t\tfor(int i = 0; i < pHashlist[HashID].m_Num; i++)\n\t\t{\n\t\t\tif(pHashlist[HashID].m_aKeys[i] == Key)\n\t\t\t\treturn pHashlist[HashID].m_aIndex[i];\n\t}\n\n\treturn -1;\n}\n\nstatic int DiffItem(int *pPast, int *pCurrent, int *pOut, int Size)\n{\n\tint Needed = 0;\n\twhile(Size)\n\t{\n\t\t*pOut = *pCurrent-*pPast;\n\t\tNeeded |= *pOut;\n\t\tpOut++;\n\t\tpPast++;\n\t\tpCurrent++;\n\t\tSize--;\n\t}\n\n\treturn Needed;\n}\n\nvoid CSnapshotDelta::UndiffItem(int *pPast, int *pDiff, int *pOut, int Size)\n{\n\twhile(Size)\n\t{\n\t\t*pOut = *pPast+*pDiff;\n\n\t\tif(*pDiff == 0)\n\t\t\tm_aSnapshotDataRate[m_SnapshotCurrent] += 1;\n\t\telse\n\t\t{\n\t\t\tunsigned char aBuf[16];\n\t\t\tunsigned char *pEnd = CVariableInt::Pack(aBuf, *pDiff);\n\t\t\tm_aSnapshotDataRate[m_SnapshotCurrent] += (int)(pEnd - (unsigned char*)aBuf) * 8;\n\t\t}\n\n\t\tpOut++;\n\t\tpPast++;\n\t\tpDiff++;\n\t\tSize--;\n\t}\n}\n\nCSnapshotDelta::CSnapshotDelta()\n{\n\tmem_zero(m_aItemSizes, sizeof(m_aItemSizes));\n\tmem_zero(m_aSnapshotDataRate, sizeof(m_aSnapshotDataRate));\n\tmem_zero(m_aSnapshotDataUpdates, sizeof(m_aSnapshotDataUpdates));\n\tm_SnapshotCurrent = 0;\n\tmem_zero(&m_Empty, sizeof(m_Empty));\n}\n\nvoid CSnapshotDelta::SetStaticsize(int ItemType, int Size)\n{\n\tm_aItemSizes[ItemType] = Size;\n}\n\nCSnapshotDelta::CData *CSnapshotDelta::EmptyDelta()\n{\n\treturn &m_Empty;\n}\n\n// TODO: OPT: this should be made much faster\nint CSnapshotDelta::CreateDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pDstData)\n{\n\tCData *pDelta = (CData *)pDstData;\n\tint *pData = (int *)pDelta->m_pData;\n\tint i, ItemSize, PastIndex;\n\tCSnapshotItem *pFromItem;\n\tCSnapshotItem *pCurItem;\n\tCSnapshotItem *pPastItem;\n\tint Count = 0;\n\tint SizeCount = 0;\n\n\tpDelta->m_NumDeletedItems = 0;\n\tpDelta->m_NumUpdateItems = 0;\n\tpDelta->m_NumTempItems = 0;\n\n\tCItemList Hashlist[HASHLIST_SIZE];\n\tGenerateHash(Hashlist, pTo);\n\n\t// pack deleted stuff\n\tfor(i = 0; i < pFrom->NumItems(); i++)\n\t{\n\t\tpFromItem = pFrom->GetItem(i);\n\t\tif(GetItemIndexHashed(pFromItem->Key(), Hashlist) == -1)\n\t\t{\n\t\t\t// deleted\n\t\t\tpDelta->m_NumDeletedItems++;\n\t\t\t*pData = pFromItem->Key();\n\t\t\tpData++;\n\t\t}\n\t}\n\n\tGenerateHash(Hashlist, pFrom);\n\tint aPastIndecies[1024];\n\n\t// fetch previous indices\n\t// we do this as a separate pass because it helps the cache\n\tconst int NumItems = pTo->NumItems();\n\tfor(i = 0; i < NumItems; i++)\n\t{\n\t\tpCurItem = pTo->GetItem(i); // O(1) .. O(n)\n\t\taPastIndecies[i] = GetItemIndexHashed(pCurItem->Key(), Hashlist); // O(n) .. O(n^n)\n\t}\n\n\tfor(i = 0; i < NumItems; i++)\n\t{\n\t\t// do delta\n\t\tItemSize = pTo->GetItemSize(i); // O(1) .. O(n)\n\t\tpCurItem = pTo->GetItem(i); // O(1) .. O(n)\n\t\tPastIndex = aPastIndecies[i];\n\n\t\tif(PastIndex != -1)\n\t\t{\n\t\t\tint *pItemDataDst = pData+3;\n\n\t\t\tpPastItem = pFrom->GetItem(PastIndex);\n\n\t\t\tif(m_aItemSizes[pCurItem->Type()])\n\t\t\t\tpItemDataDst = pData+2;\n\n\t\t\tif(DiffItem((int*)pPastItem->Data(), (int*)pCurItem->Data(), pItemDataDst, ItemSize/4))\n\t\t\t{\n\n\t\t\t\t*pData++ = pCurItem->Type();\n\t\t\t\t*pData++ = pCurItem->ID();\n\t\t\t\tif(!m_aItemSizes[pCurItem->Type()])\n\t\t\t\t\t*pData++ = ItemSize/4;\n\t\t\t\tpData += ItemSize/4;\n\t\t\t\tpDelta->m_NumUpdateItems++;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t*pData++ = pCurItem->Type();\n\t\t\t*pData++ = pCurItem->ID();\n\t\t\tif(!m_aItemSizes[pCurItem->Type()])\n\t\t\t\t*pData++ = ItemSize/4;\n\n\t\t\tmem_copy(pData, pCurItem->Data(), ItemSize);\n\t\t\tSizeCount += ItemSize;\n\t\t\tpData += ItemSize/4;\n\t\t\tpDelta->m_NumUpdateItems++;\n\t\t\tCount++;\n\t\t}\n\t}\n\n\tif(0)\n\t{\n\t\tdbg_msg(\"snapshot\", \"%d %d %d\",\n\t\t\tpDelta->m_NumDeletedItems,\n\t\t\tpDelta->m_NumUpdateItems,\n\t\t\tpDelta->m_NumTempItems);\n\t}\n\n\t/*\n\t// TODO: pack temp stuff\n\n\t// finish\n\t//mem_copy(pDelta->offsets, deleted, pDelta->num_deleted_items*sizeof(int));\n\t//mem_copy(&(pDelta->offsets[pDelta->num_deleted_items]), update, pDelta->num_update_items*sizeof(int));\n\t//mem_copy(&(pDelta->offsets[pDelta->num_deleted_items+pDelta->num_update_items]), temp, pDelta->num_temp_items*sizeof(int));\n\t//mem_copy(pDelta->data_start(), data, data_size);\n\t//pDelta->data_size = data_size;\n\t* */\n\n\tif(!pDelta->m_NumDeletedItems && !pDelta->m_NumUpdateItems && !pDelta->m_NumTempItems)\n\t\treturn 0;\n\n\treturn (int)((char*)pData-(char*)pDstData);\n}\n\nstatic int RangeCheck(void *pEnd, void *pPtr, int Size)\n{\n\tif((const char *)pPtr + Size > (const char *)pEnd)\n\t\treturn -1;\n\treturn 0;\n}\n\nint CSnapshotDelta::UnpackDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pSrcData, int DataSize)\n{\n\tCSnapshotBuilder Builder;\n\tCData *pDelta = (CData *)pSrcData;\n\tint *pData = (int *)pDelta->m_pData;\n\tint *pEnd = (int *)(((char *)pSrcData + DataSize));\n\n\tCSnapshotItem *pFromItem;\n\tint Keep, ItemSize;\n\tint *pDeleted;\n\tint ID, Type, Key;\n\tint FromIndex;\n\tint *pNewData;\n\n\tBuilder.Init();\n\n\t// unpack deleted stuff\n\tpDeleted = pData;\n\tpData += pDelta->m_NumDeletedItems;\n\tif(pData > pEnd)\n\t\treturn -1;\n\n\t// copy all non deleted stuff\n\tfor(int i = 0; i < pFrom->NumItems(); i++)\n\t{\n\t\t// dbg_assert(0, \"fail!\");\n\t\tpFromItem = pFrom->GetItem(i);\n\t\tItemSize = pFrom->GetItemSize(i);\n\t\tKeep = 1;\n\t\tfor(int d = 0; d < pDelta->m_NumDeletedItems; d++)\n\t\t{\n\t\t\tif(pDeleted[d] == pFromItem->Key())\n\t\t\t{\n\t\t\t\tKeep = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif(Keep)\n\t\t{\n\t\t\t// keep it\n\t\t\tmem_copy(\n\t\t\t\tBuilder.NewItem(pFromItem->Type(), pFromItem->ID(), ItemSize),\n\t\t\t\tpFromItem->Data(), ItemSize);\n\t\t}\n\t}\n\n\t// unpack updated stuff\n\tfor(int i = 0; i < pDelta->m_NumUpdateItems; i++)\n\t{\n\t\tif(pData+2 > pEnd)\n\t\t\treturn -1;\n\n\t\tType = *pData++;\n\t\tID = *pData++;\n\t\tif(m_aItemSizes[Type])\n\t\t\tItemSize = m_aItemSizes[Type];\n\t\telse\n\t\t{\n\t\t\tif(pData+1 > pEnd)\n\t\t\t\treturn -2;\n\t\t\tItemSize = (*pData++) * 4;\n\t\t}\n\t\tm_SnapshotCurrent = Type;\n\n\t\tif(RangeCheck(pEnd, pData, ItemSize) || ItemSize < 0) return -3;\n\n\t\tKey = (Type<<16)|ID;\n\n\t\t// create the item if needed\n\t\tpNewData = Builder.GetItemData(Key);\n\t\tif(!pNewData)\n\t\t\tpNewData = (int *)Builder.NewItem(Key>>16, Key&0xffff, ItemSize);\n\n\t\t//if(range_check(pEnd, pNewData, ItemSize)) return -4;\n\n\t\tFromIndex = pFrom->GetItemIndex(Key);\n\t\tif(FromIndex != -1)\n\t\t{\n\t\t\t// we got an update so we need pTo apply the diff\n\t\t\tUndiffItem((int *)pFrom->GetItem(FromIndex)->Data(), pData, pNewData, ItemSize/4);\n\t\t\tm_aSnapshotDataUpdates[m_SnapshotCurrent]++;\n\t\t}\n\t\telse // no previous, just copy the pData\n\t\t{\n\t\t\tmem_copy(pNewData, pData, ItemSize);\n\t\t\tm_aSnapshotDataRate[m_SnapshotCurrent] += ItemSize*8;\n\t\t\tm_aSnapshotDataUpdates[m_SnapshotCurrent]++;\n\t\t}\n\n\t\tpData += ItemSize/4;\n\t}\n\n\t// finish up\n\treturn Builder.Finish(pTo);\n}\n\n\n// CSnapshotStorage\n\nvoid CSnapshotStorage::Init()\n{\n\tm_pFirst = 0;\n\tm_pLast = 0;\n}\n\nvoid CSnapshotStorage::PurgeAll()\n{\n\tCHolder *pHolder = m_pFirst;\n\tCHolder *pNext;\n\n\twhile(pHolder)\n\t{\n\t\tpNext = pHolder->m_pNext;\n\t\tmem_free(pHolder);\n\t\tpHolder = pNext;\n\t}\n\n\t// no more snapshots in storage\n\tm_pFirst = 0;\n\tm_pLast = 0;\n}\n\nvoid CSnapshotStorage::PurgeUntil(int Tick)\n{\n\tCHolder *pHolder = m_pFirst;\n\tCHolder *pNext;\n\n\twhile(pHolder)\n\t{\n\t\tpNext = pHolder->m_pNext;\n\t\tif(pHolder->m_Tick >= Tick)\n\t\t\treturn; // no more to remove\n\t\tmem_free(pHolder);\n\n\t\t// did we come to the end of the list?\n\t\tif (!pNext)\n\t\t\tbreak;\n\n\t\tm_pFirst = pNext;\n\t\tpNext->m_pPrev = 0x0;\n\n\t\tpHolder = pNext;\n\t}\n\n\t// no more snapshots in storage\n\tm_pFirst = 0;\n\tm_pLast = 0;\n}\n\nvoid CSnapshotStorage::Add(int Tick, int64 Tagtime, int DataSize, void *pData, int CreateAlt)\n{\n\t// allocate memory for holder + snapshot_data\n\tint TotalSize = sizeof(CHolder)+DataSize;\n\n\tif(CreateAlt)\n\t\tTotalSize += DataSize;\n\n\tCHolder *pHolder = (CHolder *)mem_alloc(TotalSize, 1);\n\n\t// set data\n\tpHolder->m_Tick = Tick;\n\tpHolder->m_Tagtime = Tagtime;\n\tpHolder->m_SnapSize = DataSize;\n\tpHolder->m_pSnap = (CSnapshot*)(pHolder+1);\n\tmem_copy(pHolder->m_pSnap, pData, DataSize);\n\n\tif(CreateAlt) // create alternative if wanted\n\t{\n\t\tpHolder->m_pAltSnap = (CSnapshot*)(((char *)pHolder->m_pSnap) + DataSize);\n\t\tmem_copy(pHolder->m_pAltSnap, pData, DataSize);\n\t}\n\telse\n\t\tpHolder->m_pAltSnap = 0;\n\n\n\t// link\n\tpHolder->m_pNext = 0;\n\tpHolder->m_pPrev = m_pLast;\n\tif(m_pLast)\n\t\tm_pLast->m_pNext = pHolder;\n\telse\n\t\tm_pFirst = pHolder;\n\tm_pLast = pHolder;\n}\n\nint CSnapshotStorage::Get(int Tick, int64 *pTagtime, CSnapshot **ppData, CSnapshot **ppAltData)\n{\n\tCHolder *pHolder = m_pFirst;\n\n\twhile(pHolder)\n\t{\n\t\tif(pHolder->m_Tick == Tick)\n\t\t{\n\t\t\tif(pTagtime)\n\t\t\t\t*pTagtime = pHolder->m_Tagtime;\n\t\t\tif(ppData)\n\t\t\t\t*ppData = pHolder->m_pSnap;\n\t\t\tif(ppAltData)\n\t\t\t\t*ppAltData = pHolder->m_pAltSnap;\n\t\t\treturn pHolder->m_SnapSize;\n\t\t}\n\n\t\tpHolder = pHolder->m_pNext;\n\t}\n\n\treturn -1;\n}\n\n// CSnapshotBuilder\n\nvoid CSnapshotBuilder::Init()\n{\n\tm_DataSize = 0;\n\tm_NumItems = 0;\n}\n\nvoid CSnapshotBuilder::Init(const CSnapshot *pSnapshot)\n{\n\tif(pSnapshot->m_DataSize > CSnapshot::MAX_SIZE || pSnapshot->m_NumItems > MAX_ITEMS)\n\t{\n\t\tdbg_assert(m_DataSize < CSnapshot::MAX_SIZE, \"too much data\");\n\t\tdbg_assert(m_NumItems < MAX_ITEMS, \"too many items\");\n\t\tdbg_msg(\"snapshot\", \"invalid snapshot\"); // remove me\n\t\tm_DataSize = 0;\n\t\tm_NumItems = 0;\n\t\treturn;\n\t}\n\n\tm_DataSize = pSnapshot->m_DataSize;\n\tm_NumItems = pSnapshot->m_NumItems;\n\tmem_copy(m_aOffsets, pSnapshot->Offsets(), sizeof(int)*m_NumItems);\n\tmem_copy(m_aData, pSnapshot->DataStart(), m_DataSize);\n}\n\nCSnapshotItem *CSnapshotBuilder::GetItem(int Index)\n{\n\treturn (CSnapshotItem *)&(m_aData[m_aOffsets[Index]]);\n}\n\nint *CSnapshotBuilder::GetItemData(int Key)\n{\n\tint i;\n\tfor(i = 0; i < m_NumItems; i++)\n\t{\n\t\tif(GetItem(i)->Key() == Key)\n\t\t\treturn (int *)GetItem(i)->Data();\n\t}\n\treturn 0;\n}\n\nint CSnapshotBuilder::Finish(void *SpnapData)\n{\n\t// flattern and make the snapshot\n\tCSnapshot *pSnap = (CSnapshot *)SpnapData;\n\tint OffsetSize = sizeof(int)*m_NumItems;\n\tpSnap->m_DataSize = m_DataSize;\n\tpSnap->m_NumItems = m_NumItems;\n\tmem_copy(pSnap->Offsets(), m_aOffsets, OffsetSize);\n\tmem_copy(pSnap->DataStart(), m_aData, m_DataSize);\n\treturn sizeof(CSnapshot) + OffsetSize + m_DataSize;\n}\n\nvoid *CSnapshotBuilder::NewItem(int Type, int ID, int Size)\n{\n\tif(m_DataSize + sizeof(CSnapshotItem) + Size >= CSnapshot::MAX_SIZE ||\n\t\tm_NumItems+1 >= MAX_ITEMS)\n\t{\n\t\tdbg_assert(m_DataSize < CSnapshot::MAX_SIZE, \"too much data\");\n\t\tdbg_assert(m_NumItems < MAX_ITEMS, \"too many items\");\n\t\treturn 0;\n\t}\n\n\tCSnapshotItem *pObj = (CSnapshotItem *)(m_aData + m_DataSize);\n\n\tmem_zero(pObj, sizeof(CSnapshotItem) + Size);\n\tpObj->m_TypeAndID = (Type<<16)|ID;\n\tm_aOffsets[m_NumItems] = m_DataSize;\n\tm_DataSize += sizeof(CSnapshotItem) + Size;\n\tm_NumItems++;\n\n\treturn pObj->Data();\n}\n"
  },
  {
    "path": "src/engine/shared/snapshot.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SHARED_SNAPSHOT_H\n#define ENGINE_SHARED_SNAPSHOT_H\n\n#include <base/system.h>\n\n// CSnapshot\n\nclass CSnapshotItem\n{\npublic:\n\tint m_TypeAndID;\n\n\tint *Data() { return (int *)(this+1); }\n\tint Type() { return m_TypeAndID>>16; }\n\tint ID() { return m_TypeAndID&0xffff; }\n\tint Key() { return m_TypeAndID; }\n};\n\n\nclass CSnapshot\n{\n\tfriend class CSnapshotBuilder;\n\tint m_DataSize;\n\tint m_NumItems;\n\n\tint *Offsets() const { return (int *)(this+1); }\n\tchar *DataStart() const { return (char*)(Offsets()+m_NumItems); }\n\npublic:\n\tenum\n\t{\n\t\tMAX_SIZE=64*1024\n\t};\n\n\tvoid Clear() { m_DataSize = 0; m_NumItems = 0; }\n\tint NumItems() const { return m_NumItems; }\n\tCSnapshotItem *GetItem(int Index);\n\tint GetItemSize(int Index);\n\tint GetItemIndex(int Key);\n\n\tint Crc();\n\tvoid DebugDump();\n};\n\n\n// CSnapshotDelta\n\nclass CSnapshotDelta\n{\npublic:\n\tclass CData\n\t{\n\tpublic:\n\t\tint m_NumDeletedItems;\n\t\tint m_NumUpdateItems;\n\t\tint m_NumTempItems; // needed?\n\t\tint m_pData[1];\n\t};\n\nprivate:\n\t// TODO: strange arbitrary number\n\tshort m_aItemSizes[64];\n\tint m_aSnapshotDataRate[0xffff];\n\tint m_aSnapshotDataUpdates[0xffff];\n\tint m_SnapshotCurrent;\n\tCData m_Empty;\n\n\tvoid UndiffItem(int *pPast, int *pDiff, int *pOut, int Size);\n\npublic:\n\tCSnapshotDelta();\n\tint GetDataRate(int Index) { return m_aSnapshotDataRate[Index]; }\n\tint GetDataUpdates(int Index) { return m_aSnapshotDataUpdates[Index]; }\n\tvoid SetStaticsize(int ItemType, int Size);\n\tCData *EmptyDelta();\n\tint CreateDelta(class CSnapshot *pFrom, class CSnapshot *pTo, void *pData);\n\tint UnpackDelta(class CSnapshot *pFrom, class CSnapshot *pTo, void *pData, int DataSize);\n};\n\n\n// CSnapshotStorage\n\nclass CSnapshotStorage\n{\npublic:\n\tclass CHolder\n\t{\n\tpublic:\n\t\tCHolder *m_pPrev;\n\t\tCHolder *m_pNext;\n\n\t\tint64 m_Tagtime;\n\t\tint m_Tick;\n\n\t\tint m_SnapSize;\n\t\tCSnapshot *m_pSnap;\n\t\tCSnapshot *m_pAltSnap;\n\t};\n\n\n\tCHolder *m_pFirst;\n\tCHolder *m_pLast;\n\n\tvoid Init();\n\tvoid PurgeAll();\n\tvoid PurgeUntil(int Tick);\n\tvoid Add(int Tick, int64 Tagtime, int DataSize, void *pData, int CreateAlt);\n\tint Get(int Tick, int64 *Tagtime, CSnapshot **pData, CSnapshot **ppAltData);\n};\n\nclass CSnapshotBuilder\n{\n\tenum\n\t{\n\t\tMAX_ITEMS = 1024\n\t};\n\n\tchar m_aData[CSnapshot::MAX_SIZE];\n\tint m_DataSize;\n\n\tint m_aOffsets[MAX_ITEMS];\n\tint m_NumItems;\n\npublic:\n\tvoid Init();\n\tvoid Init(const CSnapshot *pSnapshot);\n\n\tvoid *NewItem(int Type, int ID, int Size);\n\n\tCSnapshotItem *GetItem(int Index);\n\tint *GetItemData(int Key);\n\n\tint Finish(void *Snapdata);\n};\n\n\n#endif // ENGINE_SNAPSHOT_H\n"
  },
  {
    "path": "src/engine/shared/storage.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n#include <engine/storage.h>\n#include \"linereader.h\"\n\n// compiled-in data-dir path\n#define DATA_DIR \"data\"\n\nclass CStorage : public IStorage\n{\npublic:\n\tenum\n\t{\n\t\tMAX_PATHS = 16,\n\t\tMAX_PATH_LENGTH = 512\n\t};\n\n\tchar m_aaStoragePaths[MAX_PATHS][MAX_PATH_LENGTH];\n\tint m_NumPaths;\n\tchar m_aDatadir[MAX_PATH_LENGTH];\n\tchar m_aUserdir[MAX_PATH_LENGTH];\n\tchar m_aCurrentdir[MAX_PATH_LENGTH];\n\n\tCStorage()\n\t{\n\t\tmem_zero(m_aaStoragePaths, sizeof(m_aaStoragePaths));\n\t\tm_NumPaths = 0;\n\t\tm_aDatadir[0] = 0;\n\t\tm_aUserdir[0] = 0;\n\t}\n\n\tint Init(const char *pApplicationName, int StorageType, int NumArgs, const char **ppArguments)\n\t{\n\t\t// get userdir\n\t\tfs_storage_path(pApplicationName, m_aUserdir, sizeof(m_aUserdir));\n\n\t\t// get datadir\n\t\tFindDatadir(ppArguments[0]);\n\n\t\t// get currentdir\n\t\tif(!fs_getcwd(m_aCurrentdir, sizeof(m_aCurrentdir)))\n\t\t\tm_aCurrentdir[0] = 0;\n\n\t\t// load paths from storage.cfg\n\t\tLoadPaths(ppArguments[0]);\n\n\t\tif(!m_NumPaths)\n\t\t{\n\t\t\tdbg_msg(\"storage\", \"using standard paths\");\n\t\t\tAddDefaultPaths();\n\t\t}\n\n\t\t// add save directories\n\t\tif(StorageType != STORAGETYPE_BASIC)\n\t\t{\n\t\t\tif(m_NumPaths && (!m_aaStoragePaths[TYPE_SAVE][0] || !fs_makedir(m_aaStoragePaths[TYPE_SAVE])))\n\t\t\t{\n\t\t\t\tchar aPath[MAX_PATH_LENGTH];\n\t\t\t\tif(StorageType == STORAGETYPE_CLIENT)\n\t\t\t\t{\n\t\t\t\t\tfs_makedir(GetPath(TYPE_SAVE, \"screenshots\", aPath, sizeof(aPath)));\n\t\t\t\t\tfs_makedir(GetPath(TYPE_SAVE, \"screenshots/auto\", aPath, sizeof(aPath)));\n\t\t\t\t\tfs_makedir(GetPath(TYPE_SAVE, \"maps\", aPath, sizeof(aPath)));\n\t\t\t\t\tfs_makedir(GetPath(TYPE_SAVE, \"downloadedmaps\", aPath, sizeof(aPath)));\n\t\t\t\t\tfs_makedir(GetPath(TYPE_SAVE, \"skins\", aPath, sizeof(aPath)));\n\t\t\t\t}\n\t\t\t\tfs_makedir(GetPath(TYPE_SAVE, \"dumps\", aPath, sizeof(aPath)));\n\t\t\t\tfs_makedir(GetPath(TYPE_SAVE, \"demos\", aPath, sizeof(aPath)));\n\t\t\t\tfs_makedir(GetPath(TYPE_SAVE, \"demos/auto\", aPath, sizeof(aPath)));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdbg_msg(\"storage\", \"unable to create save directory\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\n\t\treturn m_NumPaths ? 0 : 1;\n\t}\n\n\tvoid LoadPaths(const char *pArgv0)\n\t{\n\t\t// check current directory\n\t\tIOHANDLE File = io_open(\"storage.cfg\", IOFLAG_READ);\n\t\tif(!File)\n\t\t{\n\t\t\t// check usable path in argv[0]\n\t\t\tunsigned int Pos = ~0U;\n\t\t\tfor(unsigned i = 0; pArgv0[i]; i++)\n\t\t\t\tif(pArgv0[i] == '/' || pArgv0[i] == '\\\\')\n\t\t\t\t\tPos = i;\n\t\t\tif(Pos < MAX_PATH_LENGTH)\n\t\t\t{\n\t\t\t\tchar aBuffer[MAX_PATH_LENGTH];\n\t\t\t\tstr_copy(aBuffer, pArgv0, Pos+1);\n\t\t\t\tstr_append(aBuffer, \"/storage.cfg\", sizeof(aBuffer));\n\t\t\t\tFile = io_open(aBuffer, IOFLAG_READ);\n\t\t\t}\n\n\t\t\tif(Pos >= MAX_PATH_LENGTH || !File)\n\t\t\t{\n\t\t\t\tdbg_msg(\"storage\", \"couldn't open storage.cfg\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tchar *pLine;\n\t\tCLineReader LineReader;\n\t\tLineReader.Init(File);\n\n\t\twhile((pLine = LineReader.Get()))\n\t\t{\n\t\t\tif(str_length(pLine) > 9 && !str_comp_num(pLine, \"add_path \", 9))\n\t\t\t\tAddPath(pLine+9);\n\t\t}\n\n\t\tio_close(File);\n\n\t\tif(!m_NumPaths)\n\t\t\tdbg_msg(\"storage\", \"no paths found in storage.cfg\");\n\t}\n\n\tvoid AddDefaultPaths()\n\t{\n\t\tAddPath(\"$USERDIR\");\n\t\tAddPath(\"$DATADIR\");\n\t\tAddPath(\"$CURRENTDIR\");\n\t}\n\n\tvoid AddPath(const char *pPath)\n\t{\n\t\tif(m_NumPaths >= MAX_PATHS || !pPath[0])\n\t\t\treturn;\n\n\t\tif(!str_comp(pPath, \"$USERDIR\"))\n\t\t{\n\t\t\tif(m_aUserdir[0])\n\t\t\t{\n\t\t\t\tstr_copy(m_aaStoragePaths[m_NumPaths++], m_aUserdir, MAX_PATH_LENGTH);\n\t\t\t\tdbg_msg(\"storage\", \"added path '$USERDIR' ('%s')\", m_aUserdir);\n\t\t\t}\n\t\t}\n\t\telse if(!str_comp(pPath, \"$DATADIR\"))\n\t\t{\n\t\t\tif(m_aDatadir[0])\n\t\t\t{\n\t\t\t\tstr_copy(m_aaStoragePaths[m_NumPaths++], m_aDatadir, MAX_PATH_LENGTH);\n\t\t\t\tdbg_msg(\"storage\", \"added path '$DATADIR' ('%s')\", m_aDatadir);\n\t\t\t}\n\t\t}\n\t\telse if(!str_comp(pPath, \"$CURRENTDIR\"))\n\t\t{\n\t\t\tm_aaStoragePaths[m_NumPaths++][0] = 0;\n\t\t\tdbg_msg(\"storage\", \"added path '$CURRENTDIR' ('%s')\", m_aCurrentdir);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(fs_is_dir(pPath))\n\t\t\t{\n\t\t\t\tstr_copy(m_aaStoragePaths[m_NumPaths++], pPath, MAX_PATH_LENGTH);\n\t\t\t\tdbg_msg(\"storage\", \"added path '%s'\", pPath);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid FindDatadir(const char *pArgv0)\n\t{\n\t\t// 1) use data-dir in PWD if present\n\t\tif(fs_is_dir(\"data/mapres\"))\n\t\t{\n\t\t\tstr_copy(m_aDatadir, \"data\", sizeof(m_aDatadir));\n\t\t\treturn;\n\t\t}\n\n\t\t// 2) use compiled-in data-dir if present\n\t\tif(fs_is_dir(DATA_DIR \"/mapres\"))\n\t\t{\n\t\t\tstr_copy(m_aDatadir, DATA_DIR, sizeof(m_aDatadir));\n\t\t\treturn;\n\t\t}\n\n\t\t// 3) check for usable path in argv[0]\n\t\t{\n\t\t\tunsigned int Pos = ~0U;\n\t\t\tfor(unsigned i = 0; pArgv0[i]; i++)\n\t\t\t\tif(pArgv0[i] == '/' || pArgv0[i] == '\\\\')\n\t\t\t\t\tPos = i;\n\n\t\t\tif(Pos < MAX_PATH_LENGTH)\n\t\t\t{\n\t\t\t\tchar aBaseDir[MAX_PATH_LENGTH];\n\t\t\t\tstr_copy(aBaseDir, pArgv0, Pos+1);\n\t\t\t\tstr_format(m_aDatadir, sizeof(m_aDatadir), \"%s/data\", aBaseDir);\n\t\t\t\tstr_append(aBaseDir, \"/data/mapres\", sizeof(aBaseDir));\n\n\t\t\t\tif(fs_is_dir(aBaseDir))\n\t\t\t\t\treturn;\n\t\t\t\telse\n\t\t\t\t\tm_aDatadir[0] = 0;\n\t\t\t}\n\t\t}\n\n\t#if defined(CONF_FAMILY_UNIX)\n\t\t// 4) check for all default locations\n\t\t{\n\t\t\tconst char *aDirs[] = {\n\t\t\t\t\"/usr/share/teeworlds/data\",\n\t\t\t\t\"/usr/share/games/teeworlds/data\",\n\t\t\t\t\"/usr/local/share/teeworlds/data\",\n\t\t\t\t\"/usr/local/share/games/teeworlds/data\",\n\t\t\t\t\"/opt/teeworlds/data\"\n\t\t\t};\n\t\t\tconst int DirsCount = sizeof(aDirs) / sizeof(aDirs[0]);\n\n\t\t\tint i;\n\t\t\tfor (i = 0; i < DirsCount; i++)\n\t\t\t{\n\t\t\t\tchar aBuf[128];\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"%s/mapres\", aDirs[i]);\n\t\t\t\tif(fs_is_dir(aBuf))\n\t\t\t\t{\n\t\t\t\t\tstr_copy(m_aDatadir, aDirs[i], sizeof(m_aDatadir));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t#endif\n\n\t\t// no data-dir found\n\t\tdbg_msg(\"storage\", \"warning no data directory found\");\n\t}\n\n\tvirtual void ListDirectory(int Type, const char *pPath, FS_LISTDIR_CALLBACK pfnCallback, void *pUser)\n\t{\n\t\tchar aBuffer[MAX_PATH_LENGTH];\n\t\tif(Type == TYPE_ALL)\n\t\t{\n\t\t\t// list all available directories\n\t\t\tfor(int i = 0; i < m_NumPaths; ++i)\n\t\t\t\tfs_listdir(GetPath(i, pPath, aBuffer, sizeof(aBuffer)), pfnCallback, i, pUser);\n\t\t}\n\t\telse if(Type >= 0 && Type < m_NumPaths)\n\t\t{\n\t\t\t// list wanted directory\n\t\t\tfs_listdir(GetPath(Type, pPath, aBuffer, sizeof(aBuffer)), pfnCallback, Type, pUser);\n\t\t}\n\t}\n\n\tconst char *GetPath(int Type, const char *pDir, char *pBuffer, unsigned BufferSize)\n\t{\n\t\tstr_format(pBuffer, BufferSize, \"%s%s%s\", m_aaStoragePaths[Type], !m_aaStoragePaths[Type][0] ? \"\" : \"/\", pDir);\n\t\treturn pBuffer;\n\t}\n\n\tvirtual IOHANDLE OpenFile(const char *pFilename, int Flags, int Type, char *pBuffer = 0, int BufferSize = 0)\n\t{\n\t\tchar aBuffer[MAX_PATH_LENGTH];\n\t\tif(!pBuffer)\n\t\t{\n\t\t\tpBuffer = aBuffer;\n\t\t\tBufferSize = sizeof(aBuffer);\n\t\t}\n\n\t\tif(Flags&IOFLAG_WRITE)\n\t\t{\n\t\t\treturn io_open(GetPath(TYPE_SAVE, pFilename, pBuffer, BufferSize), Flags);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tIOHANDLE Handle = 0;\n\n\t\t\tif(Type == TYPE_ALL)\n\t\t\t{\n\t\t\t\t// check all available directories\n\t\t\t\tfor(int i = 0; i < m_NumPaths; ++i)\n\t\t\t\t{\n\t\t\t\t\tHandle = io_open(GetPath(i, pFilename, pBuffer, BufferSize), Flags);\n\t\t\t\t\tif(Handle)\n\t\t\t\t\t\treturn Handle;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(Type >= 0 && Type < m_NumPaths)\n\t\t\t{\n\t\t\t\t// check wanted directory\n\t\t\t\tHandle = io_open(GetPath(Type, pFilename, pBuffer, BufferSize), Flags);\n\t\t\t\tif(Handle)\n\t\t\t\t\treturn Handle;\n\t\t\t}\n\t\t}\n\n\t\tpBuffer[0] = 0;\n\t\treturn 0;\n\t}\n\n\tstruct CFindCBData\n\t{\n\t\tCStorage *pStorage;\n\t\tconst char *pFilename;\n\t\tconst char *pPath;\n\t\tchar *pBuffer;\n\t\tint BufferSize;\n\t};\n\n\tstatic int FindFileCallback(const char *pName, int IsDir, int Type, void *pUser)\n\t{\n\t\tCFindCBData Data = *static_cast<CFindCBData *>(pUser);\n\t\tif(IsDir)\n\t\t{\n\t\t\tif(pName[0] == '.')\n\t\t\t\treturn 0;\n\n\t\t\t// search within the folder\n\t\t\tchar aBuf[MAX_PATH_LENGTH];\n\t\t\tchar aPath[MAX_PATH_LENGTH];\n\t\t\tstr_format(aPath, sizeof(aPath), \"%s/%s\", Data.pPath, pName);\n\t\t\tData.pPath = aPath;\n\t\t\tfs_listdir(Data.pStorage->GetPath(Type, aPath, aBuf, sizeof(aBuf)), FindFileCallback, Type, &Data);\n\t\t\tif(Data.pBuffer[0])\n\t\t\t\treturn 1;\n\t\t}\n\t\telse if(!str_comp(pName, Data.pFilename))\n\t\t{\n\t\t\t// found the file = end\n\t\t\tstr_format(Data.pBuffer, Data.BufferSize, \"%s/%s\", Data.pPath, Data.pFilename);\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tvirtual bool FindFile(const char *pFilename, const char *pPath, int Type, char *pBuffer, int BufferSize)\n\t{\n\t\tif(BufferSize < 1)\n\t\t\treturn false;\n\n\t\tpBuffer[0] = 0;\n\t\tchar aBuf[MAX_PATH_LENGTH];\n\t\tCFindCBData Data;\n\t\tData.pStorage = this;\n\t\tData.pFilename = pFilename;\n\t\tData.pPath = pPath;\n\t\tData.pBuffer = pBuffer;\n\t\tData.BufferSize = BufferSize;\n\n\t\tif(Type == TYPE_ALL)\n\t\t{\n\t\t\t// search within all available directories\n\t\t\tfor(int i = 0; i < m_NumPaths; ++i)\n\t\t\t{\n\t\t\t\tfs_listdir(GetPath(i, pPath, aBuf, sizeof(aBuf)), FindFileCallback, i, &Data);\n\t\t\t\tif(pBuffer[0])\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse if(Type >= 0 && Type < m_NumPaths)\n\t\t{\n\t\t\t// search within wanted directory\n\t\t\tfs_listdir(GetPath(Type, pPath, aBuf, sizeof(aBuf)), FindFileCallback, Type, &Data);\n\t\t}\n\n\t\treturn pBuffer[0] != 0;\n\t}\n\n\tvirtual bool RemoveFile(const char *pFilename, int Type)\n\t{\n\t\tif(Type < 0 || Type >= m_NumPaths)\n\t\t\treturn false;\n\n\t\tchar aBuffer[MAX_PATH_LENGTH];\n\t\treturn !fs_remove(GetPath(Type, pFilename, aBuffer, sizeof(aBuffer)));\n\t}\n\n\tvirtual bool RenameFile(const char* pOldFilename, const char* pNewFilename, int Type)\n\t{\n\t\tif(Type < 0 || Type >= m_NumPaths)\n\t\t\treturn false;\n\t\tchar aOldBuffer[MAX_PATH_LENGTH];\n\t\tchar aNewBuffer[MAX_PATH_LENGTH];\n\t\treturn !fs_rename(GetPath(Type, pOldFilename, aOldBuffer, sizeof(aOldBuffer)), GetPath(Type, pNewFilename, aNewBuffer, sizeof (aNewBuffer)));\n\t}\n\n\tvirtual bool CreateFolder(const char *pFoldername, int Type)\n\t{\n\t\tif(Type < 0 || Type >= m_NumPaths)\n\t\t\treturn false;\n\n\t\tchar aBuffer[MAX_PATH_LENGTH];\n\t\treturn !fs_makedir(GetPath(Type, pFoldername, aBuffer, sizeof(aBuffer)));\n\t}\n\n\tvirtual void GetCompletePath(int Type, const char *pDir, char *pBuffer, unsigned BufferSize)\n\t{\n\t\tif(Type < 0 || Type >= m_NumPaths)\n\t\t{\n\t\t\tif(BufferSize > 0)\n\t\t\t\tpBuffer[0] = 0;\n\t\t\treturn;\n\t\t}\n\n\t\tGetPath(Type, pDir, pBuffer, BufferSize);\n\t}\n\n\tstatic IStorage *Create(const char *pApplicationName, int StorageType, int NumArgs, const char **ppArguments)\n\t{\n\t\tCStorage *p = new CStorage();\n\t\tif(p && p->Init(pApplicationName, StorageType, NumArgs, ppArguments))\n\t\t{\n\t\t\tdbg_msg(\"storage\", \"initialisation failed\");\n\t\t\tdelete p;\n\t\t\tp = 0;\n\t\t}\n\t\treturn p;\n\t}\n};\n\nIStorage *CreateStorage(const char *pApplicationName, int StorageType, int NumArgs, const char **ppArguments) { return CStorage::Create(pApplicationName, StorageType, NumArgs, ppArguments); }\n"
  },
  {
    "path": "src/engine/sound.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_SOUND_H\n#define ENGINE_SOUND_H\n\n#include \"kernel.h\"\n\nclass ISound : public IInterface\n{\n\tMACRO_INTERFACE(\"sound\", 0)\npublic:\n\tenum\n\t{\n\t\tFLAG_LOOP=1,\n\t\tFLAG_POS=2,\n\t\tFLAG_ALL=3\n\t};\n\n\tclass CSampleHandle\n\t{\n\t\tfriend class ISound;\n\t\tint m_Id;\n\tpublic:\n\t\tCSampleHandle()\n\t\t: m_Id(-1)\n\t\t{}\n\n\t\tbool IsValid() const { return Id() >= 0; }\n\t\tint Id() const { return m_Id; }\n\t};\n\n\tvirtual bool IsSoundEnabled() = 0;\n\n\tvirtual CSampleHandle LoadWV(const char *pFilename) = 0;\n\n\tvirtual void SetChannel(int ChannelID, float Volume, float Panning) = 0;\n\tvirtual void SetListenerPos(float x, float y) = 0;\n\n\tvirtual int PlayAt(int ChannelID, CSampleHandle Sound, int Flags, float x, float y) = 0;\n\tvirtual int Play(int ChannelID, CSampleHandle Sound, int Flags) = 0;\n\tvirtual void Stop(CSampleHandle Sound) = 0;\n\tvirtual void StopAll() = 0;\n\nprotected:\n\tinline CSampleHandle CreateSampleHandle(int Index)\n\t{\n\t\tCSampleHandle Tex;\n\t\tTex.m_Id = Index;\n\t\treturn Tex;\n\t}\n};\n\n\nclass IEngineSound : public ISound\n{\n\tMACRO_INTERFACE(\"enginesound\", 0)\npublic:\n\tvirtual int Init() = 0;\n\tvirtual int Update() = 0;\n\tvirtual int Shutdown() = 0;\n};\n\nextern IEngineSound *CreateEngineSound();\n\n#endif\n"
  },
  {
    "path": "src/engine/storage.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_STORAGE_H\n#define ENGINE_STORAGE_H\n\n#include \"kernel.h\"\n\nclass IStorage : public IInterface\n{\n\tMACRO_INTERFACE(\"storage\", 0)\npublic:\n\tenum\n\t{\n\t\tTYPE_SAVE = 0,\n\t\tTYPE_ALL = -1,\n\n\t\tSTORAGETYPE_BASIC = 0,\n\t\tSTORAGETYPE_SERVER,\n\t\tSTORAGETYPE_CLIENT,\n\t};\n\n\tvirtual void ListDirectory(int Type, const char *pPath, FS_LISTDIR_CALLBACK pfnCallback, void *pUser) = 0;\n\tvirtual IOHANDLE OpenFile(const char *pFilename, int Flags, int Type, char *pBuffer = 0, int BufferSize = 0) = 0;\n\tvirtual bool FindFile(const char *pFilename, const char *pPath, int Type, char *pBuffer, int BufferSize) = 0;\n\tvirtual bool RemoveFile(const char *pFilename, int Type) = 0;\n\tvirtual bool RenameFile(const char* pOldFilename, const char* pNewFilename, int Type) = 0;\n\tvirtual bool CreateFolder(const char *pFoldername, int Type) = 0;\n\tvirtual void GetCompletePath(int Type, const char *pDir, char *pBuffer, unsigned BufferSize) = 0;\n};\n\nextern IStorage *CreateStorage(const char *pApplicationName, int StorageType, int NumArgs, const char **ppArguments);\n\n\n#endif\n"
  },
  {
    "path": "src/engine/textrender.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef ENGINE_TEXTRENDER_H\n#define ENGINE_TEXTRENDER_H\n#include \"kernel.h\"\n\nenum\n{\n\tTEXTFLAG_RENDER=1,\n\tTEXTFLAG_ALLOW_NEWLINE=2,\n\tTEXTFLAG_STOP_AT_END=4\n};\n\nclass CFont;\n\nclass CTextCursor\n{\npublic:\n\tint m_Flags;\n\tint m_LineCount;\n\tint m_CharCount;\n\tint m_MaxLines;\n\n\tfloat m_StartX;\n\tfloat m_StartY;\n\tfloat m_LineWidth;\n\tfloat m_X, m_Y;\n\n\tCFont *m_pFont;\n\tfloat m_FontSize;\n};\n\nclass ITextRender : public IInterface\n{\n\tMACRO_INTERFACE(\"textrender\", 0)\npublic:\n\tvirtual void SetCursor(CTextCursor *pCursor, float x, float y, float FontSize, int Flags) = 0;\n\n\tvirtual CFont *LoadFont(const char *pFilename) = 0;\n\tvirtual void DestroyFont(CFont *pFont) = 0;\n\n\tvirtual void SetDefaultFont(CFont *pFont) = 0;\n\n\t//\n\tvirtual void TextEx(CTextCursor *pCursor, const char *pText, int Length) = 0;\n\n\t// old foolish interface\n\tvirtual void TextColor(float r, float g, float b, float a) = 0;\n\tvirtual void TextOutlineColor(float r, float g, float b, float a) = 0;\n\tvirtual void Text(void *pFontSetV, float x, float y, float Size, const char *pText, int MaxWidth) = 0;\n\tvirtual float TextWidth(void *pFontSetV, float Size, const char *pText, int Length) = 0;\n\tvirtual int TextLineCount(void *pFontSetV, float Size, const char *pText, float LineWidth) = 0;\n};\n\nclass IEngineTextRender : public ITextRender\n{\n\tMACRO_INTERFACE(\"enginetextrender\", 0)\npublic:\n\tvirtual void Init() = 0;\n};\n\nextern IEngineTextRender *CreateEngineTextRender();\n\n#endif\n"
  },
  {
    "path": "src/game/client/animstate.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n\n#include <base/math.h>\n#include <game/generated/protocol.h>\n#include <game/generated/client_data.h>\n\n#include \"animstate.h\"\n\nstatic void AnimSeqEval(CAnimSequence *pSeq, float Time, CAnimKeyframe *pFrame)\n{\n\tif(pSeq->m_NumFrames == 0)\n\t{\n\t\tpFrame->m_Time = 0;\n\t\tpFrame->m_X = 0;\n\t\tpFrame->m_Y = 0;\n\t\tpFrame->m_Angle = 0;\n\t}\n\telse if(pSeq->m_NumFrames == 1)\n\t{\n\t\t*pFrame = pSeq->m_aFrames[0];\n\t}\n\telse\n\t{\n\t\t//time = max(0.0f, min(1.0f, time / duration)); // TODO: use clamp\n\t\tCAnimKeyframe *pFrame1 = 0;\n\t\tCAnimKeyframe *pFrame2 = 0;\n\t\tfloat Blend = 0.0f;\n\n\t\t// TODO: make this smarter.. binary search\n\t\tfor (int i = 1; i < pSeq->m_NumFrames; i++)\n\t\t{\n\t\t\tif (pSeq->m_aFrames[i-1].m_Time <= Time && pSeq->m_aFrames[i].m_Time >= Time)\n\t\t\t{\n\t\t\t\tpFrame1 = &pSeq->m_aFrames[i-1];\n\t\t\t\tpFrame2 = &pSeq->m_aFrames[i];\n\t\t\t\tBlend = (Time - pFrame1->m_Time) / (pFrame2->m_Time - pFrame1->m_Time);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (pFrame1 && pFrame2)\n\t\t{\n\t\t\tpFrame->m_Time = Time;\n\t\t\tpFrame->m_X = mix(pFrame1->m_X, pFrame2->m_X, Blend);\n\t\t\tpFrame->m_Y = mix(pFrame1->m_Y, pFrame2->m_Y, Blend);\n\t\t\tpFrame->m_Angle = mix(pFrame1->m_Angle, pFrame2->m_Angle, Blend);\n\t\t}\n\t}\n}\n\nstatic void AnimAddKeyframe(CAnimKeyframe *pSeq, CAnimKeyframe *pAdded, float Amount)\n{\n\tpSeq->m_X += pAdded->m_X*Amount;\n\tpSeq->m_Y += pAdded->m_Y*Amount;\n\tpSeq->m_Angle += pAdded->m_Angle*Amount;\n}\n\nstatic void AnimAdd(CAnimState *pState, CAnimState *pAdded, float Amount)\n{\n\tAnimAddKeyframe(pState->GetBody(), pAdded->GetBody(), Amount);\n\tAnimAddKeyframe(pState->GetBackFoot(), pAdded->GetBackFoot(), Amount);\n\tAnimAddKeyframe(pState->GetFrontFoot(), pAdded->GetFrontFoot(), Amount);\n\tAnimAddKeyframe(pState->GetAttach(), pAdded->GetAttach(), Amount);\n}\n\n\nvoid CAnimState::Set(CAnimation *pAnim, float Time)\n{\n\tAnimSeqEval(&pAnim->m_Body, Time, &m_Body);\n\tAnimSeqEval(&pAnim->m_BackFoot, Time, &m_BackFoot);\n\tAnimSeqEval(&pAnim->m_FrontFoot, Time, &m_FrontFoot);\n\tAnimSeqEval(&pAnim->m_Attach, Time, &m_Attach);\n}\n\nvoid CAnimState::Add(CAnimation *pAnim, float Time, float Amount)\n{\n\tCAnimState Add;\n\tAdd.Set(pAnim, Time);\n\tAnimAdd(this, &Add, Amount);\n}\n\nCAnimState *CAnimState::GetIdle()\n{\n\tstatic CAnimState State;\n\tstatic bool Init = true;\n\n\tif(Init)\n\t{\n\t\tState.Set(&g_pData->m_aAnimations[ANIM_BASE], 0);\n\t\tState.Add(&g_pData->m_aAnimations[ANIM_IDLE], 0, 1.0f);\n\t\tInit = false;\n\t}\n\n\treturn &State;\n}\n"
  },
  {
    "path": "src/game/client/animstate.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_ANIMSTATE_H\n#define GAME_CLIENT_ANIMSTATE_H\n\nclass CAnimState\n{\n\tCAnimKeyframe m_Body;\n\tCAnimKeyframe m_BackFoot;\n\tCAnimKeyframe m_FrontFoot;\n\tCAnimKeyframe m_Attach;\n\npublic:\n\tCAnimKeyframe *GetBody() { return &m_Body; };\n\tCAnimKeyframe *GetBackFoot() { return &m_BackFoot; };\n\tCAnimKeyframe *GetFrontFoot() { return &m_FrontFoot; };\n\tCAnimKeyframe *GetAttach() { return &m_Attach; };\n\tvoid Set(CAnimation *pAnim, float Time);\n\tvoid Add(CAnimation *pAdded, float Time, float Amount);\n\n\tstatic CAnimState *GetIdle();\n};\n\n#endif\n"
  },
  {
    "path": "src/game/client/component.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENT_H\n#define GAME_CLIENT_COMPONENT_H\n\n#include <engine/input.h>\n#include \"gameclient.h\"\n\nclass CComponent\n{\nprotected:\n\tfriend class CGameClient;\n\n\tCGameClient *m_pClient;\n\n\t// perhaps propagte pointers for these as well\n\tclass IKernel *Kernel() const { return m_pClient->Kernel(); }\n\tclass IGraphics *Graphics() const { return m_pClient->Graphics(); }\n\tclass ITextRender *TextRender() const { return m_pClient->TextRender(); }\n\tclass IClient *Client() const { return m_pClient->Client(); }\n\tclass IInput *Input() const { return m_pClient->Input(); }\n\tclass IStorage *Storage() const { return m_pClient->Storage(); }\n\tclass CUI *UI() const { return m_pClient->UI(); }\n\tclass ISound *Sound() const { return m_pClient->Sound(); }\n\tclass CRenderTools *RenderTools() const { return m_pClient->RenderTools(); }\n\tclass IConsole *Console() const { return m_pClient->Console(); }\n\tclass IDemoPlayer *DemoPlayer() const { return m_pClient->DemoPlayer(); }\n\tclass IDemoRecorder *DemoRecorder() const { return m_pClient->DemoRecorder(); }\n\tclass IServerBrowser *ServerBrowser() const { return m_pClient->ServerBrowser(); }\n\tclass CLayers *Layers() const { return m_pClient->Layers(); }\n\tclass CCollision *Collision() const { return m_pClient->Collision(); }\npublic:\n\tvirtual ~CComponent() {}\n\n\tvirtual void OnStateChange(int NewState, int OldState) {};\n\tvirtual void OnConsoleInit() {};\n\tvirtual void OnInit() {};\n\tvirtual void OnReset() {};\n\tvirtual void OnRender() {};\n\tvirtual void OnRelease() {};\n\tvirtual void OnMapLoad() {};\n\tvirtual void OnMessage(int Msg, void *pRawMsg) {}\n\tvirtual bool OnMouseMove(float x, float y) { return false; }\n\tvirtual bool OnInput(IInput::CEvent e) { return false; }\n};\n\n#endif\n"
  },
  {
    "path": "src/game/client/components/binds.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/config.h>\n#include <engine/shared/config.h>\n#include \"binds.h\"\n\nbool CBinds::CBindsSpecial::OnInput(IInput::CEvent Event)\n{\n\t// don't handle invalid events and keys that arn't set to anything\n\tif(Event.m_Key >= KEY_F1 && Event.m_Key <= KEY_F15 && m_pBinds->m_aaKeyBindings[Event.m_Key][0] != 0)\n\t{\n\t\tint Stroke = 0;\n\t\tif(Event.m_Flags&IInput::FLAG_PRESS)\n\t\t\tStroke = 1;\n\n\t\tm_pBinds->GetConsole()->ExecuteLineStroked(Stroke, m_pBinds->m_aaKeyBindings[Event.m_Key]);\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nCBinds::CBinds()\n{\n\tmem_zero(m_aaKeyBindings, sizeof(m_aaKeyBindings));\n\tm_SpecialBinds.m_pBinds = this;\n}\n\nvoid CBinds::Bind(int KeyID, const char *pStr)\n{\n\tif(KeyID < 0 || KeyID >= KEY_LAST)\n\t\treturn;\n\n\tstr_copy(m_aaKeyBindings[KeyID], pStr, sizeof(m_aaKeyBindings[KeyID]));\n\tchar aBuf[256];\n\tif(!m_aaKeyBindings[KeyID][0])\n\t\tstr_format(aBuf, sizeof(aBuf), \"unbound %s (%d)\", Input()->KeyName(KeyID), KeyID);\n\telse\n\t\tstr_format(aBuf, sizeof(aBuf), \"bound %s (%d) = %s\", Input()->KeyName(KeyID), KeyID, m_aaKeyBindings[KeyID]);\n\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"binds\", aBuf);\n}\n\n\nbool CBinds::OnInput(IInput::CEvent e)\n{\n\t// don't handle invalid events and keys that arn't set to anything\n\tif(e.m_Key <= 0 || e.m_Key >= KEY_LAST || m_aaKeyBindings[e.m_Key][0] == 0)\n\t\treturn false;\n\n\tint Stroke = 0;\n\tif(e.m_Flags&IInput::FLAG_PRESS)\n\t\tStroke = 1;\n\tConsole()->ExecuteLineStroked(Stroke, m_aaKeyBindings[e.m_Key]);\n\treturn true;\n}\n\nvoid CBinds::UnbindAll()\n{\n\tfor(int i = 0; i < KEY_LAST; i++)\n\t\tm_aaKeyBindings[i][0] = 0;\n}\n\nconst char *CBinds::Get(int KeyID)\n{\n\tif(KeyID > 0 && KeyID < KEY_LAST)\n\t\treturn m_aaKeyBindings[KeyID];\n\treturn \"\";\n}\n\nconst char *CBinds::GetKey(const char *pBindStr)\n{\n\tfor(int KeyId = 0; KeyId < KEY_LAST; KeyId++)\n\t{\n\t\tconst char *pBind = Get(KeyId);\n\t\tif(!pBind[0])\n\t\t\tcontinue;\n\n\t\tif(str_comp(pBind, pBindStr) == 0)\n\t\t\treturn Input()->KeyName(KeyId);\n\t}\n\n\treturn \"\";\n}\n\nvoid CBinds::SetDefaults()\n{\n\t// set default key bindings\n\tUnbindAll();\n\tBind(KEY_F1, \"toggle_local_console\");\n\tBind(KEY_F2, \"toggle_remote_console\");\n\tBind(KEY_TAB, \"+scoreboard\");\n\tBind('u', \"+show_chat\");\n\tBind(KEY_F10, \"screenshot\");\n\n\tBind('a', \"+left\");\n\tBind('d', \"+right\");\n\n\tBind(KEY_SPACE, \"+jump\");\n\tBind(KEY_MOUSE_1, \"+fire\");\n\tBind(KEY_MOUSE_2, \"+hook\");\n\tBind(KEY_LSHIFT, \"+emote\");\n\tBind(KEY_RSHIFT, \"+spectate\");\n\tBind(KEY_RIGHT, \"spectate_next\");\n\tBind(KEY_LEFT, \"spectate_previous\");\n\n\tBind('1', \"+weapon1\");\n\tBind('2', \"+weapon2\");\n\tBind('3', \"+weapon3\");\n\tBind('4', \"+weapon4\");\n\tBind('5', \"+weapon5\");\n\n\tBind(KEY_MOUSE_WHEEL_UP, \"+prevweapon\");\n\tBind(KEY_MOUSE_WHEEL_DOWN, \"+nextweapon\");\n\n\tBind('t', \"chat all\");\n\tBind('y', \"chat team\");\n\n\tBind(KEY_F3, \"vote yes\");\n\tBind(KEY_F4, \"vote no\");\n\n\tBind('r', \"ready_change\");\n}\n\nvoid CBinds::OnConsoleInit()\n{\n\t// bindings\n\tIConfig *pConfig = Kernel()->RequestInterface<IConfig>();\n\tif(pConfig)\n\t\tpConfig->RegisterCallback(ConfigSaveCallback, this);\n\n\tConsole()->Register(\"bind\", \"sr\", CFGFLAG_CLIENT, ConBind, this, \"Bind key to execute the command\");\n\tConsole()->Register(\"unbind\", \"s\", CFGFLAG_CLIENT, ConUnbind, this, \"Unbind key\");\n\tConsole()->Register(\"unbindall\", \"\", CFGFLAG_CLIENT, ConUnbindAll, this, \"Unbind all keys\");\n\tConsole()->Register(\"dump_binds\", \"\", CFGFLAG_CLIENT, ConDumpBinds, this, \"Dump binds\");\n\n\t// default bindings\n\tSetDefaults();\n}\n\nvoid CBinds::ConBind(IConsole::IResult *pResult, void *pUserData)\n{\n\tCBinds *pBinds = (CBinds *)pUserData;\n\tconst char *pKeyName = pResult->GetString(0);\n\tint id = pBinds->GetKeyID(pKeyName);\n\n\tif(!id)\n\t{\n\t\tchar aBuf[256];\n\t\tstr_format(aBuf, sizeof(aBuf), \"key %s not found\", pKeyName);\n\t\tpBinds->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"binds\", aBuf);\n\t\treturn;\n\t}\n\n\tpBinds->Bind(id, pResult->GetString(1));\n}\n\n\nvoid CBinds::ConUnbind(IConsole::IResult *pResult, void *pUserData)\n{\n\tCBinds *pBinds = (CBinds *)pUserData;\n\tconst char *pKeyName = pResult->GetString(0);\n\tint id = pBinds->GetKeyID(pKeyName);\n\n\tif(!id)\n\t{\n\t\tchar aBuf[256];\n\t\tstr_format(aBuf, sizeof(aBuf), \"key %s not found\", pKeyName);\n\t\tpBinds->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"binds\", aBuf);\n\t\treturn;\n\t}\n\n\tpBinds->Bind(id, \"\");\n}\n\n\nvoid CBinds::ConUnbindAll(IConsole::IResult *pResult, void *pUserData)\n{\n\tCBinds *pBinds = (CBinds *)pUserData;\n\tpBinds->UnbindAll();\n}\n\n\nvoid CBinds::ConDumpBinds(IConsole::IResult *pResult, void *pUserData)\n{\n\tCBinds *pBinds = (CBinds *)pUserData;\n\tchar aBuf[1024];\n\tfor(int i = 0; i < KEY_LAST; i++)\n\t{\n\t\tif(pBinds->m_aaKeyBindings[i][0] == 0)\n\t\t\tcontinue;\n\t\tstr_format(aBuf, sizeof(aBuf), \"%s (%d) = %s\", pBinds->Input()->KeyName(i), i, pBinds->m_aaKeyBindings[i]);\n\t\tpBinds->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"binds\", aBuf);\n\t}\n}\n\nint CBinds::GetKeyID(const char *pKeyName)\n{\n\t// check for numeric\n\tif(pKeyName[0] == '&')\n\t{\n\t\tint i = str_toint(pKeyName+1);\n\t\tif(i > 0 && i < KEY_LAST)\n\t\t\treturn i; // numeric\n\t}\n\n\t// search for key\n\tfor(int i = 0; i < KEY_LAST; i++)\n\t{\n\t\tif(str_comp(pKeyName, Input()->KeyName(i)) == 0)\n\t\t\treturn i;\n\t}\n\n\treturn 0;\n}\n\nvoid CBinds::ConfigSaveCallback(IConfig *pConfig, void *pUserData)\n{\n\tCBinds *pSelf = (CBinds *)pUserData;\n\n\tchar aBuffer[256];\n\tchar *pEnd = aBuffer+sizeof(aBuffer)-8;\n\tpConfig->WriteLine(\"unbindall\");\n\tfor(int i = 0; i < KEY_LAST; i++)\n\t{\n\t\tif(pSelf->m_aaKeyBindings[i][0] == 0)\n\t\t\tcontinue;\n\t\tstr_format(aBuffer, sizeof(aBuffer), \"bind %s \", pSelf->Input()->KeyName(i));\n\n\t\t// process the string. we need to escape some characters\n\t\tconst char *pSrc = pSelf->m_aaKeyBindings[i];\n\t\tchar *pDst = aBuffer + str_length(aBuffer);\n\t\t*pDst++ = '\"';\n\t\twhile(*pSrc && pDst < pEnd)\n\t\t{\n\t\t\tif(*pSrc == '\"' || *pSrc == '\\\\') // escape \\ and \"\n\t\t\t\t*pDst++ = '\\\\';\n\t\t\t*pDst++ = *pSrc++;\n\t\t}\n\t\t*pDst++ = '\"';\n\t\t*pDst++ = 0;\n\n\t\tpConfig->WriteLine(aBuffer);\n\t}\n}\n"
  },
  {
    "path": "src/game/client/components/binds.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_BINDS_H\n#define GAME_CLIENT_COMPONENTS_BINDS_H\n#include <game/client/component.h>\n#include <engine/keys.h>\n\nclass CBinds : public CComponent\n{\n\tchar m_aaKeyBindings[KEY_LAST][128];\n\n\tint GetKeyID(const char *pKeyName);\n\n\tstatic void ConBind(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConUnbind(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConUnbindAll(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConDumpBinds(IConsole::IResult *pResult, void *pUserData);\n\tclass IConsole *GetConsole() const { return Console(); }\n\n\tstatic void ConfigSaveCallback(class IConfig *pConfig, void *pUserData);\n\npublic:\n\tCBinds();\n\n\tclass CBindsSpecial : public CComponent\n\t{\n\tpublic:\n\t\tCBinds *m_pBinds;\n\t\tvirtual bool OnInput(IInput::CEvent Event);\n\t};\n\n\tCBindsSpecial m_SpecialBinds;\n\n\tvoid Bind(int KeyID, const char *pStr);\n\tvoid SetDefaults();\n\tvoid UnbindAll();\n\tconst char *Get(int KeyID);\n\tconst char *GetKey(const char *pBindStr);\n\n\tvirtual void OnConsoleInit();\n\tvirtual bool OnInput(IInput::CEvent Event);\n};\n#endif\n"
  },
  {
    "path": "src/game/client/components/broadcast.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/shared/config.h>\n#include <engine/graphics.h>\n#include <engine/textrender.h>\n#include <game/generated/protocol.h>\n#include <game/generated/client_data.h>\n\n#include <game/client/gameclient.h>\n\n#include <game/client/components/motd.h>\n#include <game/client/components/scoreboard.h>\n\n#include \"broadcast.h\"\n\n\nCBroadcast::CBroadcast()\n{\n\tOnReset();\n}\n\nvoid CBroadcast::DoBroadcast(const char *pText)\n{\n\tstr_copy(m_aBroadcastText, pText, sizeof(m_aBroadcastText));\n\tCTextCursor Cursor;\n\tTextRender()->SetCursor(&Cursor, 0, 0, 12.0f, TEXTFLAG_STOP_AT_END);\n\tCursor.m_LineWidth = 300*Graphics()->ScreenAspect();\n\tTextRender()->TextEx(&Cursor, m_aBroadcastText, -1);\n\tm_BroadcastRenderOffset = 150*Graphics()->ScreenAspect()-Cursor.m_X/2;\n\tm_BroadcastTime = time_get()+time_freq()*10;\n}\n\nvoid CBroadcast::OnReset()\n{\n\tm_BroadcastTime = 0;\n}\n\nvoid CBroadcast::OnRender()\n{\n\tif(m_pClient->m_pScoreboard->Active() || m_pClient->m_pMotd->IsActive())\n\t\treturn;\n\n\tGraphics()->MapScreen(0, 0, 300*Graphics()->ScreenAspect(), 300);\n\n\tif(time_get() < m_BroadcastTime)\n\t{\n\t\tCTextCursor Cursor;\n\t\tTextRender()->SetCursor(&Cursor, m_BroadcastRenderOffset, 40.0f, 12.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\t\tCursor.m_LineWidth = 300*Graphics()->ScreenAspect()-m_BroadcastRenderOffset;\n\t\tTextRender()->TextEx(&Cursor, m_aBroadcastText, -1);\n\t}\n}\n\n"
  },
  {
    "path": "src/game/client/components/broadcast.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_BROADCAST_H\n#define GAME_CLIENT_COMPONENTS_BROADCAST_H\n#include <game/client/component.h>\n\nclass CBroadcast : public CComponent\n{\n\tchar m_aBroadcastText[128];\n\tint64 m_BroadcastTime;\n\tfloat m_BroadcastRenderOffset;\n\npublic:\n\tCBroadcast();\n\n\tvoid DoBroadcast(const char *pText);\n\n\tvirtual void OnReset();\n\tvirtual void OnRender();\n};\n\n#endif\n"
  },
  {
    "path": "src/game/client/components/camera.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/shared/config.h>\n\n#include <base/math.h>\n#include <game/collision.h>\n#include <game/client/gameclient.h>\n#include <game/client/component.h>\n\n#include \"camera.h\"\n#include \"controls.h\"\n\nCCamera::CCamera()\n{\n\tm_CamType = CAMTYPE_UNDEFINED;\n\tm_RotationCenter = vec2(0.0f, 0.0f);\n\tm_MenuCenter = vec2(0.0f, 0.0f);\n\n\tm_Positions[POS_START] = vec2(500.0f, 500.0f);\n\tm_Positions[POS_INTERNET] = vec2(500.0f, 500.0f);\n\tm_Positions[POS_LAN] = vec2(1000.0f, 1000.0f);\n\tm_Positions[POS_FAVORITES] = vec2(2000.0f, 500.0f);\n\tm_Positions[POS_DEMOS] = vec2(1500.0f, 1000.0f);\n\tm_Positions[POS_SETTINGS] = vec2(1000.0f, 500.0f);\n\n\tm_CurrentPosition = -1;\n}\n\nvoid CCamera::OnRender()\n{\n\tif(Client()->State() == IClient::STATE_ONLINE || Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tm_Zoom = 1.0f;\n\n\t\t// update camera center\n\t\tif(m_pClient->m_Snap.m_SpecInfo.m_Active && !m_pClient->m_Snap.m_SpecInfo.m_UsePosition)\n\t\t{\n\t\t\tif(m_CamType != CAMTYPE_SPEC)\n\t\t\t{\n\t\t\t\tm_pClient->m_pControls->m_MousePos = m_PrevCenter;\n\t\t\t\tm_pClient->m_pControls->ClampMousePos();\n\t\t\t\tm_CamType = CAMTYPE_SPEC;\n\t\t\t}\n\t\t\tm_Center = m_pClient->m_pControls->m_MousePos;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(m_CamType != CAMTYPE_PLAYER)\n\t\t\t{\n\t\t\t\tm_pClient->m_pControls->ClampMousePos();\n\t\t\t\tm_CamType = CAMTYPE_PLAYER;\n\t\t\t}\n\n\t\t\tvec2 CameraOffset(0, 0);\n\n\t\t\tfloat l = length(m_pClient->m_pControls->m_MousePos);\n\t\t\tif(l > 0.0001f) // make sure that this isn't 0\n\t\t\t{\n\t\t\t\tfloat DeadZone = g_Config.m_ClMouseDeadzone;\n\t\t\t\tfloat FollowFactor = g_Config.m_ClMouseFollowfactor/100.0f;\n\t\t\t\tfloat OffsetAmount = max(l-DeadZone, 0.0f) * FollowFactor;\n\n\t\t\t\tCameraOffset = normalize(m_pClient->m_pControls->m_MousePos)*OffsetAmount;\n\t\t\t}\n\n\t\t\tif(m_pClient->m_Snap.m_SpecInfo.m_Active)\n\t\t\t\tm_Center = m_pClient->m_Snap.m_SpecInfo.m_Position + CameraOffset;\n\t\t\telse\n\t\t\t\tm_Center = m_pClient->m_LocalCharacterPos + CameraOffset;\n\t\t}\n\t}\n\telse\n\t{\n\t\tm_Zoom = 0.7f;\n\t\tstatic vec2 Dir = vec2(1.0f, 0.0f);\n\n\t\tif(distance(m_Center, m_RotationCenter) <= (float)g_Config.m_ClRotationRadius+0.5f)\n\t\t{\n\t\t\t// do little rotation\n\t\t\tfloat RotPerTick = 360.0f/(float)g_Config.m_ClRotationSpeed * Client()->RenderFrameTime();\n\t\t\tDir = rotate(Dir, RotPerTick);\n\t\t\tm_Center = m_RotationCenter+Dir*(float)g_Config.m_ClRotationRadius;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tDir = normalize(m_RotationCenter-m_Center);\n\t\t\tm_Center += Dir*(500.0f*Client()->RenderFrameTime());\n\t\t\tDir = normalize(m_Center-m_RotationCenter);\n\t\t}\n\t}\n\n\tm_PrevCenter = m_Center;\n}\n\nvoid CCamera::ChangePosition(int PositionNumber)\n{\n\tm_RotationCenter = m_Positions[PositionNumber];\n\tm_CurrentPosition = PositionNumber;\n}\n\nint CCamera::GetCurrentPosition()\n{\n\treturn m_CurrentPosition;\n}\n\nvoid CCamera::ConSetPosition(IConsole::IResult *pResult, void *pUserData)\n{\n\tCCamera *pSelf = (CCamera *)pUserData;\n\tint PositionNumber = clamp(pResult->GetInteger(0), 0, 4);\n\tvec2 Position = vec2(pResult->GetInteger(1)*32.0f+16.0f, pResult->GetInteger(2)*32.0f+16.0f);\n\tpSelf->m_Positions[PositionNumber] = Position;\n\n\t// update\n\tif(pSelf->GetCurrentPosition() == PositionNumber)\n\t\tpSelf->ChangePosition(PositionNumber);\n}\n\nvoid CCamera::OnConsoleInit()\n{\n\tConsole()->Register(\"set_position\", \"iii\", CFGFLAG_CLIENT, ConSetPosition, this, \"Sets the rotation position\");\n}\n\nvoid CCamera::OnStateChange(int NewState, int OldState)\n{\n\tif(OldState == IClient::STATE_OFFLINE)\n\t\tm_MenuCenter = m_Center;\n\telse if(NewState != IClient::STATE_ONLINE && Client()->State() != IClient::STATE_DEMOPLAYBACK)\n\t\tm_Center = m_MenuCenter;\n}\n"
  },
  {
    "path": "src/game/client/components/camera.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_CAMERA_H\n#define GAME_CLIENT_COMPONENTS_CAMERA_H\n#include <base/vmath.h>\n#include <game/client/component.h>\n\nclass CCamera : public CComponent\n{\npublic:\n\tenum\n\t{\n\t\tPOS_START=0,\n\t\tPOS_INTERNET,\n\t\tPOS_LAN,\n\t\tPOS_FAVORITES,\n\t\tPOS_DEMOS,\n\t\tPOS_SETTINGS,\n\n\t\tNUM_POS,\n\t};\n\n\tvec2 m_Center;\n\tvec2 m_MenuCenter;\n\tvec2 m_RotationCenter;\n\tfloat m_Zoom;\n\n\tCCamera();\n\tvirtual void OnRender();\n\n\tvoid ChangePosition(int PositionNumber);\n\tint GetCurrentPosition();\n\n\tstatic void ConSetPosition(IConsole::IResult *pResult, void *pUserData);\n\n\tvirtual void OnConsoleInit();\n\tvirtual void OnStateChange(int NewState, int OldState);\n\npublic:\n\tenum\n\t{\n\t\tCAMTYPE_UNDEFINED=-1,\n\t\tCAMTYPE_SPEC,\n\t\tCAMTYPE_PLAYER,\n\t};\n\n\tint m_CamType;\n\tvec2 m_PrevCenter;\n\tvec2 m_Positions[NUM_POS];\n\tint m_CurrentPosition;\n};\n\n#endif\n"
  },
  {
    "path": "src/game/client/components/chat.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n\n#include <engine/engine.h>\n#include <engine/graphics.h>\n#include <engine/textrender.h>\n#include <engine/keys.h>\n#include <engine/shared/config.h>\n\n#include <game/generated/protocol.h>\n#include <game/generated/client_data.h>\n\n#include <game/client/gameclient.h>\n#include <game/client/localization.h>\n\n#include <game/client/components/scoreboard.h>\n#include <game/client/components/sounds.h>\n\n#include \"menus.h\"\n#include \"chat.h\"\n\n\nCChat::CChat()\n{\n\tOnReset();\n}\n\nvoid CChat::OnReset()\n{\n\tfor(int i = 0; i < MAX_LINES; i++)\n\t{\n\t\tm_aLines[i].m_Time = 0;\n\t\tm_aLines[i].m_aText[0] = 0;\n\t\tm_aLines[i].m_aName[0] = 0;\n\t}\n\n\tm_Show = false;\n\tm_InputUpdate = false;\n\tm_ChatStringOffset = 0;\n\tm_CompletionChosen = -1;\n\tm_aCompletionBuffer[0] = 0;\n\tm_PlaceholderOffset = 0;\n\tm_PlaceholderLength = 0;\n\tm_pHistoryEntry = 0x0;\n\tm_PendingChatCounter = 0;\n\tm_LastChatSend = 0;\n\n\tfor(int i = 0; i < CHAT_NUM; ++i)\n\t\tm_aLastSoundPlayed[i] = 0;\n}\n\nvoid CChat::OnRelease()\n{\n\tm_Show = false;\n}\n\nvoid CChat::OnStateChange(int NewState, int OldState)\n{\n\tif(OldState <= IClient::STATE_CONNECTING)\n\t{\n\t\tm_Mode = MODE_NONE;\n\t\tfor(int i = 0; i < MAX_LINES; i++)\n\t\t\tm_aLines[i].m_Time = 0;\n\t\tm_CurrentLine = 0;\n\t}\n}\n\nvoid CChat::ConSay(IConsole::IResult *pResult, void *pUserData)\n{\n\t((CChat*)pUserData)->Say(0, pResult->GetString(0));\n}\n\nvoid CChat::ConSayTeam(IConsole::IResult *pResult, void *pUserData)\n{\n\t((CChat*)pUserData)->Say(1, pResult->GetString(0));\n}\n\nvoid CChat::ConChat(IConsole::IResult *pResult, void *pUserData)\n{\n\tconst char *pMode = pResult->GetString(0);\n\tif(str_comp(pMode, \"all\") == 0)\n\t\t((CChat*)pUserData)->EnableMode(0);\n\telse if(str_comp(pMode, \"team\") == 0)\n\t\t((CChat*)pUserData)->EnableMode(1);\n\telse\n\t\t((CChat*)pUserData)->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"console\", \"expected all or team as mode\");\n}\n\nvoid CChat::ConShowChat(IConsole::IResult *pResult, void *pUserData)\n{\n\t((CChat *)pUserData)->m_Show = pResult->GetInteger(0) != 0;\n}\n\nvoid CChat::OnConsoleInit()\n{\n\tConsole()->Register(\"say\", \"r\", CFGFLAG_CLIENT, ConSay, this, \"Say in chat\");\n\tConsole()->Register(\"say_team\", \"r\", CFGFLAG_CLIENT, ConSayTeam, this, \"Say in team chat\");\n\tConsole()->Register(\"chat\", \"s\", CFGFLAG_CLIENT, ConChat, this, \"Enable chat with all/team mode\");\n\tConsole()->Register(\"+show_chat\", \"\", CFGFLAG_CLIENT, ConShowChat, this, \"Show chat\");\n}\n\nbool CChat::OnInput(IInput::CEvent Event)\n{\n\tif(m_Mode == MODE_NONE)\n\t\treturn false;\n\n\tif(Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_ESCAPE)\n\t{\n\t\tm_Mode = MODE_NONE;\n\t\tm_pClient->OnRelease();\n\t}\n\telse if(Event.m_Flags&IInput::FLAG_PRESS && (Event.m_Key == KEY_RETURN || Event.m_Key == KEY_KP_ENTER))\n\t{\n\t\tif(m_Input.GetString()[0])\n\t\t{\n\t\t\tbool AddEntry = false;\n\n\t\t\tif(m_LastChatSend+time_freq() < time_get())\n\t\t\t{\n\t\t\t\tSay(m_Mode == MODE_ALL ? 0 : 1, m_Input.GetString());\n\t\t\t\tAddEntry = true;\n\t\t\t}\n\t\t\telse if(m_PendingChatCounter < 3)\n\t\t\t{\n\t\t\t\t++m_PendingChatCounter;\n\t\t\t\tAddEntry = true;\n\t\t\t}\n\n\t\t\tif(AddEntry)\n\t\t\t{\n\t\t\t\tCHistoryEntry *pEntry = m_History.Allocate(sizeof(CHistoryEntry)+m_Input.GetLength());\n\t\t\t\tpEntry->m_Team = m_Mode == MODE_ALL ? 0 : 1;\n\t\t\t\tmem_copy(pEntry->m_aText, m_Input.GetString(), m_Input.GetLength()+1);\n\t\t\t}\n\t\t}\n\t\tm_pHistoryEntry = 0x0;\n\t\tm_Mode = MODE_NONE;\n\t\tm_pClient->OnRelease();\n\t}\n\tif(Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_TAB)\n\t{\n\t\t// fill the completion buffer\n\t\tif(m_CompletionChosen < 0)\n\t\t{\n\t\t\tconst char *pCursor = m_Input.GetString()+m_Input.GetCursorOffset();\n\t\t\tfor(int Count = 0; Count < m_Input.GetCursorOffset() && *(pCursor-1) != ' '; --pCursor, ++Count);\n\t\t\tm_PlaceholderOffset = pCursor-m_Input.GetString();\n\n\t\t\tfor(m_PlaceholderLength = 0; *pCursor && *pCursor != ' '; ++pCursor)\n\t\t\t\t++m_PlaceholderLength;\n\n\t\t\tstr_copy(m_aCompletionBuffer, m_Input.GetString()+m_PlaceholderOffset, min(static_cast<int>(sizeof(m_aCompletionBuffer)), m_PlaceholderLength+1));\n\t\t}\n\n\t\t// find next possible name\n\t\tconst char *pCompletionString = 0;\n\t\tm_CompletionChosen = (m_CompletionChosen+1)%(2*MAX_CLIENTS);\n\t\tfor(int i = 0; i < 2*MAX_CLIENTS; ++i)\n\t\t{\n\t\t\tint SearchType = ((m_CompletionChosen+i)%(2*MAX_CLIENTS))/MAX_CLIENTS;\n\t\t\tint Index = (m_CompletionChosen+i)%MAX_CLIENTS;\n\t\t\tif(!m_pClient->m_aClients[Index].m_Active)\n\t\t\t\tcontinue;\n\n\t\t\tbool Found = false;\n\t\t\tif(SearchType == 1)\n\t\t\t{\n\t\t\t\tif(str_comp_nocase_num(m_pClient->m_aClients[Index].m_aName, m_aCompletionBuffer, str_length(m_aCompletionBuffer)) &&\n\t\t\t\t\tstr_find_nocase(m_pClient->m_aClients[Index].m_aName, m_aCompletionBuffer))\n\t\t\t\t\tFound = true;\n\t\t\t}\n\t\t\telse if(!str_comp_nocase_num(m_pClient->m_aClients[Index].m_aName, m_aCompletionBuffer, str_length(m_aCompletionBuffer)))\n\t\t\t\tFound = true;\n\n\t\t\tif(Found)\n\t\t\t{\n\t\t\t\tpCompletionString = m_pClient->m_aClients[Index].m_aName;\n\t\t\t\tm_CompletionChosen = Index+SearchType*MAX_CLIENTS;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// insert the name\n\t\tif(pCompletionString)\n\t\t{\n\t\t\tchar aBuf[256];\n\t\t\t// add part before the name\n\t\t\tstr_copy(aBuf, m_Input.GetString(), min(static_cast<int>(sizeof(aBuf)), m_PlaceholderOffset+1));\n\n\t\t\t// add the name\n\t\t\tstr_append(aBuf, pCompletionString, sizeof(aBuf));\n\n\t\t\t// add seperator\n\t\t\tconst char *pSeparator = \"\";\n\t\t\tif(*(m_Input.GetString()+m_PlaceholderOffset+m_PlaceholderLength) != ' ')\n\t\t\t\tpSeparator = m_PlaceholderOffset == 0 ? \": \" : \" \";\n\t\t\telse if(m_PlaceholderOffset == 0)\n\t\t\t\tpSeparator = \":\";\n\t\t\tif(*pSeparator)\n\t\t\t\tstr_append(aBuf, pSeparator, sizeof(aBuf));\n\n\t\t\t// add part after the name\n\t\t\tstr_append(aBuf, m_Input.GetString()+m_PlaceholderOffset+m_PlaceholderLength, sizeof(aBuf));\n\n\t\t\tm_PlaceholderLength = str_length(pSeparator)+str_length(pCompletionString);\n\t\t\tm_OldChatStringLength = m_Input.GetLength();\n\t\t\tm_Input.Set(aBuf);\n\t\t\tm_Input.SetCursorOffset(m_PlaceholderOffset+m_PlaceholderLength);\n\t\t\tm_InputUpdate = true;\n\t\t}\n\t}\n\telse\n\t{\n\t\t// reset name completion process\n\t\tif(Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key != KEY_TAB)\n\t\t\tm_CompletionChosen = -1;\n\n\t\tm_OldChatStringLength = m_Input.GetLength();\n\t\tm_Input.ProcessInput(Event);\n\t\tm_InputUpdate = true;\n\t}\n\tif(Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_UP)\n\t{\n\t\tif(m_pHistoryEntry)\n\t\t{\n\t\t\tCHistoryEntry *pTest = m_History.Prev(m_pHistoryEntry);\n\n\t\t\tif(pTest)\n\t\t\t\tm_pHistoryEntry = pTest;\n\t\t}\n\t\telse\n\t\t\tm_pHistoryEntry = m_History.Last();\n\n\t\tif(m_pHistoryEntry)\n\t\t\tm_Input.Set(m_pHistoryEntry->m_aText);\n\t}\n\telse if (Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_DOWN)\n\t{\n\t\tif(m_pHistoryEntry)\n\t\t\tm_pHistoryEntry = m_History.Next(m_pHistoryEntry);\n\n\t\tif (m_pHistoryEntry)\n\t\t\tm_Input.Set(m_pHistoryEntry->m_aText);\n\t\telse\n\t\t\tm_Input.Clear();\n\t}\n\n\treturn true;\n}\n\n\nvoid CChat::EnableMode(int Team)\n{\n\tif(Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t\treturn;\n\n\tif(m_Mode == MODE_NONE)\n\t{\n\t\tif(Team)\n\t\t\tm_Mode = MODE_TEAM;\n\t\telse\n\t\t\tm_Mode = MODE_ALL;\n\n\t\tm_Input.Clear();\n\t\tInput()->ClearEvents();\n\t\tm_CompletionChosen = -1;\n\t}\n}\n\nvoid CChat::OnMessage(int MsgType, void *pRawMsg)\n{\n\tif(MsgType == NETMSGTYPE_SV_CHAT)\n\t{\n\t\tCNetMsg_Sv_Chat *pMsg = (CNetMsg_Sv_Chat *)pRawMsg;\n\t\tAddLine(pMsg->m_ClientID, pMsg->m_Team, pMsg->m_pMessage);\n\t}\n}\n\nvoid CChat::AddLine(int ClientID, int Team, const char *pLine)\n{\n\tif(*pLine == 0 || (ClientID != -1 && (m_pClient->m_aClients[ClientID].m_aName[0] == '\\0' || // unknown client\n\t\tm_pClient->m_aClients[ClientID].m_ChatIgnore ||\n\t\t(m_pClient->m_LocalClientID != ClientID && g_Config.m_ClShowChatFriends && !m_pClient->m_aClients[ClientID].m_Friend))))\n\t\treturn;\n\n\tbool Highlighted = false;\n\tchar *p = const_cast<char*>(pLine);\n\twhile(*p)\n\t{\n\t\tHighlighted = false;\n\t\tpLine = p;\n\t\t// find line seperator and strip multiline\n\t\twhile(*p)\n\t\t{\n\t\t\tif(*p++ == '\\n')\n\t\t\t{\n\t\t\t\t*(p-1) = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tm_CurrentLine = (m_CurrentLine+1)%MAX_LINES;\n\t\tm_aLines[m_CurrentLine].m_Time = time_get();\n\t\tm_aLines[m_CurrentLine].m_YOffset[0] = -1.0f;\n\t\tm_aLines[m_CurrentLine].m_YOffset[1] = -1.0f;\n\t\tm_aLines[m_CurrentLine].m_ClientID = ClientID;\n\t\tm_aLines[m_CurrentLine].m_Team = Team;\n\t\tm_aLines[m_CurrentLine].m_NameColor = -2;\n\n\t\t// check for highlighted name\n\t\tconst char *pHL = str_find_nocase(pLine, m_pClient->m_aClients[m_pClient->m_LocalClientID].m_aName);\n\t\tif(pHL)\n\t\t{\n\t\t\tint Length = str_length(m_pClient->m_aClients[m_pClient->m_LocalClientID].m_aName);\n\t\t\tif((pLine == pHL || pHL[-1] == ' ') && (pHL[Length] == 0 || pHL[Length] == ' ' || (pHL[Length] == ':' && pHL[Length+1] == ' ')))\n\t\t\t\tHighlighted = true;\n\t\t}\n\t\tm_aLines[m_CurrentLine].m_Highlighted =  Highlighted;\n\n\t\tif(ClientID == -1) // server message\n\t\t{\n\t\t\tstr_copy(m_aLines[m_CurrentLine].m_aName, \"*** \", sizeof(m_aLines[m_CurrentLine].m_aName));\n\t\t\tstr_format(m_aLines[m_CurrentLine].m_aText, sizeof(m_aLines[m_CurrentLine].m_aText), \"%s\", pLine);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(m_pClient->m_aClients[ClientID].m_Team == TEAM_SPECTATORS)\n\t\t\t\tm_aLines[m_CurrentLine].m_NameColor = TEAM_SPECTATORS;\n\n\t\t\tif(m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS)\n\t\t\t{\n\t\t\t\tif(m_pClient->m_aClients[ClientID].m_Team == TEAM_RED)\n\t\t\t\t\tm_aLines[m_CurrentLine].m_NameColor = TEAM_RED;\n\t\t\t\telse if(m_pClient->m_aClients[ClientID].m_Team == TEAM_BLUE)\n\t\t\t\t\tm_aLines[m_CurrentLine].m_NameColor = TEAM_BLUE;\n\t\t\t}\n\n\t\t\tstr_copy(m_aLines[m_CurrentLine].m_aName, m_pClient->m_aClients[ClientID].m_aName, sizeof(m_aLines[m_CurrentLine].m_aName));\n\t\t\tstr_format(m_aLines[m_CurrentLine].m_aText, sizeof(m_aLines[m_CurrentLine].m_aText), \": %s\", pLine);\n\t\t}\n\n\t\tchar aBuf[1024];\n\t\tstr_format(aBuf, sizeof(aBuf), \"%s%s\", m_aLines[m_CurrentLine].m_aName, m_aLines[m_CurrentLine].m_aText);\n\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, m_aLines[m_CurrentLine].m_Team?\"teamchat\":\"chat\", aBuf);\n\t}\n\n\t// play sound\n\tint64 Now = time_get();\n\tif(ClientID == -1)\n\t{\n\t\tif(Now-m_aLastSoundPlayed[CHAT_SERVER] >= time_freq()*3/10)\n\t\t{\n\t\t\tm_pClient->m_pSounds->Play(CSounds::CHN_GUI, SOUND_CHAT_SERVER, 0);\n\t\t\tm_aLastSoundPlayed[CHAT_SERVER] = Now;\n\t\t}\n\t}\n\telse if(Highlighted)\n\t{\n\t\tif(Now-m_aLastSoundPlayed[CHAT_HIGHLIGHT] >= time_freq()*3/10)\n\t\t{\n\t\t\tm_pClient->m_pSounds->Play(CSounds::CHN_GUI, SOUND_CHAT_HIGHLIGHT, 0);\n\t\t\tm_aLastSoundPlayed[CHAT_HIGHLIGHT] = Now;\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(Now-m_aLastSoundPlayed[CHAT_CLIENT] >= time_freq()*3/10)\n\t\t{\n\t\t\tm_pClient->m_pSounds->Play(CSounds::CHN_GUI, SOUND_CHAT_CLIENT, 0);\n\t\t\tm_aLastSoundPlayed[CHAT_CLIENT] = Now;\n\t\t}\n\t}\n}\n\nvoid CChat::OnRender()\n{\n\t// send pending chat messages\n\tif(m_PendingChatCounter > 0 && m_LastChatSend+time_freq() < time_get())\n\t{\n\t\tCHistoryEntry *pEntry = m_History.Last();\n\t\tfor(int i = m_PendingChatCounter-1; pEntry; --i, pEntry = m_History.Prev(pEntry))\n\t\t{\n\t\t\tif(i == 0)\n\t\t\t{\n\t\t\t\tSay(pEntry->m_Team, pEntry->m_aText);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t--m_PendingChatCounter;\n\t}\n\n\t// dont render chat if the menu is active\n\tif(m_pClient->m_pMenus->IsActive())\n\t\treturn;\n\n\tfloat Width = 300.0f*Graphics()->ScreenAspect();\n\tGraphics()->MapScreen(0.0f, 0.0f, Width, 300.0f);\n\tfloat x = 5.0f;\n\tfloat y = 300.0f-20.0f;\n\tif(m_Mode != MODE_NONE)\n\t{\n\t\t// render chat input\n\t\tCTextCursor Cursor;\n\t\tTextRender()->SetCursor(&Cursor, x, y, 8.0f, TEXTFLAG_RENDER);\n\t\tCursor.m_LineWidth = Width-190.0f;\n\t\tCursor.m_MaxLines = 2;\n\n\t\tif(m_Mode == MODE_ALL)\n\t\t\tTextRender()->TextEx(&Cursor, Localize(\"All\"), -1);\n\t\telse if(m_Mode == MODE_TEAM)\n\t\t\tTextRender()->TextEx(&Cursor, Localize(\"Team\"), -1);\n\t\telse\n\t\t\tTextRender()->TextEx(&Cursor, Localize(\"Chat\"), -1);\n\n\t\tTextRender()->TextEx(&Cursor, \": \", -1);\n\n\t\t// check if the visible text has to be moved\n\t\tif(m_InputUpdate)\n\t\t{\n\t\t\tif(m_ChatStringOffset > 0 && m_Input.GetLength() < m_OldChatStringLength)\n\t\t\t\tm_ChatStringOffset = max(0, m_ChatStringOffset-(m_OldChatStringLength-m_Input.GetLength()));\n\n\t\t\tif(m_ChatStringOffset > m_Input.GetCursorOffset())\n\t\t\t\tm_ChatStringOffset -= m_ChatStringOffset-m_Input.GetCursorOffset();\n\t\t\telse\n\t\t\t{\n\t\t\t\tCTextCursor Temp = Cursor;\n\t\t\t\tTemp.m_Flags = 0;\n\t\t\t\tTextRender()->TextEx(&Temp, m_Input.GetString()+m_ChatStringOffset, m_Input.GetCursorOffset()-m_ChatStringOffset);\n\t\t\t\tTextRender()->TextEx(&Temp, \"|\", -1);\n\t\t\t\twhile(Temp.m_LineCount > 2)\n\t\t\t\t{\n\t\t\t\t\t++m_ChatStringOffset;\n\t\t\t\t\tTemp = Cursor;\n\t\t\t\t\tTemp.m_Flags = 0;\n\t\t\t\t\tTextRender()->TextEx(&Temp, m_Input.GetString()+m_ChatStringOffset, m_Input.GetCursorOffset()-m_ChatStringOffset);\n\t\t\t\t\tTextRender()->TextEx(&Temp, \"|\", -1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tm_InputUpdate = false;\n\t\t}\n\n\t\tTextRender()->TextEx(&Cursor, m_Input.GetString()+m_ChatStringOffset, m_Input.GetCursorOffset()-m_ChatStringOffset);\n\t\tstatic float MarkerOffset = TextRender()->TextWidth(0, 8.0f, \"|\", -1)/3;\n\t\tCTextCursor Marker = Cursor;\n\t\tMarker.m_X -= MarkerOffset;\n\t\tTextRender()->TextEx(&Marker, \"|\", -1);\n\t\tTextRender()->TextEx(&Cursor, m_Input.GetString()+m_Input.GetCursorOffset(), -1);\n\t}\n\n\ty -= 8.0f;\n\n\tint64 Now = time_get();\n\tfloat LineWidth = m_pClient->m_pScoreboard->Active() ? 90.0f : 200.0f;\n\tfloat HeightLimit = m_pClient->m_pScoreboard->Active() ? 230.0f : m_Show ? 50.0f : 200.0f;\n\tfloat Begin = x;\n\tfloat FontSize = 6.0f;\n\tCTextCursor Cursor;\n\tint OffsetType = m_pClient->m_pScoreboard->Active() ? 1 : 0;\n\tfor(int i = 0; i < MAX_LINES; i++)\n\t{\n\t\tint r = ((m_CurrentLine-i)+MAX_LINES)%MAX_LINES;\n\t\tif(Now > m_aLines[r].m_Time+16*time_freq() && !m_Show)\n\t\t\tbreak;\n\n\t\t// get the y offset (calculate it if we haven't done that yet)\n\t\tif(m_aLines[r].m_YOffset[OffsetType] < 0.0f)\n\t\t{\n\t\t\tTextRender()->SetCursor(&Cursor, Begin, 0.0f, FontSize, 0);\n\t\t\tCursor.m_LineWidth = LineWidth;\n\t\t\tTextRender()->TextEx(&Cursor, m_aLines[r].m_aName, -1);\n\t\t\tTextRender()->TextEx(&Cursor, m_aLines[r].m_aText, -1);\n\t\t\tm_aLines[r].m_YOffset[OffsetType] = Cursor.m_Y + Cursor.m_FontSize;\n\t\t}\n\t\ty -= m_aLines[r].m_YOffset[OffsetType];\n\n\t\t// cut off if msgs waste too much space\n\t\tif(y < HeightLimit)\n\t\t\tbreak;\n\n\t\tfloat Blend = Now > m_aLines[r].m_Time+14*time_freq() && !m_Show ? 1.0f-(Now-m_aLines[r].m_Time-14*time_freq())/(2.0f*time_freq()) : 1.0f;\n\n\t\t// reset the cursor\n\t\tTextRender()->SetCursor(&Cursor, Begin, y, FontSize, TEXTFLAG_RENDER);\n\t\tCursor.m_LineWidth = LineWidth;\n\n\t\t// render name\n\t\tif(m_aLines[r].m_ClientID == -1)\n\t\t\tTextRender()->TextColor(1.0f, 1.0f, 0.5f, Blend); // system\n\t\telse if(m_aLines[r].m_Team)\n\t\t\tTextRender()->TextColor(0.45f, 0.9f, 0.45f, Blend); // team message\n\t\telse if(m_aLines[r].m_NameColor == TEAM_RED)\n\t\t\tTextRender()->TextColor(1.0f, 0.5f, 0.5f, Blend); // red\n\t\telse if(m_aLines[r].m_NameColor == TEAM_BLUE)\n\t\t\tTextRender()->TextColor(0.7f, 0.7f, 1.0f, Blend); // blue\n\t\telse if(m_aLines[r].m_NameColor == TEAM_SPECTATORS)\n\t\t\tTextRender()->TextColor(0.75f, 0.5f, 0.75f, Blend); // spectator\n\t\telse\n\t\t\tTextRender()->TextColor(0.8f, 0.8f, 0.8f, Blend);\n\n\t\tTextRender()->TextEx(&Cursor, m_aLines[r].m_aName, -1);\n\n\t\t// render line\n\t\tif(m_aLines[r].m_ClientID == -1)\n\t\t\tTextRender()->TextColor(1.0f, 1.0f, 0.5f, Blend); // system\n\t\telse if(m_aLines[r].m_Highlighted)\n\t\t\tTextRender()->TextColor(1.0f, 0.5f, 0.5f, Blend); // highlighted\n\t\telse if(m_aLines[r].m_Team)\n\t\t\tTextRender()->TextColor(0.65f, 1.0f, 0.65f, Blend); // team message\n\t\telse\n\t\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, Blend);\n\n\t\tTextRender()->TextEx(&Cursor, m_aLines[r].m_aText, -1);\n\t}\n\n\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n}\n\nvoid CChat::Say(int Team, const char *pLine)\n{\n\tm_LastChatSend = time_get();\n\n\t// send chat message\n\tCNetMsg_Cl_Say Msg;\n\tMsg.m_Team = Team;\n\tMsg.m_pMessage = pLine;\n\tClient()->SendPackMsg(&Msg, MSGFLAG_VITAL);\n}\n"
  },
  {
    "path": "src/game/client/components/chat.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_CHAT_H\n#define GAME_CLIENT_COMPONENTS_CHAT_H\n#include <engine/shared/ringbuffer.h>\n#include <game/client/component.h>\n#include <game/client/lineinput.h>\n\nclass CChat : public CComponent\n{\n\tCLineInput m_Input;\n\n\tenum\n\t{\n\t\tMAX_LINES = 25,\n\t};\n\n\tstruct CLine\n\t{\n\t\tint64 m_Time;\n\t\tfloat m_YOffset[2];\n\t\tint m_ClientID;\n\t\tint m_Team;\n\t\tint m_NameColor;\n\t\tchar m_aName[64];\n\t\tchar m_aText[512];\n\t\tbool m_Highlighted;\n\t};\n\n\tCLine m_aLines[MAX_LINES];\n\tint m_CurrentLine;\n\n\t// chat\n\tenum\n\t{\n\t\tMODE_NONE=0,\n\t\tMODE_ALL,\n\t\tMODE_TEAM,\n\n\t\tCHAT_SERVER=0,\n\t\tCHAT_HIGHLIGHT,\n\t\tCHAT_CLIENT,\n\t\tCHAT_NUM,\n\t};\n\n\tint m_Mode;\n\tbool m_Show;\n\tbool m_InputUpdate;\n\tint m_ChatStringOffset;\n\tint m_OldChatStringLength;\n\tint m_CompletionChosen;\n\tchar m_aCompletionBuffer[256];\n\tint m_PlaceholderOffset;\n\tint m_PlaceholderLength;\n\n\tstruct CHistoryEntry\n\t{\n\t\tint m_Team;\n\t\tchar m_aText[1];\n\t};\n\tCHistoryEntry *m_pHistoryEntry;\n\tTStaticRingBuffer<CHistoryEntry, 64*1024, CRingBufferBase::FLAG_RECYCLE> m_History;\n\tint m_PendingChatCounter;\n\tint64 m_LastChatSend;\n\tint64 m_aLastSoundPlayed[CHAT_NUM];\n\n\tstatic void ConSay(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConSayTeam(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConChat(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConShowChat(IConsole::IResult *pResult, void *pUserData);\n\npublic:\n\tCChat();\n\n\tbool IsActive() const { return m_Mode != MODE_NONE; }\n\n\tvoid AddLine(int ClientID, int Team, const char *pLine);\n\n\tvoid EnableMode(int Team);\n\n\tvoid Say(int Team, const char *pLine);\n\n\tvirtual void OnReset();\n\tvirtual void OnConsoleInit();\n\tvirtual void OnStateChange(int NewState, int OldState);\n\tvirtual void OnRender();\n\tvirtual void OnRelease();\n\tvirtual void OnMessage(int MsgType, void *pRawMsg);\n\tvirtual bool OnInput(IInput::CEvent Event);\n};\n#endif\n"
  },
  {
    "path": "src/game/client/components/console.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <math.h>\n\n#include <game/generated/client_data.h>\n\n#include <base/system.h>\n\n#include <engine/shared/ringbuffer.h>\n#include <engine/shared/config.h>\n#include <engine/graphics.h>\n#include <engine/textrender.h>\n#include <engine/storage.h>\n#include <engine/keys.h>\n#include <engine/console.h>\n\n#include <cstring>\n#include <cstdio>\n\n#include <game/client/ui.h>\n\n#include <game/version.h>\n\n#include <game/client/lineinput.h>\n#include <game/client/render.h>\n#include <game/client/components/controls.h>\n#include <game/client/components/menus.h>\n\n#include \"console.h\"\n\nenum\n{\n\tCONSOLE_CLOSED,\n\tCONSOLE_OPENING,\n\tCONSOLE_OPEN,\n\tCONSOLE_CLOSING,\n};\n\nCGameConsole::CInstance::CInstance(int Type)\n{\n\tm_pHistoryEntry = 0x0;\n\n\tm_Type = Type;\n\n\tif(Type == CGameConsole::CONSOLETYPE_LOCAL)\n\t\tm_CompletionFlagmask = CFGFLAG_CLIENT;\n\telse\n\t\tm_CompletionFlagmask = CFGFLAG_SERVER;\n\n\tm_aCompletionBuffer[0] = 0;\n\tm_CompletionChosen = -1;\n\tm_CompletionRenderOffset = 0.0f;\n\n\tm_IsCommand = false;\n}\n\nvoid CGameConsole::CInstance::Init(CGameConsole *pGameConsole)\n{\n\tm_pGameConsole = pGameConsole;\n};\n\nvoid CGameConsole::CInstance::ClearBacklog()\n{\n\tm_Backlog.Init();\n\tm_BacklogActPage = 0;\n}\n\nvoid CGameConsole::CInstance::ClearHistory()\n{\n\tm_History.Init();\n\tm_pHistoryEntry = 0;\n}\n\nvoid CGameConsole::CInstance::ExecuteLine(const char *pLine)\n{\n\tif(m_Type == CGameConsole::CONSOLETYPE_LOCAL)\n\t\tm_pGameConsole->m_pConsole->ExecuteLine(pLine);\n\telse\n\t{\n\t\tif(m_pGameConsole->Client()->RconAuthed())\n\t\t\tm_pGameConsole->Client()->Rcon(pLine);\n\t\telse\n\t\t\tm_pGameConsole->Client()->RconAuth(\"\", pLine);\n\t}\n}\n\nvoid CGameConsole::CInstance::PossibleCommandsCompleteCallback(const char *pStr, void *pUser)\n{\n\tCGameConsole::CInstance *pInstance = (CGameConsole::CInstance *)pUser;\n\tif(pInstance->m_CompletionChosen == pInstance->m_CompletionEnumerationCount)\n\t\tpInstance->m_Input.Set(pStr);\n\tpInstance->m_CompletionEnumerationCount++;\n}\n\nvoid CGameConsole::CInstance::OnInput(IInput::CEvent Event)\n{\n\tbool Handled = false;\n\n\tif(Event.m_Flags&IInput::FLAG_PRESS)\n\t{\n\t\tif(Event.m_Key == KEY_RETURN || Event.m_Key == KEY_KP_ENTER)\n\t\t{\n\t\t\tif(m_Input.GetString()[0])\n\t\t\t{\n\t\t\t\tif(m_Type == CONSOLETYPE_LOCAL || m_pGameConsole->Client()->RconAuthed())\n\t\t\t\t{\n\t\t\t\t\tchar *pEntry = m_History.Allocate(m_Input.GetLength()+1);\n\t\t\t\t\tmem_copy(pEntry, m_Input.GetString(), m_Input.GetLength()+1);\n\t\t\t\t}\n\t\t\t\tExecuteLine(m_Input.GetString());\n\t\t\t\tm_Input.Clear();\n\t\t\t\tm_pHistoryEntry = 0x0;\n\t\t\t}\n\n\t\t\tHandled = true;\n\t\t}\n\t\telse if (Event.m_Key == KEY_UP)\n\t\t{\n\t\t\tif (m_pHistoryEntry)\n\t\t\t{\n\t\t\t\tchar *pTest = m_History.Prev(m_pHistoryEntry);\n\n\t\t\t\tif (pTest)\n\t\t\t\t\tm_pHistoryEntry = pTest;\n\t\t\t}\n\t\t\telse\n\t\t\t\tm_pHistoryEntry = m_History.Last();\n\n\t\t\tif (m_pHistoryEntry)\n\t\t\t\tm_Input.Set(m_pHistoryEntry);\n\t\t\tHandled = true;\n\t\t}\n\t\telse if (Event.m_Key == KEY_DOWN)\n\t\t{\n\t\t\tif (m_pHistoryEntry)\n\t\t\t\tm_pHistoryEntry = m_History.Next(m_pHistoryEntry);\n\n\t\t\tif (m_pHistoryEntry)\n\t\t\t\tm_Input.Set(m_pHistoryEntry);\n\t\t\telse\n\t\t\t\tm_Input.Clear();\n\t\t\tHandled = true;\n\t\t}\n\t\telse if(Event.m_Key == KEY_TAB)\n\t\t{\n\t\t\tif(m_Type == CGameConsole::CONSOLETYPE_LOCAL || m_pGameConsole->Client()->RconAuthed())\n\t\t\t{\n\t\t\t\tm_CompletionChosen++;\n\t\t\t\tm_CompletionEnumerationCount = 0;\n\t\t\t\tm_pGameConsole->m_pConsole->PossibleCommands(m_aCompletionBuffer, m_CompletionFlagmask, m_Type != CGameConsole::CONSOLETYPE_LOCAL &&\n\t\t\t\t\tm_pGameConsole->Client()->RconAuthed() && m_pGameConsole->Client()->UseTempRconCommands(),\tPossibleCommandsCompleteCallback, this);\n\n\t\t\t\t// handle wrapping\n\t\t\t\tif(m_CompletionEnumerationCount && m_CompletionChosen >= m_CompletionEnumerationCount)\n\t\t\t\t{\n\t\t\t\t\tm_CompletionChosen %= m_CompletionEnumerationCount;\n\t\t\t\t\tm_CompletionEnumerationCount = 0;\n\t\t\t\t\tm_pGameConsole->m_pConsole->PossibleCommands(m_aCompletionBuffer, m_CompletionFlagmask, m_Type != CGameConsole::CONSOLETYPE_LOCAL &&\n\t\t\t\t\t\tm_pGameConsole->Client()->RconAuthed() && m_pGameConsole->Client()->UseTempRconCommands(),\tPossibleCommandsCompleteCallback, this);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if(Event.m_Key == KEY_PAGEUP)\n\t\t{\n\t\t\t++m_BacklogActPage;\n\t\t}\n\t\telse if(Event.m_Key == KEY_PAGEDOWN)\n\t\t{\n\t\t\t--m_BacklogActPage;\n\t\t\tif(m_BacklogActPage < 0)\n\t\t\t\tm_BacklogActPage = 0;\n\t\t}\n\t}\n\n\tif(!Handled)\n\t\tm_Input.ProcessInput(Event);\n\n\tif(Event.m_Flags&IInput::FLAG_PRESS)\n\t{\n\t\tif(Event.m_Key != KEY_TAB)\n\t\t{\n\t\t\tm_CompletionChosen = -1;\n\t\t\tstr_copy(m_aCompletionBuffer, m_Input.GetString(), sizeof(m_aCompletionBuffer));\n\t\t}\n\n\t\t// find the current command\n\t\t{\n\t\t\tchar aBuf[64] = {0};\n\t\t\tconst char *pSrc = GetString();\n\t\t\tint i = 0;\n\t\t\tfor(; i < (int)sizeof(aBuf)-1 && *pSrc && *pSrc != ' '; i++, pSrc++)\n\t\t\t\taBuf[i] = *pSrc;\n\t\t\taBuf[i] = 0;\n\n\t\t\tconst IConsole::CCommandInfo *pCommand = m_pGameConsole->m_pConsole->GetCommandInfo(aBuf, m_CompletionFlagmask,\n\t\t\t\tm_Type != CGameConsole::CONSOLETYPE_LOCAL && m_pGameConsole->Client()->RconAuthed() && m_pGameConsole->Client()->UseTempRconCommands());\n\t\t\tif(pCommand)\n\t\t\t{\n\t\t\t\tm_IsCommand = true;\n\t\t\t\tstr_copy(m_aCommandName, pCommand->m_pName, IConsole::TEMPCMD_NAME_LENGTH);\n\t\t\t\tstr_copy(m_aCommandHelp, pCommand->m_pHelp, IConsole::TEMPCMD_HELP_LENGTH);\n\t\t\t\tstr_copy(m_aCommandParams, pCommand->m_pParams, IConsole::TEMPCMD_PARAMS_LENGTH);\n\t\t\t}\n\t\t\telse\n\t\t\t\tm_IsCommand = false;\n\t\t}\n\t}\n}\n\nvoid CGameConsole::CInstance::PrintLine(const char *pLine)\n{\n\tint Len = str_length(pLine);\n\n\tif (Len > 255)\n\t\tLen = 255;\n\n\tCBacklogEntry *pEntry = m_Backlog.Allocate(sizeof(CBacklogEntry)+Len);\n\tpEntry->m_YOffset = -1.0f;\n\tmem_copy(pEntry->m_aText, pLine, Len);\n\tpEntry->m_aText[Len] = 0;\n}\n\nCGameConsole::CGameConsole()\n: m_LocalConsole(CONSOLETYPE_LOCAL), m_RemoteConsole(CONSOLETYPE_REMOTE)\n{\n\tm_ConsoleType = CONSOLETYPE_LOCAL;\n\tm_ConsoleState = CONSOLE_CLOSED;\n\tm_StateChangeEnd = 0.0f;\n\tm_StateChangeDuration = 0.1f;\n}\n\nfloat CGameConsole::TimeNow()\n{\n\tstatic long long s_TimeStart = time_get();\n\treturn float(time_get()-s_TimeStart)/float(time_freq());\n}\n\nCGameConsole::CInstance *CGameConsole::CurrentConsole()\n{\n\tif(m_ConsoleType == CONSOLETYPE_REMOTE)\n\t\treturn &m_RemoteConsole;\n\treturn &m_LocalConsole;\n}\n\nvoid CGameConsole::OnReset()\n{\n}\n\n// only defined for 0<=t<=1\nstatic float ConsoleScaleFunc(float t)\n{\n\t//return t;\n\treturn sinf(acosf(1.0f-t));\n}\n\nstruct CRenderInfo\n{\n\tCGameConsole *m_pSelf;\n\tCTextCursor m_Cursor;\n\tconst char *m_pCurrentCmd;\n\tint m_WantedCompletion;\n\tint m_EnumCount;\n\tfloat m_Offset;\n\tfloat m_Width;\n};\n\nvoid CGameConsole::PossibleCommandsRenderCallback(const char *pStr, void *pUser)\n{\n\tCRenderInfo *pInfo = static_cast<CRenderInfo *>(pUser);\n\n\tif(pInfo->m_EnumCount == pInfo->m_WantedCompletion)\n\t{\n\t\tfloat tw = pInfo->m_pSelf->TextRender()->TextWidth(pInfo->m_Cursor.m_pFont, pInfo->m_Cursor.m_FontSize, pStr, -1);\n\t\tpInfo->m_pSelf->Graphics()->TextureClear();\n\t\tpInfo->m_pSelf->Graphics()->QuadsBegin();\n\t\t\tpInfo->m_pSelf->Graphics()->SetColor(229.0f/255.0f,185.0f/255.0f,4.0f/255.0f,0.85f);\n\t\t\tpInfo->m_pSelf->RenderTools()->DrawRoundRect(pInfo->m_Cursor.m_X-3, pInfo->m_Cursor.m_Y, tw+5, pInfo->m_Cursor.m_FontSize+4, pInfo->m_Cursor.m_FontSize/3);\n\t\tpInfo->m_pSelf->Graphics()->QuadsEnd();\n\n\t\t// scroll when out of sight\n\t\tif(pInfo->m_Cursor.m_X < 3.0f)\n\t\t\tpInfo->m_Offset = 0.0f;\n\t\telse if(pInfo->m_Cursor.m_X+tw > pInfo->m_Width)\n\t\t\tpInfo->m_Offset -= pInfo->m_Width/2;\n\n\t\tpInfo->m_pSelf->TextRender()->TextColor(0.05f, 0.05f, 0.05f,1);\n\t\tpInfo->m_pSelf->TextRender()->TextEx(&pInfo->m_Cursor, pStr, -1);\n\t}\n\telse\n\t{\n\t\tconst char *pMatchStart = str_find_nocase(pStr, pInfo->m_pCurrentCmd);\n\n\t\tif(pMatchStart)\n\t\t{\n\t\t\tpInfo->m_pSelf->TextRender()->TextColor(0.5f,0.5f,0.5f,1);\n\t\t\tpInfo->m_pSelf->TextRender()->TextEx(&pInfo->m_Cursor, pStr, pMatchStart-pStr);\n\t\t\tpInfo->m_pSelf->TextRender()->TextColor(229.0f/255.0f,185.0f/255.0f,4.0f/255.0f,1);\n\t\t\tpInfo->m_pSelf->TextRender()->TextEx(&pInfo->m_Cursor, pMatchStart, str_length(pInfo->m_pCurrentCmd));\n\t\t\tpInfo->m_pSelf->TextRender()->TextColor(0.5f,0.5f,0.5f,1);\n\t\t\tpInfo->m_pSelf->TextRender()->TextEx(&pInfo->m_Cursor, pMatchStart+str_length(pInfo->m_pCurrentCmd), -1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpInfo->m_pSelf->TextRender()->TextColor(0.75f,0.75f,0.75f,1);\n\t\t\tpInfo->m_pSelf->TextRender()->TextEx(&pInfo->m_Cursor, pStr, -1);\n\t\t}\n\t}\n\n\tpInfo->m_EnumCount++;\n\tpInfo->m_Cursor.m_X += 7.0f;\n}\n\nvoid CGameConsole::OnRender()\n{\n\tCUIRect Screen = *UI()->Screen();\n\tfloat ConsoleMaxHeight = Screen.h*3/5.0f;\n\tfloat ConsoleHeight;\n\n\tfloat Progress = (TimeNow()-(m_StateChangeEnd-m_StateChangeDuration))/float(m_StateChangeDuration);\n\n\tif (Progress >= 1.0f)\n\t{\n\t\tif (m_ConsoleState == CONSOLE_CLOSING)\n\t\t\tm_ConsoleState = CONSOLE_CLOSED;\n\t\telse if (m_ConsoleState == CONSOLE_OPENING)\n\t\t\tm_ConsoleState = CONSOLE_OPEN;\n\n\t\tProgress = 1.0f;\n\t}\n\n\tif (m_ConsoleState == CONSOLE_OPEN && g_Config.m_ClEditor)\n\t\tToggle(CONSOLETYPE_LOCAL);\n\n\tif (m_ConsoleState == CONSOLE_CLOSED)\n\t\treturn;\n\n\tif (m_ConsoleState == CONSOLE_OPEN)\n\t\tInput()->MouseModeAbsolute();\n\n\tfloat ConsoleHeightScale;\n\n\tif (m_ConsoleState == CONSOLE_OPENING)\n\t\tConsoleHeightScale = ConsoleScaleFunc(Progress);\n\telse if (m_ConsoleState == CONSOLE_CLOSING)\n\t\tConsoleHeightScale = ConsoleScaleFunc(1.0f-Progress);\n\telse //if (console_state == CONSOLE_OPEN)\n\t\tConsoleHeightScale = ConsoleScaleFunc(1.0f);\n\n\tConsoleHeight = ConsoleHeightScale*ConsoleMaxHeight;\n\n\tGraphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h);\n\n\t// do console shadow\n\tGraphics()->TextureClear();\n\tGraphics()->QuadsBegin();\n\tIGraphics::CColorVertex Array[4] = {\n\t\tIGraphics::CColorVertex(0, 0,0,0, 0.5f),\n\t\tIGraphics::CColorVertex(1, 0,0,0, 0.5f),\n\t\tIGraphics::CColorVertex(2, 0,0,0, 0.0f),\n\t\tIGraphics::CColorVertex(3, 0,0,0, 0.0f)};\n\tGraphics()->SetColorVertex(Array, 4);\n\tIGraphics::CQuadItem QuadItem(0, ConsoleHeight, Screen.w, 10.0f);\n\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n\n\t// do background\n\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_CONSOLE_BG].m_Id);\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(0.2f, 0.2f, 0.2f,0.9f);\n\tif(m_ConsoleType == CONSOLETYPE_REMOTE)\n\t\tGraphics()->SetColor(0.4f, 0.2f, 0.2f,0.9f);\n\tGraphics()->QuadsSetSubset(0,-ConsoleHeight*0.075f,Screen.w*0.075f*0.5f,0);\n\tQuadItem = IGraphics::CQuadItem(0, 0, Screen.w, ConsoleHeight);\n\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n\n\t// do small bar shadow\n\tGraphics()->TextureClear();\n\tGraphics()->QuadsBegin();\n\tArray[0] = IGraphics::CColorVertex(0, 0,0,0, 0.0f);\n\tArray[1] = IGraphics::CColorVertex(1, 0,0,0, 0.0f);\n\tArray[2] = IGraphics::CColorVertex(2, 0,0,0, 0.25f);\n\tArray[3] = IGraphics::CColorVertex(3, 0,0,0, 0.25f);\n\tGraphics()->SetColorVertex(Array, 4);\n\tQuadItem = IGraphics::CQuadItem(0, ConsoleHeight-20, Screen.w, 10);\n\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n\n\t// do the lower bar\n\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_CONSOLE_BAR].m_Id);\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 0.9f);\n\tGraphics()->QuadsSetSubset(0,0.1f,Screen.w*0.015f,1-0.1f);\n\tQuadItem = IGraphics::CQuadItem(0,ConsoleHeight-10.0f,Screen.w,10.0f);\n\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n\n\tConsoleHeight -= 22.0f;\n\n\tCInstance *pConsole = CurrentConsole();\n\n\t{\n\t\tfloat FontSize = 10.0f;\n\t\tfloat RowHeight = FontSize*1.25f;\n\t\tfloat x = 3;\n\t\tfloat y = ConsoleHeight - RowHeight - 5.0f;\n\n\t\tCRenderInfo Info;\n\t\tInfo.m_pSelf = this;\n\t\tInfo.m_WantedCompletion = pConsole->m_CompletionChosen;\n\t\tInfo.m_EnumCount = 0;\n\t\tInfo.m_Offset = pConsole->m_CompletionRenderOffset;\n\t\tInfo.m_Width = Screen.w;\n\t\tInfo.m_pCurrentCmd = pConsole->m_aCompletionBuffer;\n\t\tTextRender()->SetCursor(&Info.m_Cursor, x+Info.m_Offset, y+RowHeight+2.0f, FontSize, TEXTFLAG_RENDER);\n\n\t\t// render prompt\n\t\tCTextCursor Cursor;\n\t\tTextRender()->SetCursor(&Cursor, x, y, FontSize, TEXTFLAG_RENDER);\n\t\tconst char *pPrompt = \"> \";\n\t\tif(m_ConsoleType == CONSOLETYPE_REMOTE)\n\t\t{\n\t\t\tif(Client()->State() == IClient::STATE_ONLINE)\n\t\t\t{\n\t\t\t\tif(Client()->RconAuthed())\n\t\t\t\t\tpPrompt = \"rcon> \";\n\t\t\t\telse\n\t\t\t\t\tpPrompt = \"ENTER PASSWORD> \";\n\t\t\t}\n\t\t\telse\n\t\t\t\tpPrompt = \"NOT CONNECTED> \";\n\t\t}\n\t\tTextRender()->TextEx(&Cursor, pPrompt, -1);\n\n\t\tx = Cursor.m_X;\n\n\t\t//hide rcon password\n\t\tchar aInputString[256];\n\t\tstr_copy(aInputString, pConsole->m_Input.GetString(), sizeof(aInputString));\n\t\tif(m_ConsoleType == CONSOLETYPE_REMOTE && Client()->State() == IClient::STATE_ONLINE && !Client()->RconAuthed())\n\t\t{\n\t\t\tfor(int i = 0; i < pConsole->m_Input.GetLength(); ++i)\n\t\t\t\taInputString[i] = '*';\n\t\t}\n\n\t\t// render console input (wrap line)\n\t\tTextRender()->SetCursor(&Cursor, x, y, FontSize, 0);\n\t\tCursor.m_LineWidth = Screen.w - 10.0f - x;\n\t\tTextRender()->TextEx(&Cursor, aInputString, pConsole->m_Input.GetCursorOffset());\n\t\tTextRender()->TextEx(&Cursor, aInputString+pConsole->m_Input.GetCursorOffset(), -1);\n\t\tint Lines = Cursor.m_LineCount;\n\t\t\n\t\ty -= (Lines - 1) * FontSize;\n\t\tTextRender()->SetCursor(&Cursor, x, y, FontSize, TEXTFLAG_RENDER);\n\t\tCursor.m_LineWidth = Screen.w - 10.0f - x;\n\t\t\n\t\tTextRender()->TextEx(&Cursor, aInputString, pConsole->m_Input.GetCursorOffset());\n\t\tstatic float MarkerOffset = TextRender()->TextWidth(0, FontSize, \"|\", -1)/3;\n\t\tCTextCursor Marker = Cursor;\n\t\tMarker.m_X -= MarkerOffset;\n\t\tMarker.m_LineWidth = -1;\n\t\tTextRender()->TextEx(&Marker, \"|\", -1);\n\t\tTextRender()->TextEx(&Cursor, aInputString+pConsole->m_Input.GetCursorOffset(), -1);\n\n\t\t// render possible commands\n\t\tif(m_ConsoleType == CONSOLETYPE_LOCAL || Client()->RconAuthed())\n\t\t{\n\t\t\tif(pConsole->m_Input.GetString()[0] != 0)\n\t\t\t{\n\t\t\t\tm_pConsole->PossibleCommands(pConsole->m_aCompletionBuffer, pConsole->m_CompletionFlagmask, m_ConsoleType != CGameConsole::CONSOLETYPE_LOCAL &&\n\t\t\t\t\tClient()->RconAuthed() && Client()->UseTempRconCommands(), PossibleCommandsRenderCallback, &Info);\n\t\t\t\tpConsole->m_CompletionRenderOffset = Info.m_Offset;\n\n\t\t\t\tif(Info.m_EnumCount <= 0)\n\t\t\t\t{\n\t\t\t\t\tif(pConsole->m_IsCommand)\n\t\t\t\t\t{\n\t\t\t\t\t\tchar aBuf[512];\n\t\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"Help: %s \", pConsole->m_aCommandHelp);\n\t\t\t\t\t\tTextRender()->TextEx(&Info.m_Cursor, aBuf, -1);\n\t\t\t\t\t\tTextRender()->TextColor(0.75f, 0.75f, 0.75f, 1);\n\t\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"Syntax: %s %s\", pConsole->m_aCommandName, pConsole->m_aCommandParams);\n\t\t\t\t\t\tTextRender()->TextEx(&Info.m_Cursor, aBuf, -1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tTextRender()->TextColor(1,1,1,1);\n\n\t\t//\trender log (actual page, wrap lines)\n\t\tCInstance::CBacklogEntry *pEntry = pConsole->m_Backlog.Last();\n\t\tfloat OffsetY = 0.0f;\n\t\tfloat LineOffset = 1.0f;\n\t\tfor(int Page = 0; Page <= pConsole->m_BacklogActPage; ++Page, OffsetY = 0.0f)\n\t\t{\n\t\t\twhile(pEntry)\n\t\t\t{\n\t\t\t\t// get y offset (calculate it if we haven't yet)\n\t\t\t\tif(pEntry->m_YOffset < 0.0f)\n\t\t\t\t{\n\t\t\t\t\tTextRender()->SetCursor(&Cursor, 0.0f, 0.0f, FontSize, 0);\n\t\t\t\t\tCursor.m_LineWidth = Screen.w-10;\n\t\t\t\t\tTextRender()->TextEx(&Cursor, pEntry->m_aText, -1);\n\t\t\t\t\tpEntry->m_YOffset = Cursor.m_Y+Cursor.m_FontSize+LineOffset;\n\t\t\t\t}\n\t\t\t\tOffsetY += pEntry->m_YOffset;\n\n\t\t\t\t//\tnext page when lines reach the top\n\t\t\t\tif(y-OffsetY <= RowHeight)\n\t\t\t\t\tbreak;\n\n\t\t\t\t//\tjust render output from actual backlog page (render bottom up)\n\t\t\t\tif(Page == pConsole->m_BacklogActPage)\n\t\t\t\t{\n\t\t\t\t\tTextRender()->SetCursor(&Cursor, 0.0f, y-OffsetY, FontSize, TEXTFLAG_RENDER);\n\t\t\t\t\tCursor.m_LineWidth = Screen.w-10.0f;\n\t\t\t\t\tTextRender()->TextEx(&Cursor, pEntry->m_aText, -1);\n\t\t\t\t}\n\t\t\t\tpEntry = pConsole->m_Backlog.Prev(pEntry);\n\t\t\t}\n\n\t\t\t//\tactual backlog page number is too high, render last available page (current checked one, render top down)\n\t\t\tif(!pEntry && Page < pConsole->m_BacklogActPage)\n\t\t\t{\n\t\t\t\tpConsole->m_BacklogActPage = Page;\n\t\t\t\tpEntry = pConsole->m_Backlog.First();\n\t\t\t\twhile(OffsetY > 0.0f && pEntry)\n\t\t\t\t{\n\t\t\t\t\tTextRender()->SetCursor(&Cursor, 0.0f, y-OffsetY, FontSize, TEXTFLAG_RENDER);\n\t\t\t\t\tCursor.m_LineWidth = Screen.w-10.0f;\n\t\t\t\t\tTextRender()->TextEx(&Cursor, pEntry->m_aText, -1);\n\t\t\t\t\tOffsetY -= pEntry->m_YOffset;\n\t\t\t\t\tpEntry = pConsole->m_Backlog.Next(pEntry);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// render page\n\t\tchar aBuf[128];\n\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"-Page %d-\"), pConsole->m_BacklogActPage+1);\n\t\tTextRender()->Text(0, 10.0f, 0.0f, FontSize, aBuf, -1);\n\n\t\t// render version\n\t\tstr_format(aBuf, sizeof(aBuf), \"v%s\", GAME_VERSION);\n\t\tfloat Width = TextRender()->TextWidth(0, FontSize, aBuf, -1);\n\t\tTextRender()->Text(0, Screen.w-Width-10.0f, 0.0f, FontSize, aBuf, -1);\n\t}\n}\n\nvoid CGameConsole::OnMessage(int MsgType, void *pRawMsg)\n{\n}\n\nbool CGameConsole::OnInput(IInput::CEvent Event)\n{\n\tif(m_ConsoleState == CONSOLE_CLOSED)\n\t\treturn false;\n\tif(Event.m_Key >= KEY_F1 && Event.m_Key <= KEY_F15)\n\t\treturn false;\n\n\tif(Event.m_Key == KEY_ESCAPE && (Event.m_Flags&IInput::FLAG_PRESS))\n\t\tToggle(m_ConsoleType);\n\telse\n\t\tCurrentConsole()->OnInput(Event);\n\n\treturn true;\n}\n\nvoid CGameConsole::Toggle(int Type)\n{\n\tif(m_ConsoleType != Type && (m_ConsoleState == CONSOLE_OPEN || m_ConsoleState == CONSOLE_OPENING))\n\t{\n\t\t// don't toggle console, just switch what console to use\n\t}\n\telse\n\t{\n\t\tif (m_ConsoleState == CONSOLE_CLOSED || m_ConsoleState == CONSOLE_OPEN)\n\t\t{\n\t\t\tm_StateChangeEnd = TimeNow()+m_StateChangeDuration;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfloat Progress = m_StateChangeEnd-TimeNow();\n\t\t\tfloat ReversedProgress = m_StateChangeDuration-Progress;\n\n\t\t\tm_StateChangeEnd = TimeNow()+ReversedProgress;\n\t\t}\n\n\t\tif (m_ConsoleState == CONSOLE_CLOSED || m_ConsoleState == CONSOLE_CLOSING)\n\t\t{\n\t\t\tInput()->MouseModeAbsolute();\n\t\t\tm_pClient->m_pMenus->UseMouseButtons(false);\n\t\t\tm_ConsoleState = CONSOLE_OPENING;\n\t\t\t// reset controls\n\t\t\tm_pClient->m_pControls->OnReset();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tInput()->MouseModeRelative();\n\t\t\tm_pClient->m_pMenus->UseMouseButtons(true);\n\t\t\tm_pClient->OnRelease();\n\t\t\tm_ConsoleState = CONSOLE_CLOSING;\n\t\t}\n\t}\n\n\tm_ConsoleType = Type;\n}\n\nvoid CGameConsole::Dump(int Type)\n{\n\tCInstance *pConsole = Type == CONSOLETYPE_REMOTE ? &m_RemoteConsole : &m_LocalConsole;\n\tchar aFilename[128];\n\tchar aDate[20];\n\n\tstr_timestamp(aDate, sizeof(aDate));\n\tstr_format(aFilename, sizeof(aFilename), \"dumps/%s_dump_%s.txt\", Type==CONSOLETYPE_REMOTE?\"remote_console\":\"local_console\", aDate);\n\tIOHANDLE io = Storage()->OpenFile(aFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE);\n\tif(io)\n\t{\n\t\tfor(CInstance::CBacklogEntry *pEntry = pConsole->m_Backlog.First(); pEntry; pEntry = pConsole->m_Backlog.Next(pEntry))\n\t\t{\n\t\t\tio_write(io, pEntry->m_aText, str_length(pEntry->m_aText));\n\t\t\tio_write_newline(io);\n\t\t}\n\t\tio_close(io);\n\t}\n}\n\nvoid CGameConsole::ConToggleLocalConsole(IConsole::IResult *pResult, void *pUserData)\n{\n\t((CGameConsole *)pUserData)->Toggle(CONSOLETYPE_LOCAL);\n}\n\nvoid CGameConsole::ConToggleRemoteConsole(IConsole::IResult *pResult, void *pUserData)\n{\n\t((CGameConsole *)pUserData)->Toggle(CONSOLETYPE_REMOTE);\n}\n\nvoid CGameConsole::ConClearLocalConsole(IConsole::IResult *pResult, void *pUserData)\n{\n\t((CGameConsole *)pUserData)->m_LocalConsole.ClearBacklog();\n}\n\nvoid CGameConsole::ConClearRemoteConsole(IConsole::IResult *pResult, void *pUserData)\n{\n\t((CGameConsole *)pUserData)->m_RemoteConsole.ClearBacklog();\n}\n\nvoid CGameConsole::ConDumpLocalConsole(IConsole::IResult *pResult, void *pUserData)\n{\n\t((CGameConsole *)pUserData)->Dump(CONSOLETYPE_LOCAL);\n}\n\nvoid CGameConsole::ConDumpRemoteConsole(IConsole::IResult *pResult, void *pUserData)\n{\n\t((CGameConsole *)pUserData)->Dump(CONSOLETYPE_REMOTE);\n}\n\nvoid CGameConsole::ClientConsolePrintCallback(const char *pStr, void *pUserData)\n{\n\t((CGameConsole *)pUserData)->m_LocalConsole.PrintLine(pStr);\n}\n\nvoid CGameConsole::ConchainConsoleOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)\n{\n\tpfnCallback(pResult, pCallbackUserData);\n\tif(pResult->NumArguments() == 1)\n\t{\n\t\tCGameConsole *pThis = static_cast<CGameConsole *>(pUserData);\n\t\tpThis->Console()->SetPrintOutputLevel(pThis->m_PrintCBIndex, pResult->GetInteger(0));\n\t}\n}\n\nvoid CGameConsole::PrintLine(int Type, const char *pLine)\n{\n\tif(Type == CONSOLETYPE_LOCAL)\n\t\tm_LocalConsole.PrintLine(pLine);\n\telse if(Type == CONSOLETYPE_REMOTE)\n\t\tm_RemoteConsole.PrintLine(pLine);\n}\n\nvoid CGameConsole::OnConsoleInit()\n{\n\t// init console instances\n\tm_LocalConsole.Init(this);\n\tm_RemoteConsole.Init(this);\n\n\tm_pConsole = Kernel()->RequestInterface<IConsole>();\n\n\t//\n\tm_PrintCBIndex = Console()->RegisterPrintCallback(g_Config.m_ConsoleOutputLevel, ClientConsolePrintCallback, this);\n\n\tConsole()->Register(\"toggle_local_console\", \"\", CFGFLAG_CLIENT, ConToggleLocalConsole, this, \"Toggle local console\");\n\tConsole()->Register(\"toggle_remote_console\", \"\", CFGFLAG_CLIENT, ConToggleRemoteConsole, this, \"Toggle remote console\");\n\tConsole()->Register(\"clear_local_console\", \"\", CFGFLAG_CLIENT, ConClearLocalConsole, this, \"Clear local console\");\n\tConsole()->Register(\"clear_remote_console\", \"\", CFGFLAG_CLIENT, ConClearRemoteConsole, this, \"Clear remote console\");\n\tConsole()->Register(\"dump_local_console\", \"\", CFGFLAG_CLIENT, ConDumpLocalConsole, this, \"Dump local console\");\n\tConsole()->Register(\"dump_remote_console\", \"\", CFGFLAG_CLIENT, ConDumpRemoteConsole, this, \"Dump remote console\");\n\n\tConsole()->Chain(\"console_output_level\", ConchainConsoleOutputLevelUpdate, this);\n}\n\nvoid CGameConsole::OnStateChange(int NewState, int OldState)\n{\n\tif(NewState == IClient::STATE_OFFLINE)\n\t\tm_RemoteConsole.ClearHistory();\n}\n"
  },
  {
    "path": "src/game/client/components/console.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_CONSOLE_H\n#define GAME_CLIENT_COMPONENTS_CONSOLE_H\n#include <engine/shared/ringbuffer.h>\n#include <game/client/component.h>\n#include <game/client/lineinput.h>\n\nclass CGameConsole : public CComponent\n{\n\tclass CInstance\n\t{\n\tpublic:\n\t\tstruct CBacklogEntry\n\t\t{\n\t\t\tfloat m_YOffset;\n\t\t\tchar m_aText[1];\n\t\t};\n\t\tTStaticRingBuffer<CBacklogEntry, 64*1024, CRingBufferBase::FLAG_RECYCLE> m_Backlog;\n\t\tTStaticRingBuffer<char, 64*1024, CRingBufferBase::FLAG_RECYCLE> m_History;\n\t\tchar *m_pHistoryEntry;\n\n\t\tCLineInput m_Input;\n\t\tint m_Type;\n\t\tint m_CompletionEnumerationCount;\n\t\tint m_BacklogActPage;\n\n\tpublic:\n\t\tCGameConsole *m_pGameConsole;\n\n\t\tchar m_aCompletionBuffer[128];\n\t\tint m_CompletionChosen;\n\t\tint m_CompletionFlagmask;\n\t\tfloat m_CompletionRenderOffset;\n\n\t\tbool m_IsCommand;\n\t\tchar m_aCommandName[IConsole::TEMPCMD_NAME_LENGTH];\n\t\tchar m_aCommandHelp[IConsole::TEMPCMD_HELP_LENGTH];\n\t\tchar m_aCommandParams[IConsole::TEMPCMD_PARAMS_LENGTH];\n\n\t\tCInstance(int t);\n\t\tvoid Init(CGameConsole *pGameConsole);\n\n\t\tvoid ClearBacklog();\n\t\tvoid ClearHistory();\n\n\t\tvoid ExecuteLine(const char *pLine);\n\n\t\tvoid OnInput(IInput::CEvent Event);\n\t\tvoid PrintLine(const char *pLine);\n\n\t\tconst char *GetString() const { return m_Input.GetString(); }\n\t\tstatic void PossibleCommandsCompleteCallback(const char *pStr, void *pUser);\n\t};\n\n\tclass IConsole *m_pConsole;\n\n\tCInstance m_LocalConsole;\n\tCInstance m_RemoteConsole;\n\n\tCInstance *CurrentConsole();\n\tfloat TimeNow();\n\tint m_PrintCBIndex;\n\n\tint m_ConsoleType;\n\tint m_ConsoleState;\n\tfloat m_StateChangeEnd;\n\tfloat m_StateChangeDuration;\n\n\tvoid Toggle(int Type);\n\tvoid Dump(int Type);\n\n\tstatic void PossibleCommandsRenderCallback(const char *pStr, void *pUser);\n\tstatic void ClientConsolePrintCallback(const char *pStr, void *pUserData);\n\tstatic void ConToggleLocalConsole(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConToggleRemoteConsole(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConClearLocalConsole(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConClearRemoteConsole(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConDumpLocalConsole(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConDumpRemoteConsole(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConchainConsoleOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData);\n\npublic:\n\tenum\n\t{\n\t\tCONSOLETYPE_LOCAL=0,\n\t\tCONSOLETYPE_REMOTE,\n\t};\n\n\tCGameConsole();\n\n\tvoid PrintLine(int Type, const char *pLine);\n\n\tvirtual void OnStateChange(int NewState, int OldState);\n\tvirtual void OnConsoleInit();\n\tvirtual void OnReset();\n\tvirtual void OnRender();\n\tvirtual void OnMessage(int MsgType, void *pRawMsg);\n\tvirtual bool OnInput(IInput::CEvent Events);\n};\n#endif\n"
  },
  {
    "path": "src/game/client/components/controls.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/math.h>\n\n#include <engine/shared/config.h>\n\n#include <game/collision.h>\n#include <game/client/gameclient.h>\n#include <game/client/component.h>\n#include <game/client/components/chat.h>\n#include <game/client/components/menus.h>\n#include <game/client/components/scoreboard.h>\n\n#include \"controls.h\"\n\nCControls::CControls()\n{\n\tmem_zero(&m_LastData, sizeof(m_LastData));\n}\n\nvoid CControls::OnReset()\n{\n\tm_LastData.m_Direction = 0;\n\tm_LastData.m_Hook = 0;\n\t// simulate releasing the fire button\n\tif((m_LastData.m_Fire&1) != 0)\n\t\tm_LastData.m_Fire++;\n\tm_LastData.m_Fire &= INPUT_STATE_MASK;\n\tm_LastData.m_Jump = 0;\n\tm_InputData = m_LastData;\n\n\tm_InputDirectionLeft = 0;\n\tm_InputDirectionRight = 0;\n}\n\nvoid CControls::OnRelease()\n{\n\tOnReset();\n}\n\nvoid CControls::OnPlayerDeath()\n{\n\tm_LastData.m_WantedWeapon = m_InputData.m_WantedWeapon = 0;\n}\n\nstatic void ConKeyInputState(IConsole::IResult *pResult, void *pUserData)\n{\n\t((int *)pUserData)[0] = pResult->GetInteger(0);\n}\n\nstatic void ConKeyInputCounter(IConsole::IResult *pResult, void *pUserData)\n{\n\tint *v = (int *)pUserData;\n\tif(((*v)&1) != pResult->GetInteger(0))\n\t\t(*v)++;\n\t*v &= INPUT_STATE_MASK;\n}\n\nstruct CInputSet\n{\n\tCControls *m_pControls;\n\tint *m_pVariable;\n\tint m_Value;\n};\n\nstatic void ConKeyInputSet(IConsole::IResult *pResult, void *pUserData)\n{\n\tCInputSet *pSet = (CInputSet *)pUserData;\n\tif(pResult->GetInteger(0))\n\t\t*pSet->m_pVariable = pSet->m_Value;\n}\n\nstatic void ConKeyInputNextPrevWeapon(IConsole::IResult *pResult, void *pUserData)\n{\n\tCInputSet *pSet = (CInputSet *)pUserData;\n\tConKeyInputCounter(pResult, pSet->m_pVariable);\n\tpSet->m_pControls->m_InputData.m_WantedWeapon = 0;\n}\n\nvoid CControls::OnConsoleInit()\n{\n\t// game commands\n\tConsole()->Register(\"+left\", \"\", CFGFLAG_CLIENT, ConKeyInputState, &m_InputDirectionLeft, \"Move left\");\n\tConsole()->Register(\"+right\", \"\", CFGFLAG_CLIENT, ConKeyInputState, &m_InputDirectionRight, \"Move right\");\n\tConsole()->Register(\"+jump\", \"\", CFGFLAG_CLIENT, ConKeyInputState, &m_InputData.m_Jump, \"Jump\");\n\tConsole()->Register(\"+hook\", \"\", CFGFLAG_CLIENT, ConKeyInputState, &m_InputData.m_Hook, \"Hook\");\n\tConsole()->Register(\"+fire\", \"\", CFGFLAG_CLIENT, ConKeyInputCounter, &m_InputData.m_Fire, \"Fire\");\n\n\t{ static CInputSet s_Set = {this, &m_InputData.m_WantedWeapon, 1}; Console()->Register(\"+weapon1\", \"\", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, \"Switch to hammer\"); }\n\t{ static CInputSet s_Set = {this, &m_InputData.m_WantedWeapon, 2}; Console()->Register(\"+weapon2\", \"\", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, \"Switch to gun\"); }\n\t{ static CInputSet s_Set = {this, &m_InputData.m_WantedWeapon, 3}; Console()->Register(\"+weapon3\", \"\", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, \"Switch to shotgun\"); }\n\t{ static CInputSet s_Set = {this, &m_InputData.m_WantedWeapon, 4}; Console()->Register(\"+weapon4\", \"\", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, \"Switch to grenade\"); }\n\t{ static CInputSet s_Set = {this, &m_InputData.m_WantedWeapon, 5}; Console()->Register(\"+weapon5\", \"\", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, \"Switch to laser\"); }\n\n\t{ static CInputSet s_Set = {this, &m_InputData.m_NextWeapon, 0}; Console()->Register(\"+nextweapon\", \"\", CFGFLAG_CLIENT, ConKeyInputNextPrevWeapon, (void *)&s_Set, \"Switch to next weapon\"); }\n\t{ static CInputSet s_Set = {this, &m_InputData.m_PrevWeapon, 0}; Console()->Register(\"+prevweapon\", \"\", CFGFLAG_CLIENT, ConKeyInputNextPrevWeapon, (void *)&s_Set, \"Switch to previous weapon\"); }\n}\n\nvoid CControls::OnMessage(int Msg, void *pRawMsg)\n{\n\tif(Msg == NETMSGTYPE_SV_WEAPONPICKUP)\n\t{\n\t\tCNetMsg_Sv_WeaponPickup *pMsg = (CNetMsg_Sv_WeaponPickup *)pRawMsg;\n\t\tif(g_Config.m_ClAutoswitchWeapons)\n\t\t\tm_InputData.m_WantedWeapon = pMsg->m_Weapon+1;\n\t}\n}\n\nint CControls::SnapInput(int *pData)\n{\n\tstatic int64 LastSendTime = 0;\n\tbool Send = false;\n\n\t// update player state\n\tif(m_pClient->m_pChat->IsActive())\n\t\tm_InputData.m_PlayerFlags = PLAYERFLAG_CHATTING;\n\telse\n\t\tm_InputData.m_PlayerFlags = 0;\n\n\tif(m_pClient->m_pScoreboard->Active())\n\t\tm_InputData.m_PlayerFlags |= PLAYERFLAG_SCOREBOARD;\n\n\tif(m_LastData.m_PlayerFlags != m_InputData.m_PlayerFlags)\n\t\tSend = true;\n\n\tm_LastData.m_PlayerFlags = m_InputData.m_PlayerFlags;\n\n\t// we freeze the input if chat or menu is activated\n\tif(m_pClient->m_pChat->IsActive() || m_pClient->m_pMenus->IsActive())\n\t{\n\t\tOnReset();\n\n\t\tmem_copy(pData, &m_InputData, sizeof(m_InputData));\n\n\t\t// send once a second just to be sure\n\t\tif(time_get() > LastSendTime + time_freq())\n\t\t\tSend = true;\n\t}\n\telse\n\t{\n\n\t\tm_InputData.m_TargetX = (int)m_MousePos.x;\n\t\tm_InputData.m_TargetY = (int)m_MousePos.y;\n\t\tif(!m_InputData.m_TargetX && !m_InputData.m_TargetY)\n\t\t{\n\t\t\tm_InputData.m_TargetX = 1;\n\t\t\tm_MousePos.x = 1;\n\t\t}\n\n\t\t// set direction\n\t\tm_InputData.m_Direction = 0;\n\t\tif(m_InputDirectionLeft && !m_InputDirectionRight)\n\t\t\tm_InputData.m_Direction = -1;\n\t\tif(!m_InputDirectionLeft && m_InputDirectionRight)\n\t\t\tm_InputData.m_Direction = 1;\n\n\t\t// stress testing\n\t\tif(g_Config.m_DbgStress)\n\t\t{\n\t\t\tfloat t = Client()->LocalTime();\n\t\t\tmem_zero(&m_InputData, sizeof(m_InputData));\n\n\t\t\tm_InputData.m_Direction = ((int)t/2)%3-1;\n\t\t\tm_InputData.m_Jump = ((int)t)&1;\n\t\t\tm_InputData.m_Fire = ((int)(t*10));\n\t\t\tm_InputData.m_Hook = ((int)(t*2))&1;\n\t\t\tm_InputData.m_WantedWeapon = ((int)t)%NUM_WEAPONS;\n\t\t\tm_InputData.m_TargetX = (int)(sinf(t*3)*100.0f);\n\t\t\tm_InputData.m_TargetY = (int)(cosf(t*3)*100.0f);\n\t\t}\n\n\t\t// check if we need to send input\n\t\tif(m_InputData.m_Direction != m_LastData.m_Direction) Send = true;\n\t\telse if(m_InputData.m_Jump != m_LastData.m_Jump) Send = true;\n\t\telse if(m_InputData.m_Fire != m_LastData.m_Fire) Send = true;\n\t\telse if(m_InputData.m_Hook != m_LastData.m_Hook) Send = true;\n\t\telse if(m_InputData.m_WantedWeapon != m_LastData.m_WantedWeapon) Send = true;\n\t\telse if(m_InputData.m_NextWeapon != m_LastData.m_NextWeapon) Send = true;\n\t\telse if(m_InputData.m_PrevWeapon != m_LastData.m_PrevWeapon) Send = true;\n\n\t\t// send at at least 10hz\n\t\tif(time_get() > LastSendTime + time_freq()/25)\n\t\t\tSend = true;\n\t}\n\n\t// copy and return size\n\tm_LastData = m_InputData;\n\n\tif(!Send)\n\t\treturn 0;\n\n\tLastSendTime = time_get();\n\tmem_copy(pData, &m_InputData, sizeof(m_InputData));\n\treturn sizeof(m_InputData);\n}\n\nvoid CControls::OnRender()\n{\n\t// update target pos\n\tif(m_pClient->m_Snap.m_pGameData && !m_pClient->m_Snap.m_SpecInfo.m_Active)\n\t\tm_TargetPos = m_pClient->m_LocalCharacterPos + m_MousePos;\n\telse if(m_pClient->m_Snap.m_SpecInfo.m_Active && m_pClient->m_Snap.m_SpecInfo.m_UsePosition)\n\t\tm_TargetPos = m_pClient->m_Snap.m_SpecInfo.m_Position + m_MousePos;\n\telse\n\t\tm_TargetPos = m_MousePos;\n}\n\nbool CControls::OnMouseMove(float x, float y)\n{\n\tif((m_pClient->m_Snap.m_pGameData && m_pClient->m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_PAUSED|GAMESTATEFLAG_ROUNDOVER|GAMESTATEFLAG_GAMEOVER)) ||\n\t\t(m_pClient->m_Snap.m_SpecInfo.m_Active && m_pClient->m_pChat->IsActive()))\n\t\treturn false;\n\n\tm_MousePos += vec2(x, y); // TODO: ugly\n\tClampMousePos();\n\n\treturn true;\n}\n\nvoid CControls::ClampMousePos()\n{\n\tif(m_pClient->m_Snap.m_SpecInfo.m_Active && !m_pClient->m_Snap.m_SpecInfo.m_UsePosition)\n\t{\n\t\tm_MousePos.x = clamp(m_MousePos.x, 200.0f, Collision()->GetWidth()*32-200.0f);\n\t\tm_MousePos.y = clamp(m_MousePos.y, 200.0f, Collision()->GetHeight()*32-200.0f);\n\n\t}\n\telse\n\t{\n\t\tfloat CameraMaxDistance = 200.0f;\n\t\tfloat FollowFactor = g_Config.m_ClMouseFollowfactor/100.0f;\n\t\tfloat MouseMax = min(CameraMaxDistance/FollowFactor + g_Config.m_ClMouseDeadzone, (float)g_Config.m_ClMouseMaxDistance);\n\n\t\tif(length(m_MousePos) > MouseMax)\n\t\t\tm_MousePos = normalize(m_MousePos)*MouseMax;\n\t}\n}\n"
  },
  {
    "path": "src/game/client/components/controls.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_CONTROLS_H\n#define GAME_CLIENT_COMPONENTS_CONTROLS_H\n#include <base/vmath.h>\n#include <game/client/component.h>\n\nclass CControls : public CComponent\n{\npublic:\n\tvec2 m_MousePos;\n\tvec2 m_TargetPos;\n\n\tCNetObj_PlayerInput m_InputData;\n\tCNetObj_PlayerInput m_LastData;\n\tint m_InputDirectionLeft;\n\tint m_InputDirectionRight;\n\n\tCControls();\n\n\tvirtual void OnReset();\n\tvirtual void OnRelease();\n\tvirtual void OnRender();\n\tvirtual void OnMessage(int MsgType, void *pRawMsg);\n\tvirtual bool OnMouseMove(float x, float y);\n\tvirtual void OnConsoleInit();\n\tvirtual void OnPlayerDeath();\n\n\tint SnapInput(int *pData);\n\tvoid ClampMousePos();\n};\n#endif\n"
  },
  {
    "path": "src/game/client/components/countryflags.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/math.h>\n#include <base/system.h>\n\n#include <engine/console.h>\n#include <engine/graphics.h>\n#include <engine/storage.h>\n#include <engine/textrender.h>\n#include <engine/external/json-parser/json.h>\n#include <engine/shared/config.h>\n\n#include \"countryflags.h\"\n\n\nvoid CCountryFlags::LoadCountryflagsIndexfile()\n{\n\t// read file data into buffer\n\tconst char *pFilename = \"countryflags/index.json\";\n\tIOHANDLE File = Storage()->OpenFile(pFilename, IOFLAG_READ, IStorage::TYPE_ALL);\n\tif(!File)\n\t{\n\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"countryflags\", \"couldn't open index file\");\n\t\treturn;\n\t}\n\tint FileSize = (int)io_length(File);\n\tchar *pFileData = (char *)mem_alloc(FileSize+1, 1);\n\tio_read(File, pFileData, FileSize);\n\tpFileData[FileSize] = 0;\n\tio_close(File);\n\n\t// parse json data\n\tjson_settings JsonSettings;\n\tmem_zero(&JsonSettings, sizeof(JsonSettings));\n\tchar aError[256];\n\tjson_value *pJsonData = json_parse_ex(&JsonSettings, pFileData, aError);\n\tif(pJsonData == 0)\n\t{\n\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, pFilename, aError);\n\t\tmem_free(pFileData);\n\t\treturn;\n\t}\n\n\t// extract data\n\tconst json_value &rInit = (*pJsonData)[\"country codes\"];\n\tif(rInit.type == json_object)\n\t{\n\t\tenum\n\t\t{\n\t\t\tNUM_INDICES = 2,\n\t\t};\n\t\tconst char *paIndices[NUM_INDICES] = {\"custom\", \"ISO 3166-1\"};\n\t\tfor(int Index = 0; Index < NUM_INDICES; ++Index)\n\t\t{\n\t\t\tconst json_value &rStart = rInit[(const char *)paIndices[Index]];\n\t\t\tif(rStart.type == json_array)\n\t\t\t{\n\t\t\t\tfor(unsigned i = 0; i < rStart.u.array.length; ++i)\n\t\t\t\t{\n\t\t\t\t\tchar aBuf[64];\n\n\t\t\t\t\t// validate country code\n\t\t\t\t\tint CountryCode = (long)rStart[i][\"code\"];\n\t\t\t\t\tif(CountryCode < CODE_LB || CountryCode > CODE_UB)\n\t\t\t\t\t{\n\t\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"country code '%i' not within valid code range [%i..%i]\", CountryCode, CODE_LB, CODE_UB);\n\t\t\t\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"countryflags\", aBuf);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// add entry\n\t\t\t\t\tconst char *pCountryName = rStart[i][\"id\"];\n\t\t\t\t\tCCountryFlag CountryFlag;\n\t\t\t\t\tCountryFlag.m_CountryCode = CountryCode;\n\t\t\t\t\tstr_copy(CountryFlag.m_aCountryCodeString, pCountryName, sizeof(CountryFlag.m_aCountryCodeString));\n\t\t\t\t\tif(g_Config.m_ClLoadCountryFlags)\n\t\t\t\t\t{\n\t\t\t\t\t\t// load the graphic file\n\t\t\t\t\t\tCImageInfo Info;\n\t\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"countryflags/%s.png\", pCountryName);\n\t\t\t\t\t\tif(!Graphics()->LoadPNG(&Info, aBuf, IStorage::TYPE_ALL))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tchar aMsg[64];\n\t\t\t\t\t\t\tstr_format(aMsg, sizeof(aMsg), \"failed to load '%s'\", aBuf);\n\t\t\t\t\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"countryflags\", aMsg);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tCountryFlag.m_Texture = Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0);\n\t\t\t\t\t\tmem_free(Info.m_pData);\n\t\t\t\t\t}\n\t\t\t\t\tm_aCountryFlags.add_unsorted(CountryFlag);\n\t\t\n\t\t\t\t\t// print message\n\t\t\t\t\tif(g_Config.m_Debug)\n\t\t\t\t\t{\n\t\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"loaded country flag '%s'\", pCountryName);\n\t\t\t\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"countryflags\", aBuf);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// clean up\n\tjson_value_free(pJsonData);\n\tmem_free(pFileData);\n\tm_aCountryFlags.sort_range();\n\n\t// find index of default item\n\tint DefaultIndex = 0, Index = 0;\n\tfor(sorted_array<CCountryFlag>::range r = m_aCountryFlags.all(); !r.empty(); r.pop_front(), ++Index)\n\t\tif(r.front().m_CountryCode == -1)\n\t\t{\n\t\t\tDefaultIndex = Index;\n\t\t\tbreak;\n\t\t}\n\t\n\t// init LUT\n\tif(DefaultIndex != 0)\n\t\tfor(int i = 0; i < CODE_RANGE; ++i)\n\t\t\tm_CodeIndexLUT[i] = DefaultIndex;\n\telse\n\t\tmem_zero(m_CodeIndexLUT, sizeof(m_CodeIndexLUT));\n\tfor(int i = 0; i < m_aCountryFlags.size(); ++i)\n\t\tm_CodeIndexLUT[max(0, (m_aCountryFlags[i].m_CountryCode-CODE_LB)%CODE_RANGE)] = i;\n}\n\nvoid CCountryFlags::OnInit()\n{\n\t// load country flags\n\tm_aCountryFlags.clear();\n\tLoadCountryflagsIndexfile();\n\tif(!m_aCountryFlags.size())\n\t{\n\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"countryflags\", \"failed to load country flags. folder='countryflags/'\");\n\t\tCCountryFlag DummyEntry;\n\t\tDummyEntry.m_CountryCode = -1;\n\t\tmem_zero(DummyEntry.m_aCountryCodeString, sizeof(DummyEntry.m_aCountryCodeString));\n\t\tm_aCountryFlags.add(DummyEntry);\n\t}\n}\n\nint CCountryFlags::Num() const\n{\n\treturn m_aCountryFlags.size();\n}\n\nconst CCountryFlags::CCountryFlag *CCountryFlags::GetByCountryCode(int CountryCode) const\n{\n\treturn GetByIndex(m_CodeIndexLUT[max(0, (CountryCode-CODE_LB)%CODE_RANGE)]);\n}\n\nconst CCountryFlags::CCountryFlag *CCountryFlags::GetByIndex(int Index) const\n{\n\treturn &m_aCountryFlags[max(0, Index%m_aCountryFlags.size())];\n}\n\nvoid CCountryFlags::Render(int CountryCode, const vec4 *pColor, float x, float y, float w, float h)\n{\n\tconst CCountryFlag *pFlag = GetByCountryCode(CountryCode);\n\tif(pFlag->m_Texture.IsValid())\n\t{\n\t\tGraphics()->TextureSet(pFlag->m_Texture);\n\t\tGraphics()->QuadsBegin();\n\t\tGraphics()->SetColor(pColor->r, pColor->g, pColor->b, pColor->a);\n\t\tIGraphics::CQuadItem QuadItem(x, y, w, h);\n\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t\tGraphics()->QuadsEnd();\n\t}\n\telse\n\t{\n\t\tCTextCursor Cursor;\n\t\tTextRender()->SetCursor(&Cursor, x, y, 10.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\t\tCursor.m_LineWidth = w;\n\t\tTextRender()->TextEx(&Cursor, pFlag->m_aCountryCodeString, -1);\n\t}\n}\n"
  },
  {
    "path": "src/game/client/components/countryflags.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_COUNTRYFLAGS_H\n#define GAME_CLIENT_COMPONENTS_COUNTRYFLAGS_H\n#include <base/vmath.h>\n#include <base/tl/sorted_array.h>\n#include <game/client/component.h>\n\nclass CCountryFlags : public CComponent\n{\npublic:\n\tstruct CCountryFlag\n\t{\n\t\tint m_CountryCode;\n\t\tchar m_aCountryCodeString[8];\n\t\tIGraphics::CTextureHandle m_Texture;\n\n\t\tbool operator<(const CCountryFlag &Other) { return str_comp(m_aCountryCodeString, Other.m_aCountryCodeString) < 0; }\n\t};\n\n\tvoid OnInit();\n\n\tint Num() const;\n\tconst CCountryFlag *GetByCountryCode(int CountryCode) const;\n\tconst CCountryFlag *GetByIndex(int Index) const;\n\tvoid Render(int CountryCode, const vec4 *pColor, float x, float y, float w, float h);\n\nprivate:\n\tenum\n\t{\n\t\tCODE_LB=-1,\n\t\tCODE_UB=999,\n\t\tCODE_RANGE=CODE_UB-CODE_LB+1,\n\t};\n\tsorted_array<CCountryFlag> m_aCountryFlags;\n\tint m_CodeIndexLUT[CODE_RANGE];\n\n\tvoid LoadCountryflagsIndexfile();\n};\n#endif\n"
  },
  {
    "path": "src/game/client/components/damageind.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/demo.h>\n#include <engine/graphics.h>\n#include <game/generated/protocol.h>\n#include <game/generated/client_data.h>\n\n#include <game/gamecore.h> // get_angle\n#include <game/client/ui.h>\n#include <game/client/render.h>\n#include \"damageind.h\"\n\nCDamageInd::CDamageInd()\n{\n\tm_NumItems = 0;\n}\n\nCDamageInd::CItem *CDamageInd::CreateI()\n{\n\tif (m_NumItems < MAX_ITEMS)\n\t{\n\t\tCItem *p = &m_aItems[m_NumItems];\n\t\tm_NumItems++;\n\t\treturn p;\n\t}\n\treturn 0;\n}\n\nvoid CDamageInd::DestroyI(CDamageInd::CItem *i)\n{\n\tm_NumItems--;\n\t*i = m_aItems[m_NumItems];\n}\n\nvoid CDamageInd::Create(vec2 Pos, vec2 Dir)\n{\n\tCItem *i = CreateI();\n\tif (i)\n\t{\n\t\ti->m_Pos = Pos;\n\t\ti->m_StartTime = Client()->LocalTime();\n\t\ti->m_Dir = Dir*-1;\n\t\ti->m_StartAngle = (( (float)rand()/(float)RAND_MAX) - 1.0f) * 2.0f * pi;\n\t}\n}\n\nvoid CDamageInd::OnRender()\n{\n\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);\n\tGraphics()->QuadsBegin();\n\tstatic float s_LastLocalTime = Client()->LocalTime();\n\tfor(int i = 0; i < m_NumItems;)\n\t{\n\t\tif(Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t\t{\n\t\t\tconst IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo();\n\t\t\tif(pInfo->m_Paused)\n\t\t\t\tm_aItems[i].m_StartTime += Client()->LocalTime()-s_LastLocalTime;\n\t\t\telse\n\t\t\t\tm_aItems[i].m_StartTime += (Client()->LocalTime()-s_LastLocalTime)*(1.0f-pInfo->m_Speed);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(m_pClient->m_Snap.m_pGameData && m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED)\n\t\t\t\tm_aItems[i].m_StartTime += Client()->LocalTime()-s_LastLocalTime;\n\t\t}\n\n\t\tfloat Life = 0.75f - (Client()->LocalTime() - m_aItems[i].m_StartTime);\n\t\tif(Life < 0.0f)\n\t\t\tDestroyI(&m_aItems[i]);\n\t\telse\n\t\t{\n\t\t\tvec2 Pos = mix(m_aItems[i].m_Pos+m_aItems[i].m_Dir*75.0f, m_aItems[i].m_Pos, clamp((Life-0.60f)/0.15f, 0.0f, 1.0f));\n\t\t\tGraphics()->SetColor(1.0f,1.0f,1.0f, Life/0.1f);\n\t\t\tGraphics()->QuadsSetRotation(m_aItems[i].m_StartAngle + Life * 2.0f);\n\t\t\tRenderTools()->SelectSprite(SPRITE_STAR1);\n\t\t\tRenderTools()->DrawSprite(Pos.x, Pos.y, 48.0f);\n\t\t\ti++;\n\t\t}\n\t}\n\ts_LastLocalTime = Client()->LocalTime();\n\tGraphics()->QuadsEnd();\n}\n\nvoid CDamageInd::OnReset()\n{\n\tm_NumItems = 0;\n}\n"
  },
  {
    "path": "src/game/client/components/damageind.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_DAMAGEIND_H\n#define GAME_CLIENT_COMPONENTS_DAMAGEIND_H\n#include <base/vmath.h>\n#include <game/client/component.h>\n\nclass CDamageInd : public CComponent\n{\n\tstruct CItem\n\t{\n\t\tvec2 m_Pos;\n\t\tvec2 m_Dir;\n\t\tfloat m_StartTime;\n\t\tfloat m_StartAngle;\n\t};\n\n\tenum\n\t{\n\t\tMAX_ITEMS=64,\n\t};\n\n\tCItem m_aItems[MAX_ITEMS];\n\tint m_NumItems;\n\n\tCItem *CreateI();\n\tvoid DestroyI(CItem *i);\n\npublic:\n\tCDamageInd();\n\n\tvoid Create(vec2 Pos, vec2 Dir);\n\tvirtual void OnRender();\n\tvirtual void OnReset();\n};\n#endif\n"
  },
  {
    "path": "src/game/client/components/debughud.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/shared/config.h>\n#include <engine/graphics.h>\n#include <engine/textrender.h>\n\n#include <game/generated/protocol.h>\n#include <game/generated/client_data.h>\n\n#include <game/layers.h>\n\n#include <game/client/gameclient.h>\n#include <game/client/animstate.h>\n#include <game/client/render.h>\n\n//#include \"controls.h\"\n//#include \"camera.h\"\n#include \"debughud.h\"\n\nvoid CDebugHud::RenderNetCorrections()\n{\n\tif(!g_Config.m_Debug || g_Config.m_DbgGraphs || !m_pClient->m_Snap.m_pLocalCharacter || !m_pClient->m_Snap.m_pLocalPrevCharacter)\n\t\treturn;\n\n\tfloat Width = 300*Graphics()->ScreenAspect();\n\tGraphics()->MapScreen(0, 0, Width, 300);\n\n\t/*float speed = distance(vec2(netobjects.local_prev_character->x, netobjects.local_prev_character->y),\n\t\tvec2(netobjects.local_character->x, netobjects.local_character->y));*/\n\n\tfloat Velspeed = length(vec2(m_pClient->m_Snap.m_pLocalCharacter->m_VelX/256.0f, m_pClient->m_Snap.m_pLocalCharacter->m_VelY/256.0f))*50;\n\tfloat Ramp = VelocityRamp(Velspeed, m_pClient->m_Tuning.m_VelrampStart, m_pClient->m_Tuning.m_VelrampRange, m_pClient->m_Tuning.m_VelrampCurvature);\n\n\tconst char *paStrings[] = {\"velspeed:\", \"velspeed*ramp:\", \"ramp:\", \"Pos\", \" x:\", \" y:\", \"netobj corrections\", \" num:\", \" on:\"};\n\tconst int Num = sizeof(paStrings)/sizeof(char *);\n\tconst float LineHeight = 6.0f;\n\tconst float Fontsize = 5.0f;\n\n\tfloat x = Width-100.0f, y = 50.0f;\n\tfor(int i = 0; i < Num; ++i)\n\t\tTextRender()->Text(0, x, y+i*LineHeight, Fontsize, paStrings[i], -1);\n\n\tx = Width-10.0f;\n\tchar aBuf[128];\n\tstr_format(aBuf, sizeof(aBuf), \"%.0f\", Velspeed/32);\n\tfloat w = TextRender()->TextWidth(0, Fontsize, aBuf, -1);\n\tTextRender()->Text(0, x-w, y, Fontsize, aBuf, -1);\n\ty += LineHeight;\n\tstr_format(aBuf, sizeof(aBuf), \"%.0f\", Velspeed/32*Ramp);\n\tw = TextRender()->TextWidth(0, Fontsize, aBuf, -1);\n\tTextRender()->Text(0, x-w, y, Fontsize, aBuf, -1);\n\ty += LineHeight;\n\tstr_format(aBuf, sizeof(aBuf), \"%.2f\", Ramp);\n\tw = TextRender()->TextWidth(0, Fontsize, aBuf, -1);\n\tTextRender()->Text(0, x-w, y, Fontsize, aBuf, -1);\n\ty += 2*LineHeight;\n\tstr_format(aBuf, sizeof(aBuf), \"%d\", m_pClient->m_Snap.m_pLocalCharacter->m_X/32);\n\tw = TextRender()->TextWidth(0, Fontsize, aBuf, -1);\n\tTextRender()->Text(0, x-w, y, Fontsize, aBuf, -1);\n\ty += LineHeight;\n\tstr_format(aBuf, sizeof(aBuf), \"%d\", m_pClient->m_Snap.m_pLocalCharacter->m_Y/32);\n\tw = TextRender()->TextWidth(0, Fontsize, aBuf, -1);\n\tTextRender()->Text(0, x-w, y, Fontsize, aBuf, -1);\n\ty += 2*LineHeight;\n\tstr_format(aBuf, sizeof(aBuf), \"%d\", m_pClient->NetobjNumCorrections());\n\tw = TextRender()->TextWidth(0, Fontsize, aBuf, -1);\n\tTextRender()->Text(0, x-w, y, Fontsize, aBuf, -1);\n\ty += LineHeight;\n\tw = TextRender()->TextWidth(0, Fontsize, m_pClient->NetobjCorrectedOn(), -1);\n\tTextRender()->Text(0, x-w, y, Fontsize, m_pClient->NetobjCorrectedOn(), -1);\n}\n\nvoid CDebugHud::RenderTuning()\n{\n\t// render tuning debugging\n\tif(!g_Config.m_DbgTuning)\n\t\treturn;\n\n\tCTuningParams StandardTuning;\n\n\tGraphics()->MapScreen(0, 0, 300*Graphics()->ScreenAspect(), 300);\n\n\tfloat y = 50.0f;\n\tint Count = 0;\n\tfor(int i = 0; i < m_pClient->m_Tuning.Num(); i++)\n\t{\n\t\tchar aBuf[128];\n\t\tfloat Current, Standard;\n\t\tm_pClient->m_Tuning.Get(i, &Current);\n\t\tStandardTuning.Get(i, &Standard);\n\n\t\tif(Standard == Current)\n\t\t\tTextRender()->TextColor(1,1,1,1.0f);\n\t\telse\n\t\t\tTextRender()->TextColor(1,0.25f,0.25f,1.0f);\n\n\t\tfloat w;\n\t\tfloat x = 5.0f;\n\n\t\tstr_format(aBuf, sizeof(aBuf), \"%.2f\", Standard);\n\t\tx += 20.0f;\n\t\tw = TextRender()->TextWidth(0, 5, aBuf, -1);\n\t\tTextRender()->Text(0x0, x-w, y+Count*6, 5, aBuf, -1);\n\n\t\tstr_format(aBuf, sizeof(aBuf), \"%.2f\", Current);\n\t\tx += 20.0f;\n\t\tw = TextRender()->TextWidth(0, 5, aBuf, -1);\n\t\tTextRender()->Text(0x0, x-w, y+Count*6, 5, aBuf, -1);\n\n\t\tx += 5.0f;\n\t\tTextRender()->Text(0x0, x, y+Count*6, 5, m_pClient->m_Tuning.m_apNames[i], -1);\n\n\t\tCount++;\n\t}\n\n\ty = y+Count*6;\n\n\tGraphics()->TextureClear();\n\tGraphics()->BlendNormal();\n\tGraphics()->LinesBegin();\n\tfloat Height = 50.0f;\n\tfloat pv = 1;\n\tIGraphics::CLineItem Array[100];\n\tfor(int i = 0; i < 100; i++)\n\t{\n\t\tfloat Speed = i/100.0f * 3000;\n\t\tfloat Ramp = VelocityRamp(Speed, m_pClient->m_Tuning.m_VelrampStart, m_pClient->m_Tuning.m_VelrampRange, m_pClient->m_Tuning.m_VelrampCurvature);\n\t\tfloat RampedSpeed = (Speed * Ramp)/1000.0f;\n\t\tArray[i] = IGraphics::CLineItem((i-1)*2, y+Height-pv*Height, i*2, y+Height-RampedSpeed*Height);\n\t\t//Graphics()->LinesDraw((i-1)*2, 200, i*2, 200);\n\t\tpv = RampedSpeed;\n\t}\n\tGraphics()->LinesDraw(Array, 100);\n\tGraphics()->LinesEnd();\n\tTextRender()->TextColor(1,1,1,1);\n}\n\nvoid CDebugHud::OnRender()\n{\n\tRenderTuning();\n\tRenderNetCorrections();\n}\n"
  },
  {
    "path": "src/game/client/components/debughud.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_DEBUGHUD_H\n#define GAME_CLIENT_COMPONENTS_DEBUGHUD_H\n#include <game/client/component.h>\n\nclass CDebugHud : public CComponent\n{\n\tvoid RenderNetCorrections();\n\tvoid RenderTuning();\npublic:\n\tvirtual void OnRender();\n};\n\n#endif\n"
  },
  {
    "path": "src/game/client/components/effects.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/demo.h>\n#include <engine/engine.h>\n\n#include <engine/shared/config.h>\n\n#include <game/generated/client_data.h>\n\n#include <game/client/components/particles.h>\n#include <game/client/components/skins.h>\n#include <game/client/components/flow.h>\n#include <game/client/components/damageind.h>\n#include <game/client/components/sounds.h>\n#include <game/client/gameclient.h>\n\n#include \"effects.h\"\n\ninline vec2 RandomDir() { return normalize(vec2(frandom()-0.5f, frandom()-0.5f)); }\n\nCEffects::CEffects()\n{\n\tm_Add50hz = false;\n\tm_Add100hz = false;\n}\n\nvoid CEffects::AirJump(vec2 Pos)\n{\n\tCParticle p;\n\tp.SetDefault();\n\tp.m_Spr = SPRITE_PART_AIRJUMP;\n\tp.m_Pos = Pos + vec2(-6.0f, 16.0f);\n\tp.m_Vel = vec2(0, -200);\n\tp.m_LifeSpan = 0.5f;\n\tp.m_StartSize = 48.0f;\n\tp.m_EndSize = 0;\n\tp.m_Rot = frandom()*pi*2;\n\tp.m_Rotspeed = pi*2;\n\tp.m_Gravity = 500;\n\tp.m_Friction = 0.7f;\n\tp.m_FlowAffected = 0.0f;\n\tm_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p);\n\n\tp.m_Pos = Pos + vec2(6.0f, 16.0f);\n\tm_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p);\n\n\tm_pClient->m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_PLAYER_AIRJUMP, 1.0f, Pos);\n}\n\nvoid CEffects::DamageIndicator(vec2 Pos, vec2 Dir)\n{\n\tm_pClient->m_pDamageind->Create(Pos, Dir);\n}\n\nvoid CEffects::PowerupShine(vec2 Pos, vec2 size)\n{\n\tif(!m_Add50hz)\n\t\treturn;\n\n\tCParticle p;\n\tp.SetDefault();\n\tp.m_Spr = SPRITE_PART_SLICE;\n\tp.m_Pos = Pos + vec2((frandom()-0.5f)*size.x, (frandom()-0.5f)*size.y);\n\tp.m_Vel = vec2(0, 0);\n\tp.m_LifeSpan = 0.5f;\n\tp.m_StartSize = 16.0f;\n\tp.m_EndSize = 0;\n\tp.m_Rot = frandom()*pi*2;\n\tp.m_Rotspeed = pi*2;\n\tp.m_Gravity = 500;\n\tp.m_Friction = 0.9f;\n\tp.m_FlowAffected = 0.0f;\n\tm_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p);\n}\n\nvoid CEffects::SmokeTrail(vec2 Pos, vec2 Vel)\n{\n\tif(!m_Add50hz)\n\t\treturn;\n\n\tCParticle p;\n\tp.SetDefault();\n\tp.m_Spr = SPRITE_PART_SMOKE;\n\tp.m_Pos = Pos;\n\tp.m_Vel = Vel + RandomDir()*50.0f;\n\tp.m_LifeSpan = 0.5f + frandom()*0.5f;\n\tp.m_StartSize = 12.0f + frandom()*8;\n\tp.m_EndSize = 0;\n\tp.m_Friction = 0.7f;\n\tp.m_Gravity = frandom()*-500.0f;\n\tm_pClient->m_pParticles->Add(CParticles::GROUP_PROJECTILE_TRAIL, &p);\n}\n\n\nvoid CEffects::SkidTrail(vec2 Pos, vec2 Vel)\n{\n\tif(!m_Add100hz)\n\t\treturn;\n\n\tCParticle p;\n\tp.SetDefault();\n\tp.m_Spr = SPRITE_PART_SMOKE;\n\tp.m_Pos = Pos;\n\tp.m_Vel = Vel + RandomDir()*50.0f;\n\tp.m_LifeSpan = 0.5f + frandom()*0.5f;\n\tp.m_StartSize = 24.0f + frandom()*12;\n\tp.m_EndSize = 0;\n\tp.m_Friction = 0.7f;\n\tp.m_Gravity = frandom()*-500.0f;\n\tp.m_Color = vec4(0.75f,0.75f,0.75f,1.0f);\n\tm_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p);\n}\n\nvoid CEffects::BulletTrail(vec2 Pos)\n{\n\tif(!m_Add100hz)\n\t\treturn;\n\n\tCParticle p;\n\tp.SetDefault();\n\tp.m_Spr = SPRITE_PART_BALL;\n\tp.m_Pos = Pos;\n\tp.m_LifeSpan = 0.25f + frandom()*0.25f;\n\tp.m_StartSize = 8.0f;\n\tp.m_EndSize = 0;\n\tp.m_Friction = 0.7f;\n\tm_pClient->m_pParticles->Add(CParticles::GROUP_PROJECTILE_TRAIL, &p);\n}\n\nvoid CEffects::PlayerSpawn(vec2 Pos)\n{\n\tfor(int i = 0; i < 32; i++)\n\t{\n\t\tCParticle p;\n\t\tp.SetDefault();\n\t\tp.m_Spr = SPRITE_PART_SHELL;\n\t\tp.m_Pos = Pos;\n\t\tp.m_Vel = RandomDir() * (powf(frandom(), 3)*600.0f);\n\t\tp.m_LifeSpan = 0.3f + frandom()*0.3f;\n\t\tp.m_StartSize = 64.0f + frandom()*32;\n\t\tp.m_EndSize = 0;\n\t\tp.m_Rot = frandom()*pi*2;\n\t\tp.m_Rotspeed = frandom();\n\t\tp.m_Gravity = frandom()*-400.0f;\n\t\tp.m_Friction = 0.7f;\n\t\tp.m_Color = vec4(0xb5/255.0f, 0x50/255.0f, 0xcb/255.0f, 1.0f);\n\t\tm_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p);\n\n\t}\n\tm_pClient->m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_PLAYER_SPAWN, 1.0f, Pos);\n}\n\nvoid CEffects::PlayerDeath(vec2 Pos, int ClientID)\n{\n\tvec3 BloodColor(1.0f,1.0f,1.0f);\n\n\tif(ClientID >= 0)\n\t{\n\t\tif(m_pClient->m_aClients[ClientID].m_aUseCustomColors[CSkins::SKINPART_BODY])\n\t\t\tBloodColor = m_pClient->m_pSkins->GetColorV3(m_pClient->m_aClients[ClientID].m_aSkinPartColors[CSkins::SKINPART_BODY]);\n\t\telse\n\t\t{\n\t\t\tconst CSkins::CSkinPart *s = m_pClient->m_pSkins->GetSkinPart(CSkins::SKINPART_BODY, m_pClient->m_aClients[ClientID].m_SkinPartIDs[CSkins::SKINPART_BODY]);\n\t\t\tif(s)\n\t\t\t\tBloodColor = s->m_BloodColor;\n\t\t}\n\t}\n\n\tfor(int i = 0; i < 64; i++)\n\t{\n\t\tCParticle p;\n\t\tp.SetDefault();\n\t\tp.m_Spr = SPRITE_PART_SPLAT01 + (rand()%3);\n\t\tp.m_Pos = Pos;\n\t\tp.m_Vel = RandomDir() * ((frandom()+0.1f)*900.0f);\n\t\tp.m_LifeSpan = 0.3f + frandom()*0.3f;\n\t\tp.m_StartSize = 24.0f + frandom()*16;\n\t\tp.m_EndSize = 0;\n\t\tp.m_Rot = frandom()*pi*2;\n\t\tp.m_Rotspeed = (frandom()-0.5f) * pi;\n\t\tp.m_Gravity = 800.0f;\n\t\tp.m_Friction = 0.8f;\n\t\tvec3 c = BloodColor * (0.75f + frandom()*0.25f);\n\t\tp.m_Color = vec4(c.r, c.g, c.b, 0.75f);\n\t\tm_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p);\n\t}\n}\n\n\nvoid CEffects::Explosion(vec2 Pos)\n{\n\t// add to flow\n\tfor(int y = -8; y <= 8; y++)\n\t\tfor(int x = -8; x <= 8; x++)\n\t\t{\n\t\t\tif(x == 0 && y == 0)\n\t\t\t\tcontinue;\n\n\t\t\tfloat a = 1 - (length(vec2(x,y)) / length(vec2(8,8)));\n\t\t\tm_pClient->m_pFlow->Add(Pos+vec2(x,y)*16, normalize(vec2(x,y))*5000.0f*a, 10.0f);\n\t\t}\n\n\t// add the explosion\n\tCParticle p;\n\tp.SetDefault();\n\tp.m_Spr = SPRITE_PART_EXPL01;\n\tp.m_Pos = Pos;\n\tp.m_LifeSpan = 0.4f;\n\tp.m_StartSize = 150.0f;\n\tp.m_EndSize = 0;\n\tp.m_Rot = frandom()*pi*2;\n\tm_pClient->m_pParticles->Add(CParticles::GROUP_EXPLOSIONS, &p);\n\n\t// add the smoke\n\tfor(int i = 0; i < 24; i++)\n\t{\n\t\tCParticle p;\n\t\tp.SetDefault();\n\t\tp.m_Spr = SPRITE_PART_SMOKE;\n\t\tp.m_Pos = Pos;\n\t\tp.m_Vel = RandomDir() * ((1.0f + frandom()*0.2f) * 1000.0f);\n\t\tp.m_LifeSpan = 0.5f + frandom()*0.4f;\n\t\tp.m_StartSize = 32.0f + frandom()*8;\n\t\tp.m_EndSize = 0;\n\t\tp.m_Gravity = frandom()*-800.0f;\n\t\tp.m_Friction = 0.4f;\n\t\tp.m_Color = mix(vec4(0.75f,0.75f,0.75f,1.0f), vec4(0.5f,0.5f,0.5f,1.0f), frandom());\n\t\tm_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p);\n\t}\n}\n\n\nvoid CEffects::HammerHit(vec2 Pos)\n{\n\t// add the explosion\n\tCParticle p;\n\tp.SetDefault();\n\tp.m_Spr = SPRITE_PART_HIT01;\n\tp.m_Pos = Pos;\n\tp.m_LifeSpan = 0.3f;\n\tp.m_StartSize = 120.0f;\n\tp.m_EndSize = 0;\n\tp.m_Rot = frandom()*pi*2;\n\tm_pClient->m_pParticles->Add(CParticles::GROUP_EXPLOSIONS, &p);\n\tm_pClient->m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_HAMMER_HIT, 1.0f, Pos);\n}\n\nvoid CEffects::OnRender()\n{\n\tstatic int64 LastUpdate100hz = 0;\n\tstatic int64 LastUpdate50hz = 0;\n\n\tif(Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tconst IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo();\n\n\t\tif(time_get()-LastUpdate100hz > time_freq()/(100*pInfo->m_Speed))\n\t\t{\n\t\t\tm_Add100hz = true;\n\t\t\tLastUpdate100hz = time_get();\n\t\t}\n\t\telse\n\t\t\tm_Add100hz = false;\n\n\t\tif(time_get()-LastUpdate50hz > time_freq()/(100*pInfo->m_Speed))\n\t\t{\n\t\t\tm_Add50hz = true;\n\t\t\tLastUpdate50hz = time_get();\n\t\t}\n\t\telse\n\t\t\tm_Add50hz = false;\n\n\t\tif(m_Add50hz)\n\t\t\tm_pClient->m_pFlow->Update();\n\n\t\treturn;\n\t}\n\n\tif(time_get()-LastUpdate100hz > time_freq()/100)\n\t{\n\t\tm_Add100hz = true;\n\t\tLastUpdate100hz = time_get();\n\t}\n\telse\n\t\tm_Add100hz = false;\n\n\tif(time_get()-LastUpdate50hz > time_freq()/100)\n\t{\n\t\tm_Add50hz = true;\n\t\tLastUpdate50hz = time_get();\n\t}\n\telse\n\t\tm_Add50hz = false;\n\n\tif(m_Add50hz)\n\t\tm_pClient->m_pFlow->Update();\n}\n"
  },
  {
    "path": "src/game/client/components/effects.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_EFFECTS_H\n#define GAME_CLIENT_COMPONENTS_EFFECTS_H\n#include <game/client/component.h>\n\nclass CEffects : public CComponent\n{\n\tbool m_Add50hz;\n\tbool m_Add100hz;\npublic:\n\tCEffects();\n\n\tvirtual void OnRender();\n\n\tvoid BulletTrail(vec2 Pos);\n\tvoid SmokeTrail(vec2 Pos, vec2 Vel);\n\tvoid SkidTrail(vec2 Pos, vec2 Vel);\n\tvoid Explosion(vec2 Pos);\n\tvoid HammerHit(vec2 Pos);\n\tvoid AirJump(vec2 Pos);\n\tvoid DamageIndicator(vec2 Pos, vec2 Dir);\n\tvoid PlayerSpawn(vec2 Pos);\n\tvoid PlayerDeath(vec2 Pos, int ClientID);\n\tvoid PowerupShine(vec2 Pos, vec2 Size);\n\n\tvoid Update();\n};\n#endif\n"
  },
  {
    "path": "src/game/client/components/emoticon.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/graphics.h>\n#include <engine/shared/config.h>\n#include <game/generated/protocol.h>\n#include <game/generated/client_data.h>\n\n#include <game/gamecore.h> // get_angle\n#include <game/client/ui.h>\n#include <game/client/render.h>\n#include \"emoticon.h\"\n\nCEmoticon::CEmoticon()\n{\n\tOnReset();\n}\n\nvoid CEmoticon::ConKeyEmoticon(IConsole::IResult *pResult, void *pUserData)\n{\n\tCEmoticon *pSelf = (CEmoticon *)pUserData;\n\tif(!pSelf->m_pClient->m_Snap.m_SpecInfo.m_Active && pSelf->Client()->State() != IClient::STATE_DEMOPLAYBACK)\n\t\tpSelf->m_Active = pResult->GetInteger(0) != 0;\n}\n\nvoid CEmoticon::ConEmote(IConsole::IResult *pResult, void *pUserData)\n{\n\t((CEmoticon *)pUserData)->Emote(pResult->GetInteger(0));\n}\n\nvoid CEmoticon::OnConsoleInit()\n{\n\tConsole()->Register(\"+emote\", \"\", CFGFLAG_CLIENT, ConKeyEmoticon, this, \"Open emote selector\");\n\tConsole()->Register(\"emote\", \"i\", CFGFLAG_CLIENT, ConEmote, this, \"Use emote\");\n}\n\nvoid CEmoticon::OnReset()\n{\n\tm_WasActive = false;\n\tm_Active = false;\n\tm_SelectedEmote = -1;\n}\n\nvoid CEmoticon::OnRelease()\n{\n\tm_Active = false;\n}\n\nvoid CEmoticon::OnMessage(int MsgType, void *pRawMsg)\n{\n}\n\nbool CEmoticon::OnMouseMove(float x, float y)\n{\n\tif(!m_Active)\n\t\treturn false;\n\n\tUI()->ConvertMouseMove(&x, &y);\n\tm_SelectorMouse += vec2(x,y);\n\treturn true;\n}\n\nvoid CEmoticon::DrawCircle(float x, float y, float r, int Segments)\n{\n\tIGraphics::CFreeformItem Array[32];\n\tint NumItems = 0;\n\tfloat FSegments = (float)Segments;\n\tfor(int i = 0; i < Segments; i+=2)\n\t{\n\t\tfloat a1 = i/FSegments * 2*pi;\n\t\tfloat a2 = (i+1)/FSegments * 2*pi;\n\t\tfloat a3 = (i+2)/FSegments * 2*pi;\n\t\tfloat Ca1 = cosf(a1);\n\t\tfloat Ca2 = cosf(a2);\n\t\tfloat Ca3 = cosf(a3);\n\t\tfloat Sa1 = sinf(a1);\n\t\tfloat Sa2 = sinf(a2);\n\t\tfloat Sa3 = sinf(a3);\n\n\t\tArray[NumItems++] = IGraphics::CFreeformItem(\n\t\t\tx, y,\n\t\t\tx+Ca1*r, y+Sa1*r,\n\t\t\tx+Ca3*r, y+Sa3*r,\n\t\t\tx+Ca2*r, y+Sa2*r);\n\t\tif(NumItems == 32)\n\t\t{\n\t\t\tm_pClient->Graphics()->QuadsDrawFreeform(Array, 32);\n\t\t\tNumItems = 0;\n\t\t}\n\t}\n\tif(NumItems)\n\t\tm_pClient->Graphics()->QuadsDrawFreeform(Array, NumItems);\n}\n\n\nvoid CEmoticon::OnRender()\n{\n\tif(!m_Active)\n\t{\n\t\tif(m_WasActive && m_SelectedEmote != -1)\n\t\t\tEmote(m_SelectedEmote);\n\t\tm_WasActive = false;\n\t\treturn;\n\t}\n\n\tif(m_pClient->m_Snap.m_SpecInfo.m_Active)\n\t{\n\t\tm_Active = false;\n\t\tm_WasActive = false;\n\t\treturn;\n\t}\n\n\tm_WasActive = true;\n\n\tif (length(m_SelectorMouse) > 170.0f)\n\t\tm_SelectorMouse = normalize(m_SelectorMouse) * 170.0f;\n\n\tfloat SelectedAngle = GetAngle(m_SelectorMouse) + 2*pi/24;\n\tif (SelectedAngle < 0)\n\t\tSelectedAngle += 2*pi;\n\n\tif (length(m_SelectorMouse) > 110.0f)\n\t\tm_SelectedEmote = (int)(SelectedAngle / (2*pi) * NUM_EMOTICONS);\n\n\tCUIRect Screen = *UI()->Screen();\n\n\tGraphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h);\n\n\tGraphics()->BlendNormal();\n\n\tGraphics()->TextureClear();\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(0,0,0,0.3f);\n\tDrawCircle(Screen.w/2, Screen.h/2, 190.0f, 64);\n\tGraphics()->QuadsEnd();\n\n\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_EMOTICONS].m_Id);\n\tGraphics()->QuadsBegin();\n\n\tfor (int i = 0; i < NUM_EMOTICONS; i++)\n\t{\n\t\tfloat Angle = 2*pi*i/NUM_EMOTICONS;\n\t\tif (Angle > pi)\n\t\t\tAngle -= 2*pi;\n\n\t\tbool Selected = m_SelectedEmote == i;\n\n\t\tfloat Size = Selected ? 80.0f : 50.0f;\n\n\t\tfloat NudgeX = 150.0f * cosf(Angle);\n\t\tfloat NudgeY = 150.0f * sinf(Angle);\n\t\tRenderTools()->SelectSprite(SPRITE_OOP + i);\n\t\tIGraphics::CQuadItem QuadItem(Screen.w/2 + NudgeX, Screen.h/2 + NudgeY, Size, Size);\n\t\tGraphics()->QuadsDraw(&QuadItem, 1);\n\t}\n\n\tGraphics()->QuadsEnd();\n\n\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_CURSOR].m_Id);\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(1,1,1,1);\n\tIGraphics::CQuadItem QuadItem(m_SelectorMouse.x+Screen.w/2,m_SelectorMouse.y+Screen.h/2,24,24);\n\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n}\n\nvoid CEmoticon::Emote(int Emoticon)\n{\n\tCNetMsg_Cl_Emoticon Msg;\n\tMsg.m_Emoticon = Emoticon;\n\tClient()->SendPackMsg(&Msg, MSGFLAG_VITAL);\n}\n"
  },
  {
    "path": "src/game/client/components/emoticon.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_EMOTICON_H\n#define GAME_CLIENT_COMPONENTS_EMOTICON_H\n#include <base/vmath.h>\n#include <game/client/component.h>\n\nclass CEmoticon : public CComponent\n{\n\tvoid DrawCircle(float x, float y, float r, int Segments);\n\n\tbool m_WasActive;\n\tbool m_Active;\n\n\tvec2 m_SelectorMouse;\n\tint m_SelectedEmote;\n\n\tstatic void ConKeyEmoticon(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConEmote(IConsole::IResult *pResult, void *pUserData);\n\npublic:\n\tCEmoticon();\n\n\tvirtual void OnReset();\n\tvirtual void OnConsoleInit();\n\tvirtual void OnRender();\n\tvirtual void OnRelease();\n\tvirtual void OnMessage(int MsgType, void *pRawMsg);\n\tvirtual bool OnMouseMove(float x, float y);\n\n\tvoid Emote(int Emoticon);\n};\n\n#endif\n"
  },
  {
    "path": "src/game/client/components/flow.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/graphics.h>\n#include <game/mapitems.h>\n#include <game/layers.h>\n#include \"flow.h\"\n\nCFlow::CFlow()\n{\n\tm_pCells = 0;\n\tm_Height = 0;\n\tm_Width = 0;\n\tm_Spacing = 16;\n}\n\nvoid CFlow::DbgRender()\n{\n\tif(!m_pCells)\n\t\treturn;\n\n\tIGraphics::CLineItem Array[1024];\n\tint NumItems = 0;\n\tGraphics()->TextureClear();\n\tGraphics()->LinesBegin();\n\tfor(int y = 0; y < m_Height; y++)\n\t\tfor(int x = 0; x < m_Width; x++)\n\t\t{\n\t\t\tvec2 Pos(x*m_Spacing, y*m_Spacing);\n\t\t\tvec2 Vel = m_pCells[y*m_Width+x].m_Vel * 0.01f;\n\t\t\tArray[NumItems++] = IGraphics::CLineItem(Pos.x, Pos.y, Pos.x+Vel.x, Pos.y+Vel.y);\n\t\t\tif(NumItems == 1024)\n\t\t\t{\n\t\t\t\tGraphics()->LinesDraw(Array, 1024);\n\t\t\t\tNumItems = 0;\n\t\t\t}\n\t\t}\n\n\tif(NumItems)\n\t\tGraphics()->LinesDraw(Array, NumItems);\n\tGraphics()->LinesEnd();\n}\n\nvoid CFlow::Init()\n{\n\tif(m_pCells)\n\t{\n\t\tmem_free(m_pCells);\n\t\tm_pCells = 0;\n\t}\n\n\tCMapItemLayerTilemap *pTilemap = Layers()->GameLayer();\n\tm_Width = pTilemap->m_Width*32/m_Spacing;\n\tm_Height = pTilemap->m_Height*32/m_Spacing;\n\n\t// allocate and clear\n\tm_pCells = (CCell *)mem_alloc(sizeof(CCell)*m_Width*m_Height, 1);\n\tfor(int y = 0; y < m_Height; y++)\n\t\tfor(int x = 0; x < m_Width; x++)\n\t\t\tm_pCells[y*m_Width+x].m_Vel = vec2(0.0f, 0.0f);\n}\n\nvoid CFlow::Update()\n{\n\tif(!m_pCells)\n\t\treturn;\n\n\tfor(int y = 0; y < m_Height; y++)\n\t\tfor(int x = 0; x < m_Width; x++)\n\t\t\tm_pCells[y*m_Width+x].m_Vel *= 0.85f;\n}\n\nvec2 CFlow::Get(vec2 Pos)\n{\n\tif(!m_pCells)\n\t\treturn vec2(0,0);\n\n\tint x = (int)(Pos.x / m_Spacing);\n\tint y = (int)(Pos.y / m_Spacing);\n\tif(x < 0 || y < 0 || x >= m_Width || y >= m_Height)\n\t\treturn vec2(0,0);\n\n\treturn m_pCells[y*m_Width+x].m_Vel;\n}\n\nvoid CFlow::Add(vec2 Pos, vec2 Vel, float Size)\n{\n\tif(!m_pCells)\n\t\treturn;\n\n\tint x = (int)(Pos.x / m_Spacing);\n\tint y = (int)(Pos.y / m_Spacing);\n\tif(x < 0 || y < 0 || x >= m_Width || y >= m_Height)\n\t\treturn;\n\n\tm_pCells[y*m_Width+x].m_Vel += Vel;\n}\n"
  },
  {
    "path": "src/game/client/components/flow.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_FLOW_H\n#define GAME_CLIENT_COMPONENTS_FLOW_H\n#include <base/vmath.h>\n#include <game/client/component.h>\n\nclass CFlow : public CComponent\n{\n\tstruct CCell\n\t{\n\t\tvec2 m_Vel;\n\t};\n\n\tCCell *m_pCells;\n\tint m_Height;\n\tint m_Width;\n\tint m_Spacing;\n\n\tvoid DbgRender();\n\tvoid Init();\npublic:\n\tCFlow();\n\n\tvec2 Get(vec2 Pos);\n\tvoid Add(vec2 Pos, vec2 Vel, float Size);\n\tvoid Update();\n};\n\n#endif\n"
  },
  {
    "path": "src/game/client/components/hud.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/graphics.h>\n#include <engine/textrender.h>\n#include <engine/shared/config.h>\n\n#include <game/generated/protocol.h>\n#include <game/generated/client_data.h>\n#include <game/layers.h>\n#include <game/client/gameclient.h>\n#include <game/client/animstate.h>\n#include <game/client/render.h>\n\n#include \"menus.h\"\n#include \"controls.h\"\n#include \"camera.h\"\n#include \"hud.h\"\n#include \"voting.h\"\n#include \"binds.h\"\n\nCHud::CHud()\n{\n\t// won't work if zero\n\tm_AverageFPS = 1.0f;\n}\n\nvoid CHud::OnReset()\n{\n}\n\nvoid CHud::RenderGameTimer()\n{\n\tfloat Half = 300.0f*Graphics()->ScreenAspect()/2.0f;\n\n\tif(!(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_SUDDENDEATH))\n\t{\n\t\tchar Buf[32];\n\t\tint Time = 0;\n\t\tif(m_pClient->m_GameInfo.m_TimeLimit && !(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_WARMUP))\n\t\t{\n\t\t\tTime = m_pClient->m_GameInfo.m_TimeLimit*60 - ((Client()->GameTick()-m_pClient->m_Snap.m_pGameData->m_GameStartTick)/Client()->GameTickSpeed());\n\n\t\t\tif(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_ROUNDOVER|GAMESTATEFLAG_GAMEOVER))\n\t\t\t\tTime = 0;\n\t\t}\n\t\telse if(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_ROUNDOVER|GAMESTATEFLAG_GAMEOVER))\n\t\t\tTime = m_pClient->m_Snap.m_pGameData->m_GameStateEndTick/Client()->GameTickSpeed();\n\t\telse\n\t\t\tTime = (Client()->GameTick()-m_pClient->m_Snap.m_pGameData->m_GameStartTick)/Client()->GameTickSpeed();\n\n\t\tstr_format(Buf, sizeof(Buf), \"%d:%02d\", Time/60, Time%60);\n\t\tfloat FontSize = 10.0f;\n\t\tfloat w = TextRender()->TextWidth(0, FontSize, Buf, -1);\n\t\t// last 60 sec red, last 10 sec blink\n\t\tif(m_pClient->m_GameInfo.m_TimeLimit && Time <= 60 && !(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_WARMUP))\n\t\t{\n\t\t\tfloat Alpha = Time <= 10 && (2*time_get()/time_freq()) % 2 ? 0.5f : 1.0f;\n\t\t\tTextRender()->TextColor(1.0f, 0.25f, 0.25f, Alpha);\n\t\t}\n\t\tTextRender()->Text(0, Half-w/2, 2, FontSize, Buf, -1);\n\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t}\n}\n\nvoid CHud::RenderPauseTimer()\n{\n\tif((m_pClient->m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_STARTCOUNTDOWN|GAMESTATEFLAG_PAUSED)) == GAMESTATEFLAG_PAUSED)\n\t{\n\t\tchar aBuf[256];\n\t\tconst char *pText = Localize(\"Game paused\");\n\t\tfloat FontSize = 20.0f;\n\t\tfloat w = TextRender()->TextWidth(0, FontSize, pText, -1);\n\t\tTextRender()->Text(0, 150*Graphics()->ScreenAspect()+-w/2, 50, FontSize, pText, -1);\n\n\t\tFontSize = 16.0f;\n\t\tif(m_pClient->m_Snap.m_pGameData->m_GameStateEndTick == 0)\n\t\t{\n\t\t\tif(m_pClient->m_Snap.m_NotReadyCount == 1)\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"%d player not ready\"), m_pClient->m_Snap.m_NotReadyCount);\n\t\t\telse if(m_pClient->m_Snap.m_NotReadyCount > 1)\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"%d players not ready\"), m_pClient->m_Snap.m_NotReadyCount);\n\t\t\telse\n\t\t\t\treturn;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfloat Seconds = static_cast<float>(m_pClient->m_Snap.m_pGameData->m_GameStateEndTick-Client()->GameTick())/SERVER_TICK_SPEED;\n\t\t\tif(Seconds < 5)\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"%.1f\", Seconds);\n\t\t\telse\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"%d\", round(Seconds));\n\t\t}\n\t\tw = TextRender()->TextWidth(0, FontSize, aBuf, -1);\n\t\tTextRender()->Text(0, 150*Graphics()->ScreenAspect()+-w/2, 75, FontSize, aBuf, -1);\n\t}\n}\n\nvoid CHud::RenderStartCountdown()\n{\n\tif(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_STARTCOUNTDOWN)\n\t{\n\t\tconst char *pText = Localize(\"Game starts in\");\n\t\tfloat FontSize = 20.0f;\n\t\tfloat w = TextRender()->TextWidth(0, FontSize, pText, -1);\n\t\tTextRender()->Text(0, 150*Graphics()->ScreenAspect()+-w/2, 50, FontSize, pText, -1);\n\n\t\tif(m_pClient->m_Snap.m_pGameData->m_GameStateEndTick == 0)\n\t\t\treturn;\n\t\t\n\t\tFontSize = 16.0f;\n\t\tchar aBuf[32];\n\t\tint Seconds = (m_pClient->m_Snap.m_pGameData->m_GameStateEndTick-Client()->GameTick()+SERVER_TICK_SPEED-1)/SERVER_TICK_SPEED;\n\t\tstr_format(aBuf, sizeof(aBuf), \"%d\", Seconds);\n\t\tw = TextRender()->TextWidth(0, FontSize, aBuf, -1);\n\t\tTextRender()->Text(0, 150*Graphics()->ScreenAspect()+-w/2, 75, FontSize, aBuf, -1);\n\t}\n}\n\nvoid CHud::RenderDeadNotification()\n{\n\tif(m_pClient->m_Snap.m_pGameData->m_GameStateFlags == 0 && m_pClient->m_aClients[m_pClient->m_LocalClientID].m_Team != TEAM_SPECTATORS &&\n\t\tm_pClient->m_Snap.m_pLocalInfo && (m_pClient->m_Snap.m_pLocalInfo->m_PlayerFlags&PLAYERFLAG_DEAD))\n\t{\n\t\tconst char *pText = Localize(\"Wait for next round\");\n\t\tfloat FontSize = 16.0f;\n\t\tfloat w = TextRender()->TextWidth(0, FontSize, pText, -1);\n\t\tTextRender()->Text(0, 150*Graphics()->ScreenAspect()+-w/2, 50, FontSize, pText, -1);\n\t}\n}\n\nvoid CHud::RenderSuddenDeath()\n{\n\tif(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_SUDDENDEATH)\n\t{\n\t\tfloat Half = 300.0f*Graphics()->ScreenAspect()/2.0f;\n\t\tconst char *pText = Localize(\"Sudden Death\");\n\t\tfloat FontSize = 12.0f;\n\t\tfloat w = TextRender()->TextWidth(0, FontSize, pText, -1);\n\t\tTextRender()->Text(0, Half-w/2, 2, FontSize, pText, -1);\n\t}\n}\n\nvoid CHud::RenderScoreHud()\n{\n\t// render small score hud\n\tif(!(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_ROUNDOVER|GAMESTATEFLAG_GAMEOVER)))\n\t{\n\t\tint GameFlags = m_pClient->m_GameInfo.m_GameFlags;\n\t\tfloat Whole = 300*Graphics()->ScreenAspect();\n\t\tfloat StartY = 229.0f;\n\n\t\tif(GameFlags&GAMEFLAG_TEAMS && m_pClient->m_Snap.m_pGameDataTeam)\n\t\t{\n\t\t\tchar aScoreTeam[2][32];\n\t\t\tstr_format(aScoreTeam[TEAM_RED], sizeof(aScoreTeam)/2, \"%d\", m_pClient->m_Snap.m_pGameDataTeam->m_TeamscoreRed);\n\t\t\tstr_format(aScoreTeam[TEAM_BLUE], sizeof(aScoreTeam)/2, \"%d\", m_pClient->m_Snap.m_pGameDataTeam->m_TeamscoreBlue);\n\t\t\tfloat aScoreTeamWidth[2] = { TextRender()->TextWidth(0, 14.0f, aScoreTeam[TEAM_RED], -1), TextRender()->TextWidth(0, 14.0f, aScoreTeam[TEAM_BLUE], -1) };\n\t\t\tfloat ScoreWidthMax = max(max(aScoreTeamWidth[TEAM_RED], aScoreTeamWidth[TEAM_BLUE]), TextRender()->TextWidth(0, 14.0f, \"100\", -1));\n\t\t\tfloat Split = 3.0f;\n\t\t\tfloat ImageSize = GameFlags&GAMEFLAG_FLAGS ? 16.0f : Split;\n\n\t\t\tfor(int t = 0; t < NUM_TEAMS; t++)\n\t\t\t{\n\t\t\t\t// draw box\n\t\t\t\tGraphics()->BlendNormal();\n\t\t\t\tGraphics()->TextureClear();\n\t\t\t\tGraphics()->QuadsBegin();\n\t\t\t\tif(t == 0)\n\t\t\t\t\tGraphics()->SetColor(1.0f, 0.0f, 0.0f, 0.25f);\n\t\t\t\telse\n\t\t\t\t\tGraphics()->SetColor(0.0f, 0.0f, 1.0f, 0.25f);\n\t\t\t\tRenderTools()->DrawRoundRectExt(Whole-ScoreWidthMax-ImageSize-2*Split, StartY+t*20, ScoreWidthMax+ImageSize+2*Split, 18.0f, 5.0f, CUI::CORNER_L);\n\t\t\t\tGraphics()->QuadsEnd();\n\n\t\t\t\t// draw score\n\t\t\t\tTextRender()->Text(0, Whole-ScoreWidthMax+(ScoreWidthMax-aScoreTeamWidth[t])/2-Split, StartY+t*20, 14.0f, aScoreTeam[t], -1);\n\n\t\t\t\tif(GameFlags&GAMEFLAG_SURVIVAL)\n\t\t\t\t{\n\t\t\t\t\t// draw number of alive players\n\t\t\t\t\tchar aBuf[32];\n\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), m_pClient->m_Snap.m_AliveCount[t]==1 ? Localize(\"%d player left\") : Localize(\"%d players left\"),\n\t\t\t\t\t\t\t\tm_pClient->m_Snap.m_AliveCount[t]);\n\t\t\t\t\tfloat w = TextRender()->TextWidth(0, 8.0f, aBuf, -1);\n\t\t\t\t\tTextRender()->Text(0, min(Whole-w-1.0f, Whole-ScoreWidthMax-ImageSize-2*Split), StartY+(t+1)*20.0f-3.0f, 8.0f, aBuf, -1);\n\t\t\t\t}\n\t\t\t\tStartY += 8.0f;\n\t\t\t}\n\n\t\t\tif(GameFlags&GAMEFLAG_FLAGS && m_pClient->m_Snap.m_pGameDataFlag)\n\t\t\t{\n\t\t\t\tint FlagCarrier[2] = { m_pClient->m_Snap.m_pGameDataFlag->m_FlagCarrierRed, m_pClient->m_Snap.m_pGameDataFlag->m_FlagCarrierBlue };\n\t\t\t\tint FlagDropTick[2] = { m_pClient->m_Snap.m_pGameDataFlag->m_FlagDropTickRed, m_pClient->m_Snap.m_pGameDataFlag->m_FlagDropTickBlue };\n\t\t\t\tStartY = 229.0f;\n\n\t\t\t\tfor(int t = 0; t < 2; t++)\n\t\t\t\t{\n\t\t\t\t\tint BlinkTimer = (FlagDropTick[t] != 0 && (Client()->GameTick()-FlagDropTick[t])/Client()->GameTickSpeed() >= 25) ? 10 : 20;\n\t\t\t\t\tif(FlagCarrier[t] == FLAG_ATSTAND || (FlagCarrier[t] == FLAG_TAKEN && ((Client()->GameTick()/BlinkTimer)&1)))\n\t\t\t\t\t{\n\t\t\t\t\t\t// draw flag\n\t\t\t\t\t\tGraphics()->BlendNormal();\n\t\t\t\t\t\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);\n\t\t\t\t\t\tGraphics()->QuadsBegin();\n\t\t\t\t\t\tRenderTools()->SelectSprite(t==0?SPRITE_FLAG_RED:SPRITE_FLAG_BLUE);\n\t\t\t\t\t\tIGraphics::CQuadItem QuadItem(Whole-ScoreWidthMax-ImageSize, StartY+1.0f+t*20, ImageSize/2, ImageSize);\n\t\t\t\t\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t\t\t\t\t\tGraphics()->QuadsEnd();\n\t\t\t\t\t}\n\t\t\t\t\telse if(FlagCarrier[t] >= 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t// draw name of the flag holder\n\t\t\t\t\t\tint ID = FlagCarrier[t]%MAX_CLIENTS;\n\t\t\t\t\t\tconst char *pName = m_pClient->m_aClients[ID].m_aName;\n\t\t\t\t\t\tfloat w = TextRender()->TextWidth(0, 8.0f, pName, -1);\n\t\t\t\t\t\tTextRender()->Text(0, min(Whole-w-1.0f, Whole-ScoreWidthMax-ImageSize-2*Split), StartY+(t+1)*20.0f-3.0f, 8.0f, pName, -1);\n\n\t\t\t\t\t\t// draw tee of the flag holder\n\t\t\t\t\t\tCTeeRenderInfo Info = m_pClient->m_aClients[ID].m_RenderInfo;\n\t\t\t\t\t\tInfo.m_Size = 18.0f;\n\t\t\t\t\t\tRenderTools()->RenderTee(CAnimState::GetIdle(), &Info, EMOTE_NORMAL, vec2(1,0),\n\t\t\t\t\t\t\tvec2(Whole-ScoreWidthMax-Info.m_Size/2-Split, StartY+1.0f+Info.m_Size/2+t*20));\n\t\t\t\t\t}\n\t\t\t\t\tStartY += 8.0f;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tint Local = -1;\n\t\t\tint aPos[2] = { 1, 2 };\n\t\t\tCGameClient::CPlayerInfoItem aPlayerInfo[2] = {{0}};\n\t\t\tint i = 0;\n\t\t\tfor(int t = 0; t < 2 && i < MAX_CLIENTS && m_pClient->m_Snap.m_aInfoByScore[i].m_pPlayerInfo; ++i)\n\t\t\t{\n\t\t\t\tif(m_pClient->m_aClients[m_pClient->m_Snap.m_aInfoByScore[i].m_ClientID].m_Team != TEAM_SPECTATORS)\n\t\t\t\t{\n\t\t\t\t\taPlayerInfo[t] = m_pClient->m_Snap.m_aInfoByScore[i];\n\t\t\t\t\tif(aPlayerInfo[t].m_ClientID == m_pClient->m_LocalClientID)\n\t\t\t\t\t\tLocal = t;\n\t\t\t\t\t++t;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// search local player info if not a spectator, nor within top2 scores\n\t\t\tif(Local == -1 && m_pClient->m_aClients[m_pClient->m_LocalClientID].m_Team != TEAM_SPECTATORS)\n\t\t\t{\n\t\t\t\tfor(; i < MAX_CLIENTS && m_pClient->m_Snap.m_aInfoByScore[i].m_pPlayerInfo; ++i)\n\t\t\t\t{\n\t\t\t\t\tif(m_pClient->m_aClients[m_pClient->m_Snap.m_aInfoByScore[i].m_ClientID].m_Team != TEAM_SPECTATORS)\n\t\t\t\t\t\t++aPos[1];\n\t\t\t\t\tif(m_pClient->m_Snap.m_aInfoByScore[i].m_ClientID == m_pClient->m_LocalClientID)\n\t\t\t\t\t{\n\t\t\t\t\t\taPlayerInfo[1] = m_pClient->m_Snap.m_aInfoByScore[i];\n\t\t\t\t\t\tLocal = 1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tchar aScore[2][32];\n\t\t\tfor(int t = 0; t < 2; ++t)\n\t\t\t{\n\t\t\t\tif(aPlayerInfo[t].m_pPlayerInfo)\n\t\t\t\t\tstr_format(aScore[t], sizeof(aScore)/2, \"%d\", aPlayerInfo[t].m_pPlayerInfo->m_Score);\n\t\t\t\telse\n\t\t\t\t\taScore[t][0] = 0;\n\t\t\t}\n\t\t\tfloat aScoreWidth[2] = {TextRender()->TextWidth(0, 14.0f, aScore[0], -1), TextRender()->TextWidth(0, 14.0f, aScore[1], -1)};\n\t\t\tfloat ScoreWidthMax = max(max(aScoreWidth[0], aScoreWidth[1]), TextRender()->TextWidth(0, 14.0f, \"10\", -1));\n\t\t\tfloat Split = 3.0f, ImageSize = 16.0f, PosSize = 16.0f;\n\n\t\t\t// todo: add core hud for LMS\n\n\t\t\tfor(int t = 0; t < 2; t++)\n\t\t\t{\n\t\t\t\t// draw box\n\t\t\t\tGraphics()->BlendNormal();\n\t\t\t\tGraphics()->TextureClear();\n\t\t\t\tGraphics()->QuadsBegin();\n\t\t\t\tif(t == Local)\n\t\t\t\t\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 0.25f);\n\t\t\t\telse\n\t\t\t\t\tGraphics()->SetColor(0.0f, 0.0f, 0.0f, 0.25f);\n\t\t\t\tRenderTools()->DrawRoundRectExt(Whole-ScoreWidthMax-ImageSize-2*Split-PosSize, StartY+t*20, ScoreWidthMax+ImageSize+2*Split+PosSize, 18.0f, 5.0f, CUI::CORNER_L);\n\t\t\t\tGraphics()->QuadsEnd();\n\n\t\t\t\t// draw score\n\t\t\t\tTextRender()->Text(0, Whole-ScoreWidthMax+(ScoreWidthMax-aScoreWidth[t])/2-Split, StartY+t*20, 14.0f, aScore[t], -1);\n\n\t\t\t\tif(aPlayerInfo[t].m_pPlayerInfo)\n \t\t\t\t{\n\t\t\t\t\t// draw name\n\t\t\t\t\tint ID = aPlayerInfo[t].m_ClientID;\n\t\t\t\t\tconst char *pName = m_pClient->m_aClients[ID].m_aName;\n\t\t\t\t\tfloat w = TextRender()->TextWidth(0, 8.0f, pName, -1);\n\t\t\t\t\tTextRender()->Text(0, min(Whole-w-1.0f, Whole-ScoreWidthMax-ImageSize-2*Split-PosSize), StartY+(t+1)*20.0f-3.0f, 8.0f, pName, -1);\n\n\t\t\t\t\t// draw tee\n\t\t\t\t\tCTeeRenderInfo Info = m_pClient->m_aClients[ID].m_RenderInfo;\n \t\t\t\t\tInfo.m_Size = 18.0f;\n \t\t\t\t\tRenderTools()->RenderTee(CAnimState::GetIdle(), &Info, EMOTE_NORMAL, vec2(1,0),\n \t\t\t\t\t\tvec2(Whole-ScoreWidthMax-Info.m_Size/2-Split, StartY+1.0f+Info.m_Size/2+t*20));\n\t\t\t\t}\n\n\t\t\t\t// draw position\n\t\t\t\tchar aBuf[32];\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"%d.\", aPos[t]);\n\t\t\t\tTextRender()->Text(0, Whole-ScoreWidthMax-ImageSize-Split-PosSize, StartY+2.0f+t*20, 10.0f, aBuf, -1);\n\n\t\t\t\tStartY += 8.0f;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid CHud::RenderWarmupTimer()\n{\n\t// render warmup timer\n\tif(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_WARMUP)\n\t{\n\t\tchar aBuf[256];\n\t\tfloat FontSize = 20.0f;\n\t\tfloat w = TextRender()->TextWidth(0, FontSize, Localize(\"Warmup\"), -1);\n\t\tTextRender()->Text(0, 150*Graphics()->ScreenAspect()+-w/2, 50, FontSize, Localize(\"Warmup\"), -1);\n\n\t\tFontSize = 16.0f;\n\t\tif(m_pClient->m_Snap.m_pGameData->m_GameStateEndTick == 0)\n\t\t{\n\t\t\tif(m_pClient->m_Snap.m_NotReadyCount == 1)\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"%d player not ready\"), m_pClient->m_Snap.m_NotReadyCount);\n\t\t\telse if(m_pClient->m_Snap.m_NotReadyCount > 1)\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"%d players not ready\"), m_pClient->m_Snap.m_NotReadyCount);\n\t\t\telse\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"wait for more players\"));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfloat Seconds = static_cast<float>(m_pClient->m_Snap.m_pGameData->m_GameStateEndTick-Client()->GameTick())/SERVER_TICK_SPEED;\n\t\t\tif(Seconds < 5)\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"%.1f\", Seconds);\n\t\t\telse\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"%d\", round(Seconds));\n\t\t}\n\t\tw = TextRender()->TextWidth(0, FontSize, aBuf, -1);\n\t\tTextRender()->Text(0, 150*Graphics()->ScreenAspect()+-w/2, 75, FontSize, aBuf, -1);\n\t}\n}\n\nvoid CHud::MapscreenToGroup(float CenterX, float CenterY, CMapItemGroup *pGroup)\n{\n\tfloat Points[4];\n\tRenderTools()->MapscreenToWorld(CenterX, CenterY, pGroup->m_ParallaxX/100.0f, pGroup->m_ParallaxY/100.0f,\n\t\tpGroup->m_OffsetX, pGroup->m_OffsetY, Graphics()->ScreenAspect(), m_pClient->m_pCamera->m_Zoom, Points);\n\tGraphics()->MapScreen(Points[0], Points[1], Points[2], Points[3]);\n}\n\nvoid CHud::RenderFps()\n{\n\tif(g_Config.m_ClShowfps)\n\t{\n\t\t// calculate avg. fps\n\t\tfloat FPS = 1.0f / Client()->RenderFrameTime();\n\t\tm_AverageFPS = (m_AverageFPS*(1.0f-(1.0f/m_AverageFPS))) + (FPS*(1.0f/m_AverageFPS));\n\t\tchar Buf[512];\n\t\tstr_format(Buf, sizeof(Buf), \"%d\", (int)m_AverageFPS);\n\t\tTextRender()->Text(0, m_Width-10-TextRender()->TextWidth(0,12,Buf,-1), 5, 12, Buf, -1);\n\t}\n}\n\nvoid CHud::RenderConnectionWarning()\n{\n\tif(Client()->ConnectionProblems())\n\t{\n\t\tconst char *pText = Localize(\"Connection Problems...\");\n\t\tfloat w = TextRender()->TextWidth(0, 24, pText, -1);\n\t\tTextRender()->Text(0, 150*Graphics()->ScreenAspect()-w/2, 50, 24, pText, -1);\n\t}\n}\n\nvoid CHud::RenderTeambalanceWarning()\n{\n\t// render prompt about team-balance\n\tif(m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS && g_Config.m_ClWarningTeambalance && m_pClient->m_ServerSettings.m_TeamBalance &&\n\t\tabsolute(m_pClient->m_GameInfo.m_aTeamSize[TEAM_RED]-m_pClient->m_GameInfo.m_aTeamSize[TEAM_BLUE]) >= NUM_TEAMS)\n\t{\n\t\tbool Flash = time_get()/(time_freq()/2)%2 == 0;\n\t\tconst char *pText = Localize(\"Please balance teams!\");\n\t\tif(Flash)\n\t\t\tTextRender()->TextColor(1,1,0.5f,1);\n\t\telse\n\t\t\tTextRender()->TextColor(0.7f,0.7f,0.2f,1.0f);\n\t\tTextRender()->Text(0x0, 5, 50, 6, pText, -1);\n\t\tTextRender()->TextColor(1,1,1,1);\n\t}\n}\n\n\nvoid CHud::RenderVoting()\n{\n\tif(!m_pClient->m_pVoting->IsVoting() || Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t\treturn;\n\n\tGraphics()->TextureClear();\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(0,0,0,0.40f);\n\tRenderTools()->DrawRoundRect(-10, 60-2, 100+10+4+5, 46, 5.0f);\n\tGraphics()->QuadsEnd();\n\n\tTextRender()->TextColor(1,1,1,1);\n\n\tCTextCursor Cursor;\n\tchar aBuf[512];\n\tstr_format(aBuf, sizeof(aBuf), Localize(\"%ds left\"), m_pClient->m_pVoting->SecondsLeft());\n\tfloat tw = TextRender()->TextWidth(0x0, 6, aBuf, -1);\n\tTextRender()->SetCursor(&Cursor, 5.0f+100.0f-tw, 60.0f, 6.0f, TEXTFLAG_RENDER);\n\tTextRender()->TextEx(&Cursor, aBuf, -1);\n\n\tTextRender()->SetCursor(&Cursor, 5.0f, 60.0f, 6.0f, TEXTFLAG_RENDER);\n\tCursor.m_LineWidth = 100.0f-tw;\n\tCursor.m_MaxLines = 3;\n\tTextRender()->TextEx(&Cursor, m_pClient->m_pVoting->VoteDescription(), -1);\n\n\t// reason\n\tstr_format(aBuf, sizeof(aBuf), \"%s %s\", Localize(\"Reason:\"), m_pClient->m_pVoting->VoteReason());\n\tTextRender()->SetCursor(&Cursor, 5.0f, 79.0f, 6.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\tCursor.m_LineWidth = 100.0f;\n\tTextRender()->TextEx(&Cursor, aBuf, -1);\n\n\tCUIRect Base = {5, 88, 100, 4};\n\tm_pClient->m_pVoting->RenderBars(Base, false);\n\n\tconst char *pYesKey = m_pClient->m_pBinds->GetKey(\"vote yes\");\n\tconst char *pNoKey = m_pClient->m_pBinds->GetKey(\"vote no\");\n\tstr_format(aBuf, sizeof(aBuf), \"%s - %s\", pYesKey, Localize(\"Vote yes\"));\n\tBase.y += Base.h+1;\n\tUI()->DoLabel(&Base, aBuf, 6.0f, -1);\n\n\tstr_format(aBuf, sizeof(aBuf), \"%s - %s\", Localize(\"Vote no\"), pNoKey);\n\tUI()->DoLabel(&Base, aBuf, 6.0f, 1);\n}\n\nvoid CHud::RenderCursor()\n{\n\tif(!m_pClient->m_Snap.m_pLocalCharacter || Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t\treturn;\n\n\tMapscreenToGroup(m_pClient->m_pCamera->m_Center.x, m_pClient->m_pCamera->m_Center.y, Layers()->GameGroup());\n\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);\n\tGraphics()->QuadsBegin();\n\n\t// render cursor\n\tRenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[m_pClient->m_Snap.m_pLocalCharacter->m_Weapon%NUM_WEAPONS].m_pSpriteCursor);\n\tfloat CursorSize = 64;\n\tRenderTools()->DrawSprite(m_pClient->m_pControls->m_TargetPos.x, m_pClient->m_pControls->m_TargetPos.y, CursorSize);\n\tGraphics()->QuadsEnd();\n}\n\nvoid CHud::RenderHealthAndAmmo(const CNetObj_Character *pCharacter)\n{\n\tif(!pCharacter)\n\t\treturn;\n\n\tfloat x = 5;\n\tfloat y = 5;\n\tint i;\n\tIGraphics::CQuadItem Array[10];\n\n\t// render ammo\n\tif(pCharacter->m_Weapon == WEAPON_NINJA)\n\t{\n\t\tGraphics()->TextureClear();\n\t\tGraphics()->QuadsBegin();\n\t\tGraphics()->SetColor(0.8f, 0.8f, 0.8f, 0.5f);\n\t\tRenderTools()->DrawRoundRectExt(x,y+24, 118.0f, 10.0f, 0.0f, 0);\n\n\t\tint Max = g_pData->m_Weapons.m_Ninja.m_Duration * Client()->GameTickSpeed() / 1000;\n\t\tfloat Width = 116.0f * clamp(pCharacter->m_AmmoCount-Client()->GameTick(), 0, Max) / Max;\n\t\tGraphics()->SetColor(0.9f, 0.2f, 0.2f, 0.85f);\n\t\tRenderTools()->DrawRoundRectExt(x+1.0f, y+25.0f, Width, 8.0f, 0.0f, 0);\n\t\tGraphics()->QuadsEnd();\n\n\t\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);\n\t\tGraphics()->QuadsBegin();\n\t\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\tRenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[WEAPON_NINJA].m_pSpriteBody);\n\t\tRenderTools()->DrawRoundRectExt(x+40.0f,y+25, 32.0f, 8.0f, 0.0f, 0);\n\t}\n\telse\n\t{\n\t\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);\n\t\tGraphics()->QuadsBegin();\n\t\tRenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[pCharacter->m_Weapon%NUM_WEAPONS].m_pSpriteProj);\n\t\tfor(i = 0; i < min(pCharacter->m_AmmoCount, 10); i++)\n\t\t\tArray[i] = IGraphics::CQuadItem(x+i*12,y+24,10,10);\n\t\tGraphics()->QuadsDrawTL(Array, i);\n\t}\n\n\tint h = 0;\n\n\t// render health\n\tRenderTools()->SelectSprite(SPRITE_HEALTH_FULL);\n\tfor(; h < min(pCharacter->m_Health, 10); h++)\n\t\tArray[h] = IGraphics::CQuadItem(x+h*12,y,10,10);\n\tGraphics()->QuadsDrawTL(Array, h);\n\n\ti = 0;\n\tRenderTools()->SelectSprite(SPRITE_HEALTH_EMPTY);\n\tfor(; h < 10; h++)\n\t\tArray[i++] = IGraphics::CQuadItem(x+h*12,y,10,10);\n\tGraphics()->QuadsDrawTL(Array, i);\n\n\t// render armor meter\n\th = 0;\n\tRenderTools()->SelectSprite(SPRITE_ARMOR_FULL);\n\tfor(; h < min(pCharacter->m_Armor, 10); h++)\n\t\tArray[h] = IGraphics::CQuadItem(x+h*12,y+12,10,10);\n\tGraphics()->QuadsDrawTL(Array, h);\n\n\ti = 0;\n\tRenderTools()->SelectSprite(SPRITE_ARMOR_EMPTY);\n\tfor(; h < 10; h++)\n\t\tArray[i++] = IGraphics::CQuadItem(x+h*12,y+12,10,10);\n\tGraphics()->QuadsDrawTL(Array, i);\n\tGraphics()->QuadsEnd();\n}\n\nvoid CHud::RenderSpectatorHud()\n{\n\t// draw the box\n\tGraphics()->TextureClear();\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(0.0f, 0.0f, 0.0f, 0.4f);\n\tRenderTools()->DrawRoundRectExt(m_Width-180.0f, m_Height-15.0f, 180.0f, 15.0f, 5.0f, CUI::CORNER_TL);\n\tGraphics()->QuadsEnd();\n\n\t// draw the text\n\tchar aBuf[128];\n\tstr_format(aBuf, sizeof(aBuf), \"%s: %s\", Localize(\"Spectate\"), m_pClient->m_Snap.m_SpecInfo.m_SpectatorID != SPEC_FREEVIEW ?\n\t\tm_pClient->m_aClients[m_pClient->m_Snap.m_SpecInfo.m_SpectatorID].m_aName : Localize(\"Free-View\"));\n\tTextRender()->Text(0, m_Width-174.0f, m_Height-13.0f, 8.0f, aBuf, -1);\n}\n\nvoid CHud::OnRender()\n{\n\tif(!m_pClient->m_Snap.m_pGameData)\n\t\treturn;\n\n\t// dont render hud if the menu is active\n\tif(m_pClient->m_pMenus->IsActive())\n\t\treturn;\n\n\tm_Width = 300.0f*Graphics()->ScreenAspect();\n\tm_Height = 300.0f;\n\tGraphics()->MapScreen(0.0f, 0.0f, m_Width, m_Height);\n\n\tif(g_Config.m_ClShowhud)\n\t{\n\t\tif(m_pClient->m_Snap.m_pLocalCharacter && !(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_ROUNDOVER|GAMESTATEFLAG_GAMEOVER)))\n\t\t\tRenderHealthAndAmmo(m_pClient->m_Snap.m_pLocalCharacter);\n\t\telse if(m_pClient->m_Snap.m_SpecInfo.m_Active)\n\t\t{\n\t\t\tif(m_pClient->m_Snap.m_SpecInfo.m_SpectatorID != SPEC_FREEVIEW)\n\t\t\t\tRenderHealthAndAmmo(&m_pClient->m_Snap.m_aCharacters[m_pClient->m_Snap.m_SpecInfo.m_SpectatorID].m_Cur);\n\t\t\tRenderSpectatorHud();\n\t\t}\n\n\t\tRenderGameTimer();\n\t\tRenderPauseTimer();\n\t\tRenderStartCountdown();\n\t\tRenderDeadNotification();\n\t\tRenderSuddenDeath();\n\t\tRenderScoreHud();\n\t\tRenderWarmupTimer();\n\t\tRenderFps();\n\t\tif(Client()->State() != IClient::STATE_DEMOPLAYBACK)\n\t\t\tRenderConnectionWarning();\n\t\tRenderTeambalanceWarning();\n\t\tRenderVoting();\n\t}\n\tRenderCursor();\n}\n"
  },
  {
    "path": "src/game/client/components/hud.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_HUD_H\n#define GAME_CLIENT_COMPONENTS_HUD_H\n#include <game/client/component.h>\n\nclass CHud : public CComponent\n{\n\tfloat m_Width, m_Height;\n\tfloat m_AverageFPS;\n\n\tvoid RenderCursor();\n\n\tvoid RenderFps();\n\tvoid RenderConnectionWarning();\n\tvoid RenderTeambalanceWarning();\n\tvoid RenderVoting();\n\tvoid RenderHealthAndAmmo(const CNetObj_Character *pCharacter);\n\tvoid RenderGameTimer();\n\tvoid RenderPauseTimer();\n\tvoid RenderStartCountdown();\n\tvoid RenderDeadNotification();\n\tvoid RenderSuddenDeath();\n\tvoid RenderScoreHud();\n\tvoid RenderSpectatorHud();\n\tvoid RenderWarmupTimer();\n\n\tvoid MapscreenToGroup(float CenterX, float CenterY, struct CMapItemGroup *PGroup);\npublic:\n\tCHud();\n\n\tvirtual void OnReset();\n\tvirtual void OnRender();\n};\n\n#endif\n"
  },
  {
    "path": "src/game/client/components/items.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/graphics.h>\n#include <engine/demo.h>\n#include <game/generated/protocol.h>\n#include <game/generated/client_data.h>\n\n#include <game/gamecore.h> // get_angle\n#include <game/client/gameclient.h>\n#include <game/client/ui.h>\n#include <game/client/render.h>\n\n#include <game/client/components/flow.h>\n#include <game/client/components/effects.h>\n\n#include \"items.h\"\n\nvoid CItems::OnReset()\n{\n\tm_NumExtraProjectiles = 0;\n}\n\nvoid CItems::RenderProjectile(const CNetObj_Projectile *pCurrent, int ItemID)\n{\n\t// get positions\n\tfloat Curvature = 0;\n\tfloat Speed = 0;\n\tif(pCurrent->m_Type == WEAPON_GRENADE)\n\t{\n\t\tCurvature = m_pClient->m_Tuning.m_GrenadeCurvature;\n\t\tSpeed = m_pClient->m_Tuning.m_GrenadeSpeed;\n\t}\n\telse if(pCurrent->m_Type == WEAPON_SHOTGUN)\n\t{\n\t\tCurvature = m_pClient->m_Tuning.m_ShotgunCurvature;\n\t\tSpeed = m_pClient->m_Tuning.m_ShotgunSpeed;\n\t}\n\telse if(pCurrent->m_Type == WEAPON_GUN)\n\t{\n\t\tCurvature = m_pClient->m_Tuning.m_GunCurvature;\n\t\tSpeed = m_pClient->m_Tuning.m_GunSpeed;\n\t}\n\n\tstatic float s_LastGameTickTime = Client()->GameTickTime();\n\tif(m_pClient->m_Snap.m_pGameData && !(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED))\n\t\ts_LastGameTickTime = Client()->GameTickTime();\n\tfloat Ct = (Client()->PrevGameTick()-pCurrent->m_StartTick)/(float)SERVER_TICK_SPEED + s_LastGameTickTime;\n\tif(Ct < 0)\n\t\treturn; // projectile havn't been shot yet\n\n\tvec2 StartPos(pCurrent->m_X, pCurrent->m_Y);\n\tvec2 StartVel(pCurrent->m_VelX/100.0f, pCurrent->m_VelY/100.0f);\n\tvec2 Pos = CalcPos(StartPos, StartVel, Curvature, Speed, Ct);\n\tvec2 PrevPos = CalcPos(StartPos, StartVel, Curvature, Speed, Ct-0.001f);\n\n\n\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);\n\tGraphics()->QuadsBegin();\n\n\tRenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[clamp(pCurrent->m_Type, 0, NUM_WEAPONS-1)].m_pSpriteProj);\n\tvec2 Vel = Pos-PrevPos;\n\t//vec2 pos = mix(vec2(prev->x, prev->y), vec2(current->x, current->y), Client()->IntraGameTick());\n\n\n\t// add particle for this projectile\n\tif(pCurrent->m_Type == WEAPON_GRENADE)\n\t{\n\t\tm_pClient->m_pEffects->SmokeTrail(Pos, Vel*-1);\n\t\tstatic float s_Time = 0.0f;\n\t\tstatic float s_LastLocalTime = Client()->LocalTime();\n\n\t\tif(Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t\t{\n\t\t\tconst IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo();\n\t\t\tif(!pInfo->m_Paused)\n\t\t\t\ts_Time += (Client()->LocalTime()-s_LastLocalTime)*pInfo->m_Speed;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(m_pClient->m_Snap.m_pGameData && !(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED))\n\t\t\t\ts_Time += Client()->LocalTime()-s_LastLocalTime;\n\t\t}\n\n\t\tGraphics()->QuadsSetRotation(s_Time*pi*2*2 + ItemID);\n\t\ts_LastLocalTime = Client()->LocalTime();\n\t}\n\telse\n\t{\n\t\tm_pClient->m_pEffects->BulletTrail(Pos);\n\n\t\tif(length(Vel) > 0.00001f)\n\t\t\tGraphics()->QuadsSetRotation(GetAngle(Vel));\n\t\telse\n\t\t\tGraphics()->QuadsSetRotation(0);\n\n\t}\n\n\tIGraphics::CQuadItem QuadItem(Pos.x, Pos.y, 32, 32);\n\tGraphics()->QuadsDraw(&QuadItem, 1);\n\tGraphics()->QuadsSetRotation(0);\n\tGraphics()->QuadsEnd();\n}\n\nvoid CItems::RenderPickup(const CNetObj_Pickup *pPrev, const CNetObj_Pickup *pCurrent)\n{\n\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);\n\tGraphics()->QuadsBegin();\n\tvec2 Pos = mix(vec2(pPrev->m_X, pPrev->m_Y), vec2(pCurrent->m_X, pCurrent->m_Y), Client()->IntraGameTick());\n\tfloat Angle = 0.0f;\n\tfloat Size = 64.0f;\n\tconst int c[] = {\n\t\tSPRITE_PICKUP_HEALTH,\n\t\tSPRITE_PICKUP_ARMOR,\n\t\tSPRITE_PICKUP_GRENADE,\n\t\tSPRITE_PICKUP_SHOTGUN,\n\t\tSPRITE_PICKUP_LASER,\n\t\tSPRITE_PICKUP_NINJA\n\t\t};\n\tRenderTools()->SelectSprite(c[pCurrent->m_Type]);\n\n\tswitch(pCurrent->m_Type)\n\t{\n\tcase PICKUP_GRENADE:\n\t\tSize = g_pData->m_Weapons.m_aId[WEAPON_GRENADE].m_VisualSize;\n\t\tbreak;\n\tcase PICKUP_SHOTGUN:\n\t\tSize = g_pData->m_Weapons.m_aId[WEAPON_SHOTGUN].m_VisualSize;\n\t\tbreak;\n\tcase PICKUP_LASER:\n\t\tSize = g_pData->m_Weapons.m_aId[WEAPON_LASER].m_VisualSize;\n\t\tbreak;\n\tcase PICKUP_NINJA:\n\t\tm_pClient->m_pEffects->PowerupShine(Pos, vec2(96,18));\n\t\tSize *= 2.0f;\n\t\tPos.x -= 10.0f;\n\t}\n\t\n\n\tGraphics()->QuadsSetRotation(Angle);\n\n\tstatic float s_Time = 0.0f;\n\tstatic float s_LastLocalTime = Client()->LocalTime();\n\tfloat Offset = Pos.y/32.0f + Pos.x/32.0f;\n\tif(Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tconst IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo();\n\t\tif(!pInfo->m_Paused)\n\t\t\ts_Time += (Client()->LocalTime()-s_LastLocalTime)*pInfo->m_Speed;\n\t}\n\telse\n\t{\n\t\tif(m_pClient->m_Snap.m_pGameData && !(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED))\n\t\t\ts_Time += Client()->LocalTime()-s_LastLocalTime;\n \t}\n\tPos.x += cosf(s_Time*2.0f+Offset)*2.5f;\n\tPos.y += sinf(s_Time*2.0f+Offset)*2.5f;\n\ts_LastLocalTime = Client()->LocalTime();\n\tRenderTools()->DrawSprite(Pos.x, Pos.y, Size);\n\tGraphics()->QuadsEnd();\n}\n\nvoid CItems::RenderFlag(const CNetObj_Flag *pPrev, const CNetObj_Flag *pCurrent, const CNetObj_GameDataFlag *pPrevGameDataFlag, const CNetObj_GameDataFlag *pCurGameDataFlag)\n{\n\tfloat Angle = 0.0f;\n\tfloat Size = 42.0f;\n\n\tGraphics()->BlendNormal();\n\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);\n\tGraphics()->QuadsBegin();\n\n\tif(pCurrent->m_Team == TEAM_RED)\n\t\tRenderTools()->SelectSprite(SPRITE_FLAG_RED);\n\telse\n\t\tRenderTools()->SelectSprite(SPRITE_FLAG_BLUE);\n\n\tGraphics()->QuadsSetRotation(Angle);\n\n\tvec2 Pos = mix(vec2(pPrev->m_X, pPrev->m_Y), vec2(pCurrent->m_X, pCurrent->m_Y), Client()->IntraGameTick());\n\n\tif(pCurGameDataFlag)\n\t{\n\t\t// make sure that the flag isn't interpolated between capture and return\n\t\tif(pPrevGameDataFlag &&\n\t\t\t((pCurrent->m_Team == TEAM_RED && pPrevGameDataFlag->m_FlagCarrierRed != pCurGameDataFlag->m_FlagCarrierRed) ||\n\t\t\t(pCurrent->m_Team == TEAM_BLUE && pPrevGameDataFlag->m_FlagCarrierBlue != pCurGameDataFlag->m_FlagCarrierBlue)))\n\t\t\tPos = vec2(pCurrent->m_X, pCurrent->m_Y);\n\n\t\t// make sure to use predicted position if we are the carrier\n\t\tif(m_pClient->m_LocalClientID != -1 &&\n\t\t\t((pCurrent->m_Team == TEAM_RED && pCurGameDataFlag->m_FlagCarrierRed == m_pClient->m_LocalClientID) ||\n\t\t\t(pCurrent->m_Team == TEAM_BLUE && pCurGameDataFlag->m_FlagCarrierBlue == m_pClient->m_LocalClientID)))\n\t\t\tPos = m_pClient->m_LocalCharacterPos;\n\t}\n\n\tIGraphics::CQuadItem QuadItem(Pos.x, Pos.y-Size*0.75f, Size, Size*2);\n\tGraphics()->QuadsDraw(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n}\n\n\nvoid CItems::RenderLaser(const struct CNetObj_Laser *pCurrent)\n{\n\tvec2 Pos = vec2(pCurrent->m_X, pCurrent->m_Y);\n\tvec2 From = vec2(pCurrent->m_FromX, pCurrent->m_FromY);\n\tvec2 Dir = normalize(Pos-From);\n\n\tfloat Ticks = Client()->GameTick() + Client()->IntraGameTick() - pCurrent->m_StartTick;\n\tfloat Ms = (Ticks/50.0f) * 1000.0f;\n\tfloat a = Ms / m_pClient->m_Tuning.m_LaserBounceDelay;\n\ta = clamp(a, 0.0f, 1.0f);\n\tfloat Ia = 1-a;\n\n\tvec2 Out, Border;\n\n\tGraphics()->BlendNormal();\n\tGraphics()->TextureClear();\n\tGraphics()->QuadsBegin();\n\n\t//vec4 inner_color(0.15f,0.35f,0.75f,1.0f);\n\t//vec4 outer_color(0.65f,0.85f,1.0f,1.0f);\n\n\t// do outline\n\tvec4 OuterColor(0.075f, 0.075f, 0.25f, 1.0f);\n\tGraphics()->SetColor(OuterColor.r, OuterColor.g, OuterColor.b, 1.0f);\n\tOut = vec2(Dir.y, -Dir.x) * (7.0f*Ia);\n\n\tIGraphics::CFreeformItem Freeform(\n\t\t\tFrom.x-Out.x, From.y-Out.y,\n\t\t\tFrom.x+Out.x, From.y+Out.y,\n\t\t\tPos.x-Out.x, Pos.y-Out.y,\n\t\t\tPos.x+Out.x, Pos.y+Out.y);\n\tGraphics()->QuadsDrawFreeform(&Freeform, 1);\n\n\t// do inner\n\tvec4 InnerColor(0.5f, 0.5f, 1.0f, 1.0f);\n\tOut = vec2(Dir.y, -Dir.x) * (5.0f*Ia);\n\tGraphics()->SetColor(InnerColor.r, InnerColor.g, InnerColor.b, 1.0f); // center\n\n\tFreeform = IGraphics::CFreeformItem(\n\t\t\tFrom.x-Out.x, From.y-Out.y,\n\t\t\tFrom.x+Out.x, From.y+Out.y,\n\t\t\tPos.x-Out.x, Pos.y-Out.y,\n\t\t\tPos.x+Out.x, Pos.y+Out.y);\n\tGraphics()->QuadsDrawFreeform(&Freeform, 1);\n\n\tGraphics()->QuadsEnd();\n\n\t// render head\n\t{\n\t\tGraphics()->BlendNormal();\n\t\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_PARTICLES].m_Id);\n\t\tGraphics()->QuadsBegin();\n\n\t\tint Sprites[] = {SPRITE_PART_SPLAT01, SPRITE_PART_SPLAT02, SPRITE_PART_SPLAT03};\n\t\tRenderTools()->SelectSprite(Sprites[Client()->GameTick()%3]);\n\t\tGraphics()->QuadsSetRotation(Client()->GameTick());\n\t\tGraphics()->SetColor(OuterColor.r, OuterColor.g, OuterColor.b, 1.0f);\n\t\tIGraphics::CQuadItem QuadItem(Pos.x, Pos.y, 24, 24);\n\t\tGraphics()->QuadsDraw(&QuadItem, 1);\n\t\tGraphics()->SetColor(InnerColor.r, InnerColor.g, InnerColor.b, 1.0f);\n\t\tQuadItem = IGraphics::CQuadItem(Pos.x, Pos.y, 20, 20);\n\t\tGraphics()->QuadsDraw(&QuadItem, 1);\n\t\tGraphics()->QuadsEnd();\n\t}\n\n\tGraphics()->BlendNormal();\n}\n\nvoid CItems::OnRender()\n{\n\tif(Client()->State() < IClient::STATE_ONLINE)\n\t\treturn;\n\n\tint Num = Client()->SnapNumItems(IClient::SNAP_CURRENT);\n\tfor(int i = 0; i < Num; i++)\n\t{\n\t\tIClient::CSnapItem Item;\n\t\tconst void *pData = Client()->SnapGetItem(IClient::SNAP_CURRENT, i, &Item);\n\n\t\tif(Item.m_Type == NETOBJTYPE_PROJECTILE)\n\t\t{\n\t\t\tRenderProjectile((const CNetObj_Projectile *)pData, Item.m_ID);\n\t\t}\n\t\telse if(Item.m_Type == NETOBJTYPE_PICKUP)\n\t\t{\n\t\t\tconst void *pPrev = Client()->SnapFindItem(IClient::SNAP_PREV, Item.m_Type, Item.m_ID);\n\t\t\tif(pPrev)\n\t\t\t\tRenderPickup((const CNetObj_Pickup *)pPrev, (const CNetObj_Pickup *)pData);\n\t\t}\n\t\telse if(Item.m_Type == NETOBJTYPE_LASER)\n\t\t{\n\t\t\tRenderLaser((const CNetObj_Laser *)pData);\n\t\t}\n\t}\n\n\t// render flag\n\tfor(int i = 0; i < Num; i++)\n\t{\n\t\tIClient::CSnapItem Item;\n\t\tconst void *pData = Client()->SnapGetItem(IClient::SNAP_CURRENT, i, &Item);\n\n\t\tif(Item.m_Type == NETOBJTYPE_FLAG)\n\t\t{\n\t\t\tconst void *pPrev = Client()->SnapFindItem(IClient::SNAP_PREV, Item.m_Type, Item.m_ID);\n\t\t\tif (pPrev)\n\t\t\t{\n\t\t\t\tconst void *pPrevGameDataFlag = Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_GAMEDATAFLAG, m_pClient->m_Snap.m_GameDataFlagSnapID);\n\t\t\t\tRenderFlag(static_cast<const CNetObj_Flag *>(pPrev), static_cast<const CNetObj_Flag *>(pData),\n\t\t\t\t\t\t\tstatic_cast<const CNetObj_GameDataFlag *>(pPrevGameDataFlag), m_pClient->m_Snap.m_pGameDataFlag);\n\t\t\t}\n\t\t}\n\t}\n\n\t// render extra projectiles\n\tfor(int i = 0; i < m_NumExtraProjectiles; i++)\n\t{\n\t\tif(m_aExtraProjectiles[i].m_StartTick < Client()->GameTick())\n\t\t{\n\t\t\tm_aExtraProjectiles[i] = m_aExtraProjectiles[m_NumExtraProjectiles-1];\n\t\t\tm_NumExtraProjectiles--;\n\t\t}\n\t\telse\n\t\t\tRenderProjectile(&m_aExtraProjectiles[i], 0);\n\t}\n}\n\nvoid CItems::AddExtraProjectile(CNetObj_Projectile *pProj)\n{\n\tif(m_NumExtraProjectiles != MAX_EXTRA_PROJECTILES)\n\t{\n\t\tm_aExtraProjectiles[m_NumExtraProjectiles] = *pProj;\n\t\tm_NumExtraProjectiles++;\n\t}\n}\n"
  },
  {
    "path": "src/game/client/components/items.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_ITEMS_H\n#define GAME_CLIENT_COMPONENTS_ITEMS_H\n#include <game/client/component.h>\n\nclass CItems : public CComponent\n{\n\tenum\n\t{\n\t\tMAX_EXTRA_PROJECTILES=32,\n\t};\n\n\tCNetObj_Projectile m_aExtraProjectiles[MAX_EXTRA_PROJECTILES];\n\tint m_NumExtraProjectiles;\n\n\tvoid RenderProjectile(const CNetObj_Projectile *pCurrent, int ItemID);\n\tvoid RenderPickup(const CNetObj_Pickup *pPrev, const CNetObj_Pickup *pCurrent);\n\tvoid RenderFlag(const CNetObj_Flag *pPrev, const CNetObj_Flag *pCurrent, const CNetObj_GameDataFlag *pPrevGameDataFlag, const CNetObj_GameDataFlag *pCurGameDataFlag);\n\tvoid RenderLaser(const struct CNetObj_Laser *pCurrent);\n\npublic:\n\tvirtual void OnReset();\n\tvirtual void OnRender();\n\n\tvoid AddExtraProjectile(CNetObj_Projectile *pProj);\n};\n\n#endif\n"
  },
  {
    "path": "src/game/client/components/killmessages.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/graphics.h>\n#include <engine/textrender.h>\n#include <game/generated/protocol.h>\n#include <game/generated/client_data.h>\n\n#include <game/client/gameclient.h>\n#include <game/client/animstate.h>\n#include \"killmessages.h\"\n\nvoid CKillMessages::OnReset()\n{\n\tm_KillmsgCurrent = 0;\n\tfor(int i = 0; i < MAX_KILLMSGS; i++)\n\t\tm_aKillmsgs[i].m_Tick = -100000;\n}\n\nvoid CKillMessages::OnMessage(int MsgType, void *pRawMsg)\n{\n\tif(MsgType == NETMSGTYPE_SV_KILLMSG)\n\t{\n\t\tCNetMsg_Sv_KillMsg *pMsg = (CNetMsg_Sv_KillMsg *)pRawMsg;\n\n\t\t// unpack messages\n\t\tCKillMsg Kill;\n\t\tKill.m_VictimID = pMsg->m_Victim;\n\t\tKill.m_VictimTeam = m_pClient->m_aClients[Kill.m_VictimID].m_Team;\n\t\tstr_copy(Kill.m_aVictimName, m_pClient->m_aClients[Kill.m_VictimID].m_aName, sizeof(Kill.m_aVictimName));\n\t\tKill.m_VictimRenderInfo = m_pClient->m_aClients[Kill.m_VictimID].m_RenderInfo;\n\t\tKill.m_KillerID = pMsg->m_Killer;\n\t\tKill.m_KillerTeam = m_pClient->m_aClients[Kill.m_KillerID].m_Team;\n\t\tstr_copy(Kill.m_aKillerName, m_pClient->m_aClients[Kill.m_KillerID].m_aName, sizeof(Kill.m_aKillerName));\n\t\tKill.m_KillerRenderInfo = m_pClient->m_aClients[Kill.m_KillerID].m_RenderInfo;\n\t\tKill.m_Weapon = pMsg->m_Weapon;\n\t\tKill.m_ModeSpecial = pMsg->m_ModeSpecial;\n\t\tKill.m_Tick = Client()->GameTick();\n\n\t\t// add the message\n\t\tm_KillmsgCurrent = (m_KillmsgCurrent+1)%MAX_KILLMSGS;\n\t\tm_aKillmsgs[m_KillmsgCurrent] = Kill;\n\t}\n}\n\nvoid CKillMessages::OnRender()\n{\n\tfloat Width = 400*3.0f*Graphics()->ScreenAspect();\n\tfloat Height = 400*3.0f;\n\n\tGraphics()->MapScreen(0, 0, Width*1.5f, Height*1.5f);\n\tfloat StartX = Width*1.5f-10.0f;\n\tfloat y = 20.0f;\n\n\tfor(int i = 1; i <= MAX_KILLMSGS; i++)\n\t{\n\t\tint r = (m_KillmsgCurrent+i)%MAX_KILLMSGS;\n\t\tif(Client()->GameTick() > m_aKillmsgs[r].m_Tick+50*10)\n\t\t\tcontinue;\n\n\t\tfloat FontSize = 36.0f;\n\t\tfloat KillerNameW = TextRender()->TextWidth(0, FontSize, m_aKillmsgs[r].m_aKillerName, -1);\n\t\tfloat VictimNameW = TextRender()->TextWidth(0, FontSize, m_aKillmsgs[r].m_aVictimName, -1);\n\n\t\tfloat x = StartX;\n\n\t\t// render victim name\n\t\tx -= VictimNameW;\n\t\tTextRender()->Text(0, x, y, FontSize, m_aKillmsgs[r].m_aVictimName, -1);\n\n\t\t// render victim tee\n\t\tx -= 24.0f;\n\n\t\tif(m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_FLAGS)\n\t\t{\n\t\t\tif(m_aKillmsgs[r].m_ModeSpecial&1)\n\t\t\t{\n\t\t\t\tGraphics()->BlendNormal();\n\t\t\t\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);\n\t\t\t\tGraphics()->QuadsBegin();\n\n\t\t\t\tif(m_aKillmsgs[r].m_VictimTeam == TEAM_RED)\n\t\t\t\t\tRenderTools()->SelectSprite(SPRITE_FLAG_BLUE);\n\t\t\t\telse\n\t\t\t\t\tRenderTools()->SelectSprite(SPRITE_FLAG_RED);\n\n\t\t\t\tfloat Size = 56.0f;\n\t\t\t\tIGraphics::CQuadItem QuadItem(x, y-16, Size/2, Size);\n\t\t\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t\t\t\tGraphics()->QuadsEnd();\n\t\t\t}\n\t\t}\n\n\t\tRenderTools()->RenderTee(CAnimState::GetIdle(), &m_aKillmsgs[r].m_VictimRenderInfo, EMOTE_PAIN, vec2(-1,0), vec2(x, y+28));\n\t\tx -= 32.0f;\n\n\t\t// render weapon\n\t\tx -= 44.0f;\n\t\tif (m_aKillmsgs[r].m_Weapon >= 0)\n\t\t{\n\t\t\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);\n\t\t\tGraphics()->QuadsBegin();\n\t\t\tRenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[m_aKillmsgs[r].m_Weapon].m_pSpriteBody);\n\t\t\tRenderTools()->DrawSprite(x, y+28, 96);\n\t\t\tGraphics()->QuadsEnd();\n\t\t}\n\t\tx -= 52.0f;\n\n\t\tif(m_aKillmsgs[r].m_VictimID != m_aKillmsgs[r].m_KillerID)\n\t\t{\n\t\t\tif(m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_FLAGS)\n\t\t\t{\n\t\t\t\tif(m_aKillmsgs[r].m_ModeSpecial&2)\n\t\t\t\t{\n\t\t\t\t\tGraphics()->BlendNormal();\n\t\t\t\t\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);\n\t\t\t\t\tGraphics()->QuadsBegin();\n\n\t\t\t\t\tif(m_aKillmsgs[r].m_KillerTeam == TEAM_RED)\n\t\t\t\t\t\tRenderTools()->SelectSprite(SPRITE_FLAG_BLUE, SPRITE_FLAG_FLIP_X);\n\t\t\t\t\telse\n\t\t\t\t\t\tRenderTools()->SelectSprite(SPRITE_FLAG_RED, SPRITE_FLAG_FLIP_X);\n\n\t\t\t\t\tfloat Size = 56.0f;\n\t\t\t\t\tIGraphics::CQuadItem QuadItem(x-56, y-16, Size/2, Size);\n\t\t\t\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t\t\t\t\tGraphics()->QuadsEnd();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// render killer tee\n\t\t\tx -= 24.0f;\n\t\t\tRenderTools()->RenderTee(CAnimState::GetIdle(), &m_aKillmsgs[r].m_KillerRenderInfo, EMOTE_ANGRY, vec2(1,0), vec2(x, y+28));\n\t\t\tx -= 32.0f;\n\n\t\t\t// render killer name\n\t\t\tx -= KillerNameW;\n\t\t\tTextRender()->Text(0, x, y, FontSize, m_aKillmsgs[r].m_aKillerName, -1);\n\t\t}\n\n\t\ty += 46.0f;\n\t}\n}\n"
  },
  {
    "path": "src/game/client/components/killmessages.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_KILLMESSAGES_H\n#define GAME_CLIENT_COMPONENTS_KILLMESSAGES_H\n#include <game/client/component.h>\n\nclass CKillMessages : public CComponent\n{\npublic:\n\t// kill messages\n\tstruct CKillMsg\n\t{\n\t\tint m_Weapon;\n\t\tint m_VictimID;\n\t\tint m_VictimTeam;\n\t\tchar m_aVictimName[64];\n\t\tCTeeRenderInfo m_VictimRenderInfo;\n\t\tint m_KillerID;\n\t\tint m_KillerTeam;\n\t\tchar m_aKillerName[64];\n\t\tCTeeRenderInfo m_KillerRenderInfo;\n\t\tint m_ModeSpecial; // for CTF, if the guy is carrying a flag for example\n\t\tint m_Tick;\n\t};\n\n\tenum\n\t{\n\t\tMAX_KILLMSGS = 5,\n\t};\n\n\tCKillMsg m_aKillmsgs[MAX_KILLMSGS];\n\tint m_KillmsgCurrent;\n\n\tvirtual void OnReset();\n\tvirtual void OnRender();\n\tvirtual void OnMessage(int MsgType, void *pRawMsg);\n};\n\n#endif\n"
  },
  {
    "path": "src/game/client/components/mapimages.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/graphics.h>\n#include <engine/map.h>\n#include <engine/storage.h>\n#include <game/client/component.h>\n#include <game/mapitems.h>\n\n#include \"mapimages.h\"\n\nCMapImages::CMapImages()\n{\n\tm_Count = 0;\n\tm_MenuCount = 0;\n}\n\nvoid CMapImages::OnMapLoad()\n{\n\tIMap *pMap = Kernel()->RequestInterface<IMap>();\n\n\t// unload all textures\n\tfor(int i = 0; i < m_Count; i++)\n\t{\n\t\tGraphics()->UnloadTexture(m_aTextures[i]);\n\t\tm_aTextures[i] = IGraphics::CTextureHandle();\n\t}\n\tm_Count = 0;\n\n\tint Start;\n\tpMap->GetType(MAPITEMTYPE_IMAGE, &Start, &m_Count);\n\n\t// load new textures\n\tfor(int i = 0; i < m_Count; i++)\n\t{\n\t\tCMapItemImage *pImg = (CMapItemImage *)pMap->GetItem(Start+i, 0, 0);\n\t\tif(pImg->m_External || (pImg->m_Version > 1 && pImg->m_Format != CImageInfo::FORMAT_RGB && pImg->m_Format != CImageInfo::FORMAT_RGBA))\n\t\t{\n\t\t\tchar Buf[256];\n\t\t\tchar *pName = (char *)pMap->GetData(pImg->m_ImageName);\n\t\t\tstr_format(Buf, sizeof(Buf), \"mapres/%s.png\", pName);\n\t\t\tm_aTextures[i] = Graphics()->LoadTexture(Buf, IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvoid *pData = pMap->GetData(pImg->m_ImageData);\n\t\t\tm_aTextures[i] = Graphics()->LoadTextureRaw(pImg->m_Width, pImg->m_Height, pImg->m_Version == 1 ? CImageInfo::FORMAT_RGBA : pImg->m_Format, pData, CImageInfo::FORMAT_RGBA, 0);\n\t\t\tpMap->UnloadData(pImg->m_ImageData);\n\t\t}\n\t}\n}\n\nvoid CMapImages::OnMenuMapLoad(IMap *pMap)\n{\n\t// unload all textures\n\tfor(int i = 0; i < m_MenuCount; i++)\n\t{\n\t\tGraphics()->UnloadTexture(m_aMenuTextures[i]);\n\t\tm_aMenuTextures[i] = IGraphics::CTextureHandle();\n\t}\n\tm_MenuCount = 0;\n\n\tint Start;\n\tpMap->GetType(MAPITEMTYPE_IMAGE, &Start, &m_MenuCount);\n\n\t// load new textures\n\tfor(int i = 0; i < m_MenuCount; i++)\n\t{\n\t\tCMapItemImage *pImg = (CMapItemImage *)pMap->GetItem(Start+i, 0, 0);\n\t\tif(pImg->m_External || (pImg->m_Version > 1 && pImg->m_Format != CImageInfo::FORMAT_RGB && pImg->m_Format != CImageInfo::FORMAT_RGBA))\n\t\t{\n\t\t\tchar Buf[256];\n\t\t\tchar *pName = (char *)pMap->GetData(pImg->m_ImageName);\n\t\t\tstr_format(Buf, sizeof(Buf), \"mapres/%s.png\", pName);\n\t\t\tm_aMenuTextures[i] = Graphics()->LoadTexture(Buf, IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvoid *pData = pMap->GetData(pImg->m_ImageData);\n\t\t\tm_aMenuTextures[i] = Graphics()->LoadTextureRaw(pImg->m_Width, pImg->m_Height, pImg->m_Version == 1 ? CImageInfo::FORMAT_RGBA : pImg->m_Format, pData, CImageInfo::FORMAT_RGBA, 0);\n\t\t\tpMap->UnloadData(pImg->m_ImageData);\n\t\t}\n\t}\n}\n\nIGraphics::CTextureHandle CMapImages::Get(int Index) const\n{\n\tif(Client()->State() == IClient::STATE_ONLINE || Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t\treturn m_aTextures[Index];\n\treturn m_aMenuTextures[Index];\n}\n\nint CMapImages::Num() const\n{\n\tif(Client()->State() == IClient::STATE_ONLINE || Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t\treturn m_Count;\n\treturn m_MenuCount;\n}\n"
  },
  {
    "path": "src/game/client/components/mapimages.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_MAPIMAGES_H\n#define GAME_CLIENT_COMPONENTS_MAPIMAGES_H\n#include <game/client/component.h>\n\nclass CMapImages : public CComponent\n{\n\tIGraphics::CTextureHandle m_aTextures[64];\n\tIGraphics::CTextureHandle m_aMenuTextures[64];\n\tint m_Count;\n\tint m_MenuCount;\npublic:\n\tCMapImages();\n\n\tIGraphics::CTextureHandle Get(int Index) const;\n\tint Num() const;\n\n\tvirtual void OnMapLoad();\n\tvoid OnMenuMapLoad(class IMap *pMap);\n};\n\n#endif\n"
  },
  {
    "path": "src/game/client/components/maplayers.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/graphics.h>\n#include <engine/keys.h>\n#include <engine/demo.h>\n#include <engine/serverbrowser.h>\n#include <engine/shared/config.h>\n#include <engine/storage.h>\n\n#include <game/layers.h>\n#include <game/client/gameclient.h>\n#include <game/client/component.h>\n#include <game/client/render.h>\n\n#include <game/client/components/camera.h>\n#include <game/client/components/mapimages.h>\n\n\n#include \"maplayers.h\"\n\nCMapLayers::CMapLayers(int t)\n{\n\tm_Type = t;\n\tm_CurrentLocalTick = 0;\n\tm_LastLocalTick = 0;\n\tm_EnvelopeUpdate = false;\n\tm_pMenuMap = 0;\n\tm_pMenuLayers = 0;\n}\n\nvoid CMapLayers::OnInit()\n{\n\tif(m_Type == TYPE_BACKGROUND)\n\t{\n\t\tm_pMenuLayers = new CLayers;\n\t\tm_pMenuMap = CreateEngineMap();\n\n\t\tchar aBuf[128];\n\t\tstr_format(aBuf, sizeof(aBuf), \"maps/%s.map\", g_Config.m_ClBackgroundMap);\n\t\tif(!m_pMenuMap->Load(aBuf, m_pClient->Storage()))\n\t\t{\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"map '%s' not found\", g_Config.m_ClBackgroundMap);\n\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"client\", aBuf);\n\t\t\treturn;\n\t\t}\n\n\t\tstr_format(aBuf, sizeof(aBuf), \"loaded map '%s'\", g_Config.m_ClBackgroundMap);\n\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"client\", aBuf);\n\n\t\tm_pMenuLayers->Init(Kernel(), m_pMenuMap);\n\t\tRenderTools()->RenderTilemapGenerateSkip(m_pMenuLayers);\n\t\tm_pClient->m_pMapimages->OnMenuMapLoad(m_pMenuMap);\n\t}\n}\n\nvoid CMapLayers::EnvelopeUpdate()\n{\n\tif(Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tconst IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo();\n\t\tm_CurrentLocalTick = pInfo->m_CurrentTick;\n\t\tm_LastLocalTick = pInfo->m_CurrentTick;\n\t\tm_EnvelopeUpdate = true;\n\t}\n}\n\n\nvoid CMapLayers::MapScreenToGroup(float CenterX, float CenterY, CMapItemGroup *pGroup)\n{\n\tfloat Points[4];\n\tRenderTools()->MapscreenToWorld(CenterX, CenterY, pGroup->m_ParallaxX/100.0f, pGroup->m_ParallaxY/100.0f,\n\t\tpGroup->m_OffsetX, pGroup->m_OffsetY, Graphics()->ScreenAspect(), m_pClient->m_pCamera->m_Zoom, Points);\n\tGraphics()->MapScreen(Points[0], Points[1], Points[2], Points[3]);\n}\n\nvoid CMapLayers::EnvelopeEval(float TimeOffset, int Env, float *pChannels, void *pUser)\n{\n\tCMapLayers *pThis = (CMapLayers *)pUser;\n\tpChannels[0] = 0;\n\tpChannels[1] = 0;\n\tpChannels[2] = 0;\n\tpChannels[3] = 0;\n\n\tCEnvPoint *pPoints = 0;\n\n\tCLayers *pLayers = 0;\n\t{\n\t\tint Start, Num;\n\t\tif(pThis->Client()->State() == IClient::STATE_ONLINE || pThis->Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t\t\tpLayers = pThis->Layers();\n\t\telse\n\t\t\tpLayers = pThis->m_pMenuLayers;\n\t\tpLayers->Map()->GetType(MAPITEMTYPE_ENVPOINTS, &Start, &Num);\n\t\tif(Num)\n\t\t\tpPoints = (CEnvPoint *)pLayers->Map()->GetItem(Start, 0, 0);\n\t}\n\n\tint Start, Num;\n\tpLayers->Map()->GetType(MAPITEMTYPE_ENVELOPE, &Start, &Num);\n\n\tif(Env >= Num)\n\t\treturn;\n\n\tCMapItemEnvelope *pItem = (CMapItemEnvelope *)pLayers->Map()->GetItem(Start+Env, 0, 0);\n\n\tstatic float s_Time = 0.0f;\n\tstatic float s_LastLocalTime = pThis->Client()->LocalTime();\n\tif(pThis->Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tconst IDemoPlayer::CInfo *pInfo = pThis->DemoPlayer()->BaseInfo();\n\t\t\n\t\tif(!pInfo->m_Paused || pThis->m_EnvelopeUpdate)\n\t\t{\n\t\t\tif(pThis->m_CurrentLocalTick != pInfo->m_CurrentTick)\n\t\t\t{\n\t\t\t\tpThis->m_LastLocalTick = pThis->m_CurrentLocalTick;\n\t\t\t\tpThis->m_CurrentLocalTick = pInfo->m_CurrentTick;\n\t\t\t}\n\n\t\t\ts_Time = mix(pThis->m_LastLocalTick / (float)pThis->Client()->GameTickSpeed(),\n\t\t\t\t\t\tpThis->m_CurrentLocalTick / (float)pThis->Client()->GameTickSpeed(),\n\t\t\t\t\t\tpThis->Client()->IntraGameTick());\n\t\t}\n\n\t\tpThis->RenderTools()->RenderEvalEnvelope(pPoints+pItem->m_StartPoint, pItem->m_NumPoints, 4, s_Time+TimeOffset, pChannels);\n\t}\n\telse if(pThis->Client()->State() != IClient::STATE_OFFLINE)\n\t{\n\t\tif(pThis->m_pClient->m_Snap.m_pGameData && !(pThis->m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED))\n\t\t{\n\t\t\tif(pItem->m_Version < 2 || pItem->m_Synchronized)\n\t\t\t{\n\t\t\t\ts_Time = mix((pThis->Client()->PrevGameTick()-pThis->m_pClient->m_Snap.m_pGameData->m_GameStartTick) / (float)pThis->Client()->GameTickSpeed(),\n\t\t\t\t\t\t\t(pThis->Client()->GameTick()-pThis->m_pClient->m_Snap.m_pGameData->m_GameStartTick) / (float)pThis->Client()->GameTickSpeed(),\n\t\t\t\t\t\t\tpThis->Client()->IntraGameTick());\n\t\t\t}\n\t\t\telse\n\t\t\t\ts_Time += pThis->Client()->LocalTime()-s_LastLocalTime;\n\t\t}\n\t\tpThis->RenderTools()->RenderEvalEnvelope(pPoints+pItem->m_StartPoint, pItem->m_NumPoints, 4, s_Time+TimeOffset, pChannels);\n\t\ts_LastLocalTime = pThis->Client()->LocalTime();\n\t}\n\telse\n\t{\n\t\ts_Time = pThis->Client()->LocalTime();\n\t\tpThis->RenderTools()->RenderEvalEnvelope(pPoints+pItem->m_StartPoint, pItem->m_NumPoints, 4, s_Time+TimeOffset, pChannels);\n\t}\n}\n\nvoid CMapLayers::OnRender()\n{\n\tif((Client()->State() != IClient::STATE_ONLINE && Client()->State() != IClient::STATE_DEMOPLAYBACK && !m_pMenuMap))\n\t\treturn;\n\n\tCLayers *pLayers = 0;\n\tif(Client()->State() == IClient::STATE_ONLINE || Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t\tpLayers = Layers();\n\telse if(m_pMenuMap->IsLoaded())\n\t\tpLayers = m_pMenuLayers;\n\n\tif(!pLayers)\n\t\treturn;\n\n\tCUIRect Screen;\n\tGraphics()->GetScreen(&Screen.x, &Screen.y, &Screen.w, &Screen.h);\n\n\tvec2 Center = m_pClient->m_pCamera->m_Center;\n\t//float center_x = gameclient.camera->center.x;\n\t//float center_y = gameclient.camera->center.y;\n\n\tbool PassedGameLayer = false;\n\n\tfor(int g = 0; g < pLayers->NumGroups(); g++)\n\t{\n\t\tCMapItemGroup *pGroup = pLayers->GetGroup(g);\n\n\t\tif(!g_Config.m_GfxNoclip && pGroup->m_Version >= 2 && pGroup->m_UseClipping)\n\t\t{\n\t\t\t// set clipping\n\t\t\tfloat Points[4];\n\t\t\tMapScreenToGroup(Center.x, Center.y, pLayers->GameGroup());\n\t\t\tGraphics()->GetScreen(&Points[0], &Points[1], &Points[2], &Points[3]);\n\t\t\tfloat x0 = (pGroup->m_ClipX - Points[0]) / (Points[2]-Points[0]);\n\t\t\tfloat y0 = (pGroup->m_ClipY - Points[1]) / (Points[3]-Points[1]);\n\t\t\tfloat x1 = ((pGroup->m_ClipX+pGroup->m_ClipW) - Points[0]) / (Points[2]-Points[0]);\n\t\t\tfloat y1 = ((pGroup->m_ClipY+pGroup->m_ClipH) - Points[1]) / (Points[3]-Points[1]);\n\n\t\t\tGraphics()->ClipEnable((int)(x0*Graphics()->ScreenWidth()), (int)(y0*Graphics()->ScreenHeight()),\n\t\t\t\t(int)((x1-x0)*Graphics()->ScreenWidth()), (int)((y1-y0)*Graphics()->ScreenHeight()));\n\t\t}\n\n\t\tMapScreenToGroup(Center.x, Center.y, pGroup);\n\n\t\tfor(int l = 0; l < pGroup->m_NumLayers; l++)\n\t\t{\n\t\t\tCMapItemLayer *pLayer = pLayers->GetLayer(pGroup->m_StartLayer+l);\n\t\t\tbool Render = false;\n\t\t\tbool IsGameLayer = false;\n\n\t\t\tif(pLayer == (CMapItemLayer*)pLayers->GameLayer())\n\t\t\t{\n\t\t\t\tIsGameLayer = true;\n\t\t\t\tPassedGameLayer = 1;\n\t\t\t}\n\n\t\t\t// skip rendering if detail layers if not wanted\n\t\t\tif(pLayer->m_Flags&LAYERFLAG_DETAIL && !g_Config.m_GfxHighDetail && !IsGameLayer && (Client()->State() == IClient::STATE_ONLINE || Client()->State() == IClient::STATE_DEMOPLAYBACK))\n\t\t\t\tcontinue;\n\n\t\t\tif(m_Type == -1)\n\t\t\t\tRender = true;\n\t\t\telse if(m_Type == 0)\n\t\t\t{\n\t\t\t\tif(PassedGameLayer && (Client()->State() == IClient::STATE_ONLINE || Client()->State() == IClient::STATE_DEMOPLAYBACK))\n\t\t\t\t\treturn;\n\t\t\t\tRender = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(PassedGameLayer && !IsGameLayer)\n\t\t\t\t\tRender = true;\n\t\t\t}\n\n\t\t\tif(Render && pLayer->m_Type == LAYERTYPE_TILES && Input()->KeyPressed(KEY_LCTRL) && Input()->KeyPressed(KEY_LSHIFT) && Input()->KeyDown(KEY_KP0))\n\t\t\t{\n\t\t\t\tCMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer;\n\t\t\t\tCTile *pTiles = (CTile *)pLayers->Map()->GetData(pTMap->m_Data);\n\t\t\t\tCServerInfo CurrentServerInfo;\n\t\t\t\tClient()->GetServerInfo(&CurrentServerInfo);\n\t\t\t\tchar aFilename[256];\n\t\t\t\tstr_format(aFilename, sizeof(aFilename), \"dumps/tilelayer_dump_%s-%d-%d-%dx%d.txt\", CurrentServerInfo.m_aMap, g, l, pTMap->m_Width, pTMap->m_Height);\n\t\t\t\tIOHANDLE File = Storage()->OpenFile(aFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE);\n\t\t\t\tif(File)\n\t\t\t\t{\n\t\t\t\t\tfor(int y = 0; y < pTMap->m_Height; y++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor(int x = 0; x < pTMap->m_Width; x++)\n\t\t\t\t\t\t\tio_write(File, &(pTiles[y*pTMap->m_Width + x].m_Index), sizeof(pTiles[y*pTMap->m_Width + x].m_Index));\n\t\t\t\t\t\tio_write_newline(File);\n\t\t\t\t\t}\n\t\t\t\t\tio_close(File);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(Render && !IsGameLayer)\n\t\t\t{\n\t\t\t\t//layershot_begin();\n\n\t\t\t\tif(pLayer->m_Type == LAYERTYPE_TILES)\n\t\t\t\t{\n\t\t\t\t\tCMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer;\n\t\t\t\t\tif(pTMap->m_Image == -1)\n\t\t\t\t\t\tGraphics()->TextureClear();\n\t\t\t\t\telse\n\t\t\t\t\t\tGraphics()->TextureSet(m_pClient->m_pMapimages->Get(pTMap->m_Image));\n\n\t\t\t\t\tCTile *pTiles = (CTile *)pLayers->Map()->GetData(pTMap->m_Data);\n\t\t\t\t\tGraphics()->BlendNone();\n\t\t\t\t\tvec4 Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f);\n\t\t\t\t\tRenderTools()->RenderTilemap(pTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE,\n\t\t\t\t\t\t\t\t\t\t\t\t\tEnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset);\n\t\t\t\t\tGraphics()->BlendNormal();\n\t\t\t\t\tRenderTools()->RenderTilemap(pTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT,\n\t\t\t\t\t\t\t\t\t\t\t\t\tEnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset);\n\t\t\t\t}\n\t\t\t\telse if(pLayer->m_Type == LAYERTYPE_QUADS)\n\t\t\t\t{\n\t\t\t\t\tCMapItemLayerQuads *pQLayer = (CMapItemLayerQuads *)pLayer;\n\t\t\t\t\tif(pQLayer->m_Image == -1)\n\t\t\t\t\t\tGraphics()->TextureClear();\n\t\t\t\t\telse\n\t\t\t\t\t\tGraphics()->TextureSet(m_pClient->m_pMapimages->Get(pQLayer->m_Image));\n\n\t\t\t\t\tCQuad *pQuads = (CQuad *)pLayers->Map()->GetDataSwapped(pQLayer->m_Data);\n\n\t\t\t\t\tGraphics()->BlendNone();\n\t\t\t\t\tRenderTools()->RenderQuads(pQuads, pQLayer->m_NumQuads, LAYERRENDERFLAG_OPAQUE, EnvelopeEval, this);\n\t\t\t\t\tGraphics()->BlendNormal();\n\t\t\t\t\tRenderTools()->RenderQuads(pQuads, pQLayer->m_NumQuads, LAYERRENDERFLAG_TRANSPARENT, EnvelopeEval, this);\n\t\t\t\t}\n\n\t\t\t\t//layershot_end();\n\t\t\t}\n\t\t}\n\t\tif(!g_Config.m_GfxNoclip)\n\t\t\tGraphics()->ClipDisable();\n\t}\n\n\tif(!g_Config.m_GfxNoclip)\n\t\tGraphics()->ClipDisable();\n\n\t// reset the screen like it was before\n\tGraphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h);\n}\n\nvoid CMapLayers::ConchainBackgroundMap(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)\n{\n\tpfnCallback(pResult, pCallbackUserData);\n\tif(pResult->NumArguments())\n\t\t((CMapLayers*)pUserData)->BackgroundMapUpdate();\n}\n\nvoid CMapLayers::OnConsoleInit()\n{\n\tConsole()->Chain(\"cl_background_map\", ConchainBackgroundMap, this);\n}\n\nvoid CMapLayers::BackgroundMapUpdate()\n{\n\tif(m_Type == TYPE_BACKGROUND && m_pMenuMap)\n\t{\n\t\t// uload map\n\t\tm_pMenuMap->Unload();\n\n\t\tchar aBuf[128];\n\t\tstr_format(aBuf, sizeof(aBuf), \"maps/%s.map\", g_Config.m_ClBackgroundMap);\n\t\tif(!m_pMenuMap->Load(aBuf, m_pClient->Storage()))\n\t\t{\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"map '%s' not found\", g_Config.m_ClBackgroundMap);\n\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"client\", aBuf);\n\t\t\treturn;\n\t\t}\n\n\t\tstr_format(aBuf, sizeof(aBuf), \"loaded map '%s'\", g_Config.m_ClBackgroundMap);\n\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"client\", aBuf);\n\n\t\tm_pMenuLayers->Init(Kernel(), m_pMenuMap);\n\t\tRenderTools()->RenderTilemapGenerateSkip(m_pMenuLayers);\n\t\tm_pClient->m_pMapimages->OnMenuMapLoad(m_pMenuMap);\n\t}\n}\n"
  },
  {
    "path": "src/game/client/components/maplayers.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_MAPLAYERS_H\n#define GAME_CLIENT_COMPONENTS_MAPLAYERS_H\n#include <game/client/component.h>\n\nclass CMapLayers : public CComponent\n{\n\tCLayers *m_pMenuLayers;\n\tIEngineMap *m_pMenuMap;\n\n\tint m_Type;\n\tint m_CurrentLocalTick;\n\tint m_LastLocalTick;\n\tbool m_EnvelopeUpdate;\n\n\tvoid MapScreenToGroup(float CenterX, float CenterY, CMapItemGroup *pGroup);\n\tstatic void EnvelopeEval(float TimeOffset, int Env, float *pChannels, void *pUser);\npublic:\n\tenum\n\t{\n\t\tTYPE_BACKGROUND=0,\n\t\tTYPE_FOREGROUND,\n\t};\n\n\tCMapLayers(int Type);\n\tvirtual void OnInit();\n\tvirtual void OnRender();\n\n\tvoid EnvelopeUpdate();\n\n\tstatic void ConchainBackgroundMap(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData);\n\n\tvirtual void OnConsoleInit();\n\n\tvoid BackgroundMapUpdate();\n\n\tbool MenuMapLoaded() { return m_pMenuMap ? m_pMenuMap->IsLoaded() : false; }\n};\n\n#endif\n"
  },
  {
    "path": "src/game/client/components/menus.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <math.h>\n\n#include <base/system.h>\n#include <base/math.h>\n#include <base/vmath.h>\n\n#include <engine/config.h>\n#include <engine/editor.h>\n#include <engine/engine.h>\n#include <engine/friends.h>\n#include <engine/keys.h>\n#include <engine/serverbrowser.h>\n#include <engine/storage.h>\n#include <engine/textrender.h>\n#include <engine/shared/config.h>\n\n#include <game/version.h>\n#include <game/generated/protocol.h>\n\n#include <game/generated/client_data.h>\n#include <game/client/components/camera.h>\n#include <game/client/components/sounds.h>\n#include <game/client/gameclient.h>\n#include <game/client/lineinput.h>\n#include <mastersrv/mastersrv.h>\n\n#include \"maplayers.h\"\n#include \"countryflags.h\"\n#include \"menus.h\"\n#include \"skins.h\"\n\nfloat CMenus::ms_ButtonHeight = 25.0f;\nfloat CMenus::ms_ListheaderHeight = 20.0f;\nfloat CMenus::ms_FontmodHeight = 0.8f;\n\nIInput::CEvent CMenus::m_aInputEvents[MAX_INPUTEVENTS];\nint CMenus::m_NumInputEvents;\n\n\nCMenus::CMenus()\n{\n\tm_Popup = POPUP_NONE;\n\tm_NextPopup = POPUP_NONE;\n\tm_ActivePage = PAGE_INTERNET;\n\tm_GamePage = PAGE_GAME;\n\n\tm_NeedRestartGraphics = false;\n\tm_NeedRestartSound = false;\n\tm_TeePartSelected = CSkins::SKINPART_BODY;\n\tm_aSaveSkinName[0] = 0;\n\tm_RefreshSkinSelector = true;\n\tm_pSelectedSkin = 0;\n\tm_MenuActive = true;\n\tm_UseMouseButtons = true;\n\n\tm_MenuPage = PAGE_START;\n\n\tm_InfoMode = false;\n\n\tm_EscapePressed = false;\n\tm_EnterPressed = false;\n\tm_DeletePressed = false;\n\tm_NumInputEvents = 0;\n\n\tm_LastInput = time_get();\n\n\tstr_copy(m_aCurrentDemoFolder, \"demos\", sizeof(m_aCurrentDemoFolder));\n\tm_aCallvoteReason[0] = 0;\n\n\tm_FriendlistSelectedIndex = -1;\n\n\tm_SelectedFilter = 0;\n\n\tm_SelectedServer.m_Filter = -1;\n\tm_SelectedServer.m_Index = -1;\n}\n\nfloat *CMenus::ButtonFade(const void *pID, float Seconds, int Checked)\n{\n\tfloat *pFade = (float*)pID;\n\tif(UI()->HotItem() == pID || Checked)\n\t\t*pFade = Seconds;\n\telse if(*pFade > 0.0f)\n\t{\n\t\t*pFade -= Client()->RenderFrameTime();\n\t\tif(*pFade < 0.0f)\n\t\t\t*pFade = 0.0f;\n\t}\n\treturn pFade;\n}\n\nint CMenus::DoIcon(int ImageId, int SpriteId, const CUIRect *pRect)\n{\n\tGraphics()->TextureSet(g_pData->m_aImages[ImageId].m_Id);\n\n\tGraphics()->QuadsBegin();\n\tRenderTools()->SelectSprite(SpriteId);\n\tIGraphics::CQuadItem QuadItem(pRect->x, pRect->y, pRect->w, pRect->h);\n\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n\n\treturn 0;\n}\n\nint CMenus::DoButton_Toggle(const void *pID, int Checked, const CUIRect *pRect, bool Active)\n{\n\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_GUIBUTTONS].m_Id);\n\tGraphics()->QuadsBegin();\n\tif(!Active)\n\t\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 0.5f);\n\tRenderTools()->SelectSprite(Checked?SPRITE_GUIBUTTON_ON:SPRITE_GUIBUTTON_OFF);\n\tIGraphics::CQuadItem QuadItem(pRect->x, pRect->y, pRect->w, pRect->h);\n\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tif(UI()->HotItem() == pID && Active)\n\t{\n\t\tRenderTools()->SelectSprite(SPRITE_GUIBUTTON_HOVER);\n\t\tIGraphics::CQuadItem QuadItem(pRect->x, pRect->y, pRect->w, pRect->h);\n\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t}\n\tGraphics()->QuadsEnd();\n\n\treturn Active ? UI()->DoButtonLogic(pID, \"\", Checked, pRect) : 0;\n}\n\nint CMenus::DoButton_Menu(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Corners, float r, float FontFactor, vec4 ColorHot, bool TextFade)\n{\n\tfloat Seconds = 0.6f; //  0.6 seconds for fade\n\tfloat *pFade = ButtonFade(pID, Seconds, Checked);\n\tfloat FadeVal = *pFade/Seconds;\n\n\tvec4 Color = mix(vec4(0.0f, 0.0f, 0.0f, 0.25f), ColorHot, FadeVal);\n\n\tRenderTools()->DrawUIRect(pRect, Color, Corners, r);\n\tCUIRect Temp;\n\tpRect->HMargin(pRect->h>=20.0f?2.0f:1.0f, &Temp);\n\tTemp.HMargin((Temp.h*FontFactor)/2.0f, &Temp);\n\tif(TextFade)\n\t{\n\t\tTextRender()->TextColor(1.0f-FadeVal, 1.0f-FadeVal, 1.0f-FadeVal, 1.0f);\n\t\tTextRender()->TextOutlineColor(0.0f+FadeVal, 0.0f+FadeVal, 0.0f+FadeVal, 0.25f);\n\t}\n\tUI()->DoLabel(&Temp, pText, Temp.h*ms_FontmodHeight, 0);\n\tif(TextFade)\n\t{\n\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\tTextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f);\n\t}\n\treturn UI()->DoButtonLogic(pID, pText, Checked, pRect);\n}\n\nint CMenus::DoButton_MenuImage(const void *pID, const char *pText, int Checked, const CUIRect *pRect, const char *pImageName, float r, float FontFactor)\n{\n\tfloat Seconds = 0.6f; //  0.6 seconds for fade\n\tfloat *pFade = ButtonFade(pID, Seconds);\n\tfloat FadeVal = *pFade/Seconds;\n\n\tRenderTools()->DrawUIRect(pRect, vec4(0.0f+FadeVal, 0.0f+FadeVal, 0.0f+FadeVal, 0.25f+FadeVal*0.5f), CUI::CORNER_ALL, r);\n\tCUIRect Text, Image;\n\tpRect->VSplitRight(pRect->h*4.0f, &Text, &Image); // always correct ratio for image\n\n\t// render image\n\tconst CMenuImage *pImage = FindMenuImage(pImageName);\n\tif(pImage)\n\t{\n\t\t\n\t\tGraphics()->TextureSet(pImage->m_GreyTexture);\n\t\tGraphics()->QuadsBegin();\n\t\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\tIGraphics::CQuadItem QuadItem(Image.x, Image.y, Image.w, Image.h);\n\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t\tGraphics()->QuadsEnd();\n\n\t\tif(*pFade > 0.0f)\n\t\t{\n\t\t\tGraphics()->TextureSet(pImage->m_OrgTexture);\n\t\t\tGraphics()->QuadsBegin();\n\t\t\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, *pFade/Seconds);\n\t\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t\t\tGraphics()->QuadsEnd();\n\t\t}\n\t\t\n\t}\n\n\tText.HMargin(pRect->h>=20.0f?2.0f:1.0f, &Text);\n\tText.HMargin((Text.h*FontFactor)/2.0f, &Text);\n\tText.VSplitLeft(r, 0, &Text);\n\tTextRender()->TextColor(1.0f-FadeVal, 1.0f-FadeVal, 1.0f-FadeVal, 1.0f);\n\tTextRender()->TextOutlineColor(0.0f+FadeVal, 0.0f+FadeVal, 0.0f+FadeVal, 0.25f);\n\tUI()->DoLabel(&Text, pText, Text.h*ms_FontmodHeight, 0);\n\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\tTextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f);\n\treturn UI()->DoButtonLogic(pID, pText, Checked, pRect);\n}\n\nvoid CMenus::DoButton_KeySelect(const void *pID, const char *pText, int Checked, const CUIRect *pRect)\n{\n\tfloat Seconds = 0.6f; //  0.6 seconds for fade\n\tfloat *pFade = ButtonFade(pID, Seconds, Checked);\n\tfloat FadeVal = *pFade/Seconds;\n\n\tRenderTools()->DrawUIRect(pRect, vec4(0.0f+FadeVal, 0.0f+FadeVal, 0.0f+FadeVal, 0.25f+FadeVal*0.5f), CUI::CORNER_ALL, 5.0f);\n\tCUIRect Temp;\n\tpRect->HMargin(1.0f, &Temp);\n\tTextRender()->TextColor(1.0f-FadeVal, 1.0f-FadeVal, 1.0f-FadeVal, 1.0f);\n\tTextRender()->TextOutlineColor(0.0f+FadeVal, 0.0f+FadeVal, 0.0f+FadeVal, 0.25f);\n\tUI()->DoLabel(&Temp, pText, Temp.h*ms_FontmodHeight, 0);\n\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\tTextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f);\n}\n\nint CMenus::DoButton_MenuTab(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Corners)\n{\n\tif(Checked)\n\t\tRenderTools()->DrawUIRect(pRect, vec4(1.0f, 1.0f, 1.0f, 0.25f), Corners, 10.0f);\n\telse\n\t{\n\t\tRenderTools()->DrawUIRect(pRect, vec4(0.0f, 0.0f, 0.0f, 0.25f), Corners, 10.0f);\n\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 0.7f);\n\t}\n\n\tCUIRect Temp;\n\tpRect->HMargin(pRect->h>=20.0f?2.0f:1.0f, &Temp);\n\tUI()->DoLabel(&Temp, pText, Temp.h*ms_FontmodHeight, 0);\n\n\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\treturn UI()->DoButtonLogic(pID, pText, Checked, pRect);\n}\n\nint CMenus::DoButton_MenuTabTop(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Corners, float r, float FontFactor)\n{\n\tfloat Seconds = 0.6f; //  0.6 seconds for fade\n\tfloat *pFade = ButtonFade(pID, Seconds, Checked);\n\tfloat FadeVal = *pFade/Seconds;\n\n\tRenderTools()->DrawUIRect(pRect, vec4(0.0f+FadeVal, 0.0f+FadeVal, 0.0f+FadeVal, 0.25f+FadeVal*0.5f), Corners, r);\n\tCUIRect Temp;\n\tpRect->HMargin(pRect->h>=20.0f?2.0f:1.0f, &Temp);\n\tTemp.HMargin((Temp.h*FontFactor)/2.0f, &Temp);\n\tTextRender()->TextColor(1.0f-FadeVal, 1.0f-FadeVal, 1.0f-FadeVal, 1.0f);\n\tTextRender()->TextOutlineColor(0.0f+FadeVal, 0.0f+FadeVal, 0.0f+FadeVal, 0.25f);\n\tUI()->DoLabel(&Temp, pText, Temp.h*ms_FontmodHeight, 0);\n\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\tTextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f);\n\treturn UI()->DoButtonLogic(pID, pText, Checked, pRect);\n}\n\nint CMenus::DoButton_GridHeader(const void *pID, const char *pText, int Checked, const CUIRect *pRect)\n//void CMenus::ui_draw_grid_header(const void *id, const char *text, int checked, const CUIRect *r, const void *extra)\n{\n\tif(Checked)\n\t{\n\t\tRenderTools()->DrawUIRect(pRect, vec4(1,1,1,0.5f), CUI::CORNER_ALL, 5.0f);\n\t\tTextRender()->TextColor(0.0f, 0.0f, 0.0f, 1.0f);\n\t\tTextRender()->TextOutlineColor(1.0f, 1.0f, 1.0f, 0.25f);\n\t}\n\n\tCUIRect Label;\n\tpRect->VSplitLeft(5.0f, 0, &Label);\n\tLabel.y+=2.0f;\n\tUI()->DoLabel(&Label, pText, pRect->h*ms_FontmodHeight*0.8f, 0);\n\n\tif(Checked)\n\t{\n\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\tTextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f);\n\t}\n\n\treturn UI()->DoButtonLogic(pID, pText, Checked, pRect);\n}\n\nint CMenus::DoButton_GridHeaderIcon(const void *pID, int ImageID, int SpriteID, const CUIRect *pRect, int Corners)\n{\n\tfloat Seconds = 0.6f; //  0.6 seconds for fade\n\tfloat *pFade = ButtonFade(pID, Seconds);\n\n\tRenderTools()->DrawUIRect(pRect, vec4(1.0f, 1.0f, 1.0f, 0.5f+(*pFade/Seconds)*0.25f), Corners, 5.0f);\n\n\tCUIRect Image;\n\tpRect->HMargin(2.0f, &Image);\n\tpRect->VMargin((Image.w-Image.h)/2.0f, &Image);\n\n\tGraphics()->TextureSet(g_pData->m_aImages[ImageID].m_Id);\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 0.5f);\n\tRenderTools()->SelectSprite(SpriteID);\n\tIGraphics::CQuadItem QuadItem(Image.x, Image.y, Image.w, Image.h);\n\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n\n\treturn UI()->DoButtonLogic(pID, \"\", false, pRect);\n}\n\nint CMenus::DoButton_CheckBox_Common(const void *pID, const char *pText, const char *pBoxText, const CUIRect *pRect, bool Checked)\n//void CMenus::ui_draw_checkbox_common(const void *id, const char *text, const char *boxtext, const CUIRect *r, const void *extra)\n{\n\tRenderTools()->DrawUIRect(pRect, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\tCUIRect c = *pRect;\n\tCUIRect t = *pRect;\n\tc.w = c.h;\n\tt.x += c.w;\n\tt.w -= c.w;\n\tt.VSplitLeft(5.0f, 0, &t);\n\n\tc.Margin(2.0f, &c);\n\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_MENUICONS].m_Id);\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, UI()->HotItem() == pID ? 1.0f : 0.6f);\n\tif(Checked)\n\t\tRenderTools()->SelectSprite(SPRITE_MENU_CHECKBOX_ACTIVE);\n\telse\n\t\tRenderTools()->SelectSprite(SPRITE_MENU_CHECKBOX_INACTIVE);\n\tIGraphics::CQuadItem QuadItem(c.x, c.y, c.w, c.h);\n\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n\n\tt.y += 2.0f; // lame fix\n\tUI()->DoLabel(&c, pBoxText, pRect->h*ms_FontmodHeight*0.6f, 0);\n\tUI()->DoLabel(&t, pText, pRect->h*ms_FontmodHeight*0.8f, -1);\n\treturn UI()->DoButtonLogic(pID, pText, 0, pRect);\n}\n\nint CMenus::DoButton_CheckBox(const void *pID, const char *pText, int Checked, const CUIRect *pRect)\n{\n\treturn DoButton_CheckBox_Common(pID, pText, \"\", pRect, Checked);\n}\n\nint CMenus::DoButton_CheckBox_Number(const void *pID, const char *pText, int Checked, const CUIRect *pRect)\n{\n\tchar aBuf[16];\n\tstr_format(aBuf, sizeof(aBuf), \"%d\", Checked);\n\treturn DoButton_CheckBox_Common(pID, pText, aBuf, pRect);\n}\n\nint CMenus::DoButton_SpriteID(const void *pID, int ImageID, int SpriteID, const CUIRect *pRect, int Corners, float r, bool Fade)\n{\n\tfloat Seconds = 0.6f; //  0.6 seconds for fade\n\tfloat *pFade = ButtonFade(pID, Seconds);\n\tfloat FadeVal = *pFade/Seconds;\n\n\tCUIRect Icon = *pRect;\n\tIcon.Margin(2.0f, &Icon);\n\n\tif(Fade)\n\t\tRenderTools()->DrawUIRect(pRect, vec4(0.0f+FadeVal, 0.0f+FadeVal, 0.0f+FadeVal, 0.25f+FadeVal*0.5f), Corners, r);\n\telse\n\t\tRenderTools()->DrawUIRect(pRect, vec4(0.0f, 0.0f, 0.0f, 0.25f), Corners, r);\n\tGraphics()->TextureSet(g_pData->m_aImages[ImageID].m_Id);\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);\n\tRenderTools()->SelectSprite(SpriteID);\n\tIGraphics::CQuadItem QuadItem(Icon.x, Icon.y, Icon.w, Icon.h);\n\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n\n\treturn UI()->DoButtonLogic(pID, \"\", false, pRect);\n}\n\nint CMenus::DoButton_SpriteClean(int ImageID, int SpriteID, const CUIRect *pRect)\n{\n\tint Inside = UI()->MouseInside(pRect);\n\n\tGraphics()->TextureSet(g_pData->m_aImages[ImageID].m_Id);\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, Inside ? 1.0f : 0.6f);\n\tRenderTools()->SelectSprite(SpriteID);\n\tIGraphics::CQuadItem QuadItem(pRect->x, pRect->y, pRect->w, pRect->h);\n\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n\n\tint ReturnValue = 0;\n\tif(Inside && Input()->KeyDown(KEY_MOUSE_1))\n\t\tReturnValue = 1;\n\n\treturn ReturnValue;\n}\n\nint CMenus::DoButton_SpriteCleanID(const void *pID, int ImageID, int SpriteID, const CUIRect *pRect, bool Blend)\n{\n\tint Inside = UI()->MouseInside(pRect);\n\n\tGraphics()->TextureSet(g_pData->m_aImages[ImageID].m_Id);\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, !Blend || Inside ? 1.0f : 0.6f);\n\tRenderTools()->SelectSprite(SpriteID);\n\tIGraphics::CQuadItem QuadItem(pRect->x, pRect->y, pRect->w, pRect->h);\n\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n\n\treturn UI()->DoButtonLogic(pID, 0, 0, pRect);\n}\n\nint CMenus::DoButton_MouseOver(int ImageID, int SpriteID, const CUIRect *pRect)\n{\n\tint Inside = UI()->MouseInside(pRect);\n\n\tGraphics()->TextureSet(g_pData->m_aImages[ImageID].m_Id);\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, Inside ? 1.0f : 0.6f);\n\tRenderTools()->SelectSprite(SpriteID);\n\tIGraphics::CQuadItem QuadItem(pRect->x, pRect->y, pRect->w, pRect->h);\n\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n\n\treturn Inside;\n}\n\nint CMenus::DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned StrSize, float FontSize, float *pOffset, bool Hidden, int Corners)\n{\n\tint Inside = UI()->MouseInside(pRect);\n\tbool ReturnValue = false;\n\tbool UpdateOffset = false;\n\tstatic int s_AtIndex = 0;\n\tstatic bool s_DoScroll = false;\n\n\tFontSize *= UI()->Scale();\n\n\tif(UI()->LastActiveItem() == pID)\n\t{\n\t\tstatic float s_ScrollStart = 0.0f;\n\n\t\tint Len = str_length(pStr);\n\t\tif(Len == 0)\n\t\t\ts_AtIndex = 0;\n\n\t\tif(Inside && UI()->MouseButton(0))\n\t\t{\n\t\t\ts_DoScroll = true;\n\t\t\ts_ScrollStart = UI()->MouseX();\n\t\t\tint MxRel = (int)(UI()->MouseX() - pRect->x);\n\t\t\tfloat Offset = pRect->w/2.0f-TextRender()->TextWidth(0, FontSize, pStr, -1)/2.0f;\n\n\t\t\tfor(int i = 1; i <= Len; i++)\n\t\t\t{\n\t\t\t\tif(Offset + TextRender()->TextWidth(0, FontSize, pStr, i) - *pOffset > MxRel)\n\t\t\t\t{\n\t\t\t\t\ts_AtIndex = i - 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif(i == Len)\n\t\t\t\t\ts_AtIndex = Len;\n\t\t\t}\n\t\t}\n\t\telse if(!UI()->MouseButton(0))\n\t\t\ts_DoScroll = false;\n\t\telse if(s_DoScroll)\n\t\t{\n\t\t\t// do scrolling\n\t\t\tif(UI()->MouseX() < pRect->x && s_ScrollStart-UI()->MouseX() > 10.0f)\n\t\t\t{\n\t\t\t\ts_AtIndex = max(0, s_AtIndex-1);\n\t\t\t\ts_ScrollStart = UI()->MouseX();\n\t\t\t\tUpdateOffset = true;\n\t\t\t}\n\t\t\telse if(UI()->MouseX() > pRect->x+pRect->w && UI()->MouseX()-s_ScrollStart > 10.0f)\n\t\t\t{\n\t\t\t\ts_AtIndex = min(Len, s_AtIndex+1);\n\t\t\t\ts_ScrollStart = UI()->MouseX();\n\t\t\t\tUpdateOffset = true;\n\t\t\t}\n\t\t}\n\n\t\tfor(int i = 0; i < m_NumInputEvents; i++)\n\t\t{\n\t\t\tLen = str_length(pStr);\n\t\t\tReturnValue |= CLineInput::Manipulate(m_aInputEvents[i], pStr, StrSize, &Len, &s_AtIndex);\n\t\t}\n\t}\n\n\tbool JustGotActive = false;\n\n\tif(UI()->ActiveItem() == pID)\n\t{\n\t\tif(!UI()->MouseButton(0))\n\t\t{\n\t\t\ts_AtIndex = min(s_AtIndex, str_length(pStr));\n\t\t\ts_DoScroll = false;\n\t\t\tUI()->SetActiveItem(0);\n\t\t}\n\t}\n\telse if(UI()->HotItem() == pID)\n\t{\n\t\tif(UI()->MouseButton(0))\n\t\t{\n\t\t\tif (UI()->LastActiveItem() != pID)\n\t\t\t\tJustGotActive = true;\n\t\t\tUI()->SetActiveItem(pID);\n\t\t}\n\t}\n\n\tif(Inside)\n\t\tUI()->SetHotItem(pID);\n\n\tCUIRect Textbox = *pRect;\n\tRenderTools()->DrawUIRect(&Textbox, vec4(0.0f, 0.0f, 0.0f, 0.25f), Corners, 5.0f);\n\tTextbox.VMargin(2.0f, &Textbox);\n\tTextbox.HMargin(2.0f, &Textbox);\n\n\tconst char *pDisplayStr = pStr;\n\tchar aStars[128];\n\n\tif(Hidden)\n\t{\n\t\tunsigned s = str_length(pStr);\n\t\tif(s >= sizeof(aStars))\n\t\t\ts = sizeof(aStars)-1;\n\t\tfor(unsigned int i = 0; i < s; ++i)\n\t\t\taStars[i] = '*';\n\t\taStars[s] = 0;\n\t\tpDisplayStr = aStars;\n\t}\n\n\t// check if the text has to be moved\n\tif(UI()->LastActiveItem() == pID && !JustGotActive && (UpdateOffset || m_NumInputEvents))\n\t{\n\t\tfloat w = TextRender()->TextWidth(0, FontSize, pDisplayStr, s_AtIndex);\n\t\tif(w-*pOffset > Textbox.w)\n\t\t{\n\t\t\t// move to the left\n\t\t\tfloat wt = TextRender()->TextWidth(0, FontSize, pDisplayStr, -1);\n\t\t\tdo\n\t\t\t{\n\t\t\t\t*pOffset += min(wt-*pOffset-Textbox.w, Textbox.w/3);\n\t\t\t}\n\t\t\twhile(w-*pOffset > Textbox.w);\n\t\t}\n\t\telse if(w-*pOffset < 0.0f)\n\t\t{\n\t\t\t// move to the right\n\t\t\tdo\n\t\t\t{\n\t\t\t\t*pOffset = max(0.0f, *pOffset-Textbox.w/3);\n\t\t\t}\n\t\t\twhile(w-*pOffset < 0.0f);\n\t\t}\n\t}\n\tUI()->ClipEnable(pRect);\n\tTextbox.x -= *pOffset;\n\n\tUI()->DoLabel(&Textbox, pDisplayStr, FontSize, 0);\n\n\t// render the cursor\n\tif(UI()->LastActiveItem() == pID && !JustGotActive)\n\t{\n\t\tfloat w = TextRender()->TextWidth(0, FontSize, pDisplayStr, -1);\n\t\tTextbox = *pRect;\n\t\tTextbox.x += Textbox.w/2.0f-w/2.0f;\n\t\tw = TextRender()->TextWidth(0, FontSize, pDisplayStr, s_AtIndex);\n\t\tTextbox.x += (w-*pOffset-TextRender()->TextWidth(0, FontSize, \"|\", -1)/2);\n\n\t\tif((2*time_get()/time_freq()) % 2)\t// make it blink\n\t\t\tUI()->DoLabel(&Textbox, \"|\", FontSize, -1);\n\t}\n\tUI()->ClipDisable();\n\n\treturn ReturnValue;\n}\n\nvoid CMenus::DoEditBoxOption(void *pID, char *pOption, int OptionLength, const CUIRect *pRect, const char *pStr,  float VSplitVal, float *pOffset, bool Hidden)\n{\n\tRenderTools()->DrawUIRect(pRect, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\tCUIRect Label, EditBox;\n\tpRect->VSplitLeft(VSplitVal, &Label, &EditBox);\n\n\tchar aBuf[32];\n\tstr_format(aBuf, sizeof(aBuf), \"%s:\", pStr);\n\tLabel.y += 2.0f;\n\tUI()->DoLabel(&Label, aBuf, pRect->h*ms_FontmodHeight*0.8f, 0);\n\n\tDoEditBox(pID, &EditBox, pOption, OptionLength, pRect->h*ms_FontmodHeight*0.8f, pOffset, Hidden);\n}\n\nvoid CMenus::DoScrollbarOption(void *pID, int *pOption, const CUIRect *pRect, const char *pStr, float VSplitVal, int Min, int Max, bool infinite)\n{\n\tRenderTools()->DrawUIRect(pRect, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\tCUIRect Label, ScrollBar;\n\tpRect->VSplitLeft(VSplitVal, &Label, &ScrollBar);\n\n\tchar aBuf[32];\n\tif(*pOption || !infinite)\n\t\tstr_format(aBuf, sizeof(aBuf), \"%s: %i\", pStr, *pOption);\n\telse\n\t\tstr_format(aBuf, sizeof(aBuf), \"%s: \\xe2\\x88\\x9e\", pStr);\n\tLabel.VSplitLeft(Label.h+5.0f, 0, &Label);\n\tLabel.y += 2.0f;\n\tUI()->DoLabel(&Label, aBuf, pRect->h*ms_FontmodHeight*0.8f, -1);\n\n\tScrollBar.VMargin(4.0f, &ScrollBar);\n\t*pOption = static_cast<int>(DoScrollbarH(pOption, &ScrollBar, (float)(*pOption-Min)/(float)(Max-Min))*(float)(Max-Min)+(float)Min+0.1f);\n}\n\nfloat CMenus::DoDropdownMenu(void *pID, const CUIRect *pRect, const char *pStr, float HeaderHeight, FDropdownCallback pfnCallback)\n{\n\tCUIRect View = *pRect;\n\tCUIRect Header, Label;\n\n\tbool Active = pID == m_pActiveDropdown;\n\tint Corners = Active ? CUI::CORNER_T : CUI::CORNER_ALL;\n\n\tView.HSplitTop(HeaderHeight, &Header, &View);\n\n\t// background\n\tRenderTools()->DrawUIRect(&Header, vec4(0.0f, 0.0f, 0.0f, 0.25f), Corners, 5.0f);\n\n\t// render icon\n\tCUIRect Button;\n\tHeader.VSplitLeft(Header.h, &Button, 0);\n\tButton.Margin(2.0f, &Button);\n\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_MENUICONS].m_Id);\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, UI()->HotItem() == pID ? 1.0f : 0.6f);\n\tif(Active)\n\t\tRenderTools()->SelectSprite(SPRITE_MENU_EXPANDED);\n\telse\n\t\tRenderTools()->SelectSprite(SPRITE_MENU_COLLAPSED);\n\tIGraphics::CQuadItem QuadItem(Button.x, Button.y, Button.w, Button.h);\n\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);\n\tGraphics()->QuadsEnd();\n\n\t// label\n\tLabel = Header;\n\tLabel.y += 2.0f;\n\tUI()->DoLabel(&Label, pStr, Header.h*ms_FontmodHeight*0.8f, 0);\n\n\tif(UI()->DoButtonLogic(pID, 0, 0, &Header))\n\t{\n\t\tif(Active)\n\t\t\tm_pActiveDropdown = 0;\n\t\telse\n\t\t\tm_pActiveDropdown = (int*)pID;\n\t}\n\n\t// render content of expanded menu\n\tif(Active)\n\t\treturn HeaderHeight + pfnCallback(View, this);\n\n\treturn HeaderHeight;\n}\n\nvoid CMenus::DoInfoBox(const CUIRect *pRect, const char *pLabel, const char *pValue)\n{\n\tRenderTools()->DrawUIRect(pRect, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\tCUIRect Label, Value;\n\tpRect->VSplitMid(&Label, &Value);\n\n\tRenderTools()->DrawUIRect(&Value, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\tchar aBuf[32];\n\tstr_format(aBuf, sizeof(aBuf), \"%s:\", pLabel);\n\tLabel.y += 2.0f;\n\tUI()->DoLabel(&Label, aBuf, pRect->h*ms_FontmodHeight*0.8f, 0);\n\n\tValue.y += 2.0f;\n\tUI()->DoLabel(&Value, pValue, pRect->h*ms_FontmodHeight*0.8f, 0);\n}\n\nfloat CMenus::DoScrollbarV(const void *pID, const CUIRect *pRect, float Current)\n{\n\tCUIRect Handle;\n\tstatic float OffsetY;\n\tpRect->HSplitTop(33, &Handle, 0);\n\n\tHandle.y += (pRect->h-Handle.h)*Current;\n\n\t// logic\n\tfloat ReturnValue = Current;\n\tint Inside = UI()->MouseInside(&Handle);\n\n\tif(UI()->ActiveItem() == pID)\n\t{\n\t\tif(!UI()->MouseButton(0))\n\t\t\tUI()->SetActiveItem(0);\n\n\t\tfloat Min = pRect->y;\n\t\tfloat Max = pRect->h-Handle.h;\n\t\tfloat Cur = UI()->MouseY()-OffsetY;\n\t\tReturnValue = (Cur-Min)/Max;\n\t\tif(ReturnValue < 0.0f) ReturnValue = 0.0f;\n\t\tif(ReturnValue > 1.0f) ReturnValue = 1.0f;\n\t}\n\telse if(UI()->HotItem() == pID)\n\t{\n\t\tif(UI()->MouseButton(0))\n\t\t{\n\t\t\tUI()->SetActiveItem(pID);\n\t\t\tOffsetY = UI()->MouseY()-Handle.y;\n\t\t}\n\t}\n\n\tif(Inside)\n\t\tUI()->SetHotItem(pID);\n\n\t// render\n\tCUIRect Rail;\n\tpRect->VMargin(5.0f, &Rail);\n\tRenderTools()->DrawUIRect(&Rail, vec4(1.0f, 1.0f, 1.0f, 0.25f), CUI::CORNER_ALL, Rail.w/2.0f);\n\n\tCUIRect Slider = Handle;\n\tSlider.VMargin(5.0f, &Slider);\n\n\tRenderTools()->DrawUIRect(&Slider, vec4(1.0f , 1.0f, 1.0f, 1.0f), CUI::CORNER_ALL, Slider.w/2.0f);\n\n\treturn ReturnValue;\n}\n\nfloat CMenus::DoScrollbarH(const void *pID, const CUIRect *pRect, float Current)\n{\n\tCUIRect Handle;\n\tstatic float OffsetX;\n\tpRect->VSplitLeft(33, &Handle, 0);\n\n\tHandle.x += (pRect->w-Handle.w)*Current;\n\n\t// logic\n\tfloat ReturnValue = Current;\n\tint Inside = UI()->MouseInside(&Handle);\n\n\tif(UI()->ActiveItem() == pID)\n\t{\n\t\tif(!UI()->MouseButton(0))\n\t\t\tUI()->SetActiveItem(0);\n\n\t\tfloat Min = pRect->x;\n\t\tfloat Max = pRect->w-Handle.w;\n\t\tfloat Cur = UI()->MouseX()-OffsetX;\n\t\tReturnValue = (Cur-Min)/Max;\n\t\tif(ReturnValue < 0.0f) ReturnValue = 0.0f;\n\t\tif(ReturnValue > 1.0f) ReturnValue = 1.0f;\n\t}\n\telse if(UI()->HotItem() == pID)\n\t{\n\t\tif(UI()->MouseButton(0))\n\t\t{\n\t\t\tUI()->SetActiveItem(pID);\n\t\t\tOffsetX = UI()->MouseX()-Handle.x;\n\t\t}\n\t}\n\n\tif(Inside)\n\t\tUI()->SetHotItem(pID);\n\n\t// render\n\tCUIRect Rail;\n\tpRect->HMargin(5.0f, &Rail);\n\tRenderTools()->DrawUIRect(&Rail, vec4(1.0f, 1.0f, 1.0f, 0.25f), CUI::CORNER_ALL, Rail.h/2.0f);\n\n\tCUIRect Slider = Handle;\n\tSlider.HMargin(5.0f, &Slider);\n\n\tRenderTools()->DrawUIRect(&Slider, vec4(1.0f , 1.0f, 1.0f, 1.0f), CUI::CORNER_ALL, Slider.h/2.0f);\n\n\treturn ReturnValue;\n}\n\nstatic CUIRect gs_ListBoxOriginalView;\nstatic CUIRect gs_ListBoxView;\nstatic float gs_ListBoxRowHeight;\nstatic int gs_ListBoxItemIndex;\nstatic int gs_ListBoxSelectedIndex;\nstatic int gs_ListBoxNewSelected;\nstatic int gs_ListBoxDoneEvents;\nstatic int gs_ListBoxNumItems;\nstatic int gs_ListBoxItemsPerRow;\nstatic float gs_ListBoxScrollValue;\nstatic bool gs_ListBoxItemActivated;\n\nvoid CMenus::UiDoListboxHeader(const CUIRect *pRect, const char *pTitle, float HeaderHeight, float Spacing)\n{\n\tCUIRect Header;\n\tCUIRect View = *pRect;\n\n\t// background\n\tView.HSplitTop(ms_ListheaderHeight+Spacing, &Header, 0);\n\tRenderTools()->DrawUIRect(&Header, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_T, 5.0f);\n\n\t// draw header\n\tView.HSplitTop(ms_ListheaderHeight, &Header, &View);\n\tHeader.y += 2.0f;\n\tUI()->DoLabel(&Header, pTitle, Header.h*ms_FontmodHeight*0.8f, 0);\n\n\tView.HSplitTop(Spacing, &Header, &View);\n\n\t// setup the variables\n\tgs_ListBoxOriginalView = View;\n}\n\nvoid CMenus::UiDoListboxStart(const void *pID, float RowHeight, const char *pBottomText, int NumItems,\n\t\t\t\t\t\t\t\tint ItemsPerRow, int SelectedIndex, float ScrollValue, const CUIRect *pRect, bool Background)\n{\n\tCUIRect View, Scroll, Row;\n\tif(pRect)\n\t\tView = *pRect;\n\telse\n\t\tView = gs_ListBoxOriginalView;\n\tCUIRect Footer;\n\n\t// background\n\tif(Background)\n\t\tRenderTools()->DrawUIRect(&View, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f);\n\n\t// draw footers\n\tif(pBottomText)\n\t{\n\t\tView.HSplitBottom(ms_ListheaderHeight, &View, &Footer);\n\t\tFooter.VSplitLeft(10.0f, 0, &Footer);\n\t\tFooter.y += 2.0f;\n\t\tUI()->DoLabel(&Footer, pBottomText, Footer.h*ms_FontmodHeight*0.8f, 0);\n\t}\n\n\t// prepare the scroll\n\tView.VSplitRight(20.0f, &View, &Scroll);\n\n\t// scroll background\n\tRenderTools()->DrawUIRect(&Scroll, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\t// list background\n\tRenderTools()->DrawUIRect(&View, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\t// setup the variables\n\tgs_ListBoxOriginalView = View;\n\tgs_ListBoxSelectedIndex = SelectedIndex;\n\tgs_ListBoxNewSelected = SelectedIndex;\n\tgs_ListBoxItemIndex = 0;\n\tgs_ListBoxRowHeight = RowHeight;\n\tgs_ListBoxNumItems = NumItems;\n\tgs_ListBoxItemsPerRow = ItemsPerRow;\n\tgs_ListBoxDoneEvents = 0;\n\tgs_ListBoxScrollValue = ScrollValue;\n\tgs_ListBoxItemActivated = false;\n\n\t// do the scrollbar\n\tView.HSplitTop(gs_ListBoxRowHeight, &Row, 0);\n\n\tint NumViewable = (int)(gs_ListBoxOriginalView.h/Row.h) + 1;\n\tint Num = (NumItems+gs_ListBoxItemsPerRow-1)/gs_ListBoxItemsPerRow-NumViewable+1;\n\tif(Num < 0)\n\t\tNum = 0;\n\tif(Num > 0)\n\t{\n\t\tif(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP) && UI()->MouseInside(&View))\n\t\t\tgs_ListBoxScrollValue -= 3.0f/Num;\n\t\tif(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN) && UI()->MouseInside(&View))\n\t\t\tgs_ListBoxScrollValue += 3.0f/Num;\n\n\t\tif(gs_ListBoxScrollValue < 0.0f) gs_ListBoxScrollValue = 0.0f;\n\t\tif(gs_ListBoxScrollValue > 1.0f) gs_ListBoxScrollValue = 1.0f;\n\t}\n\n\tScroll.HMargin(5.0f, &Scroll);\n\tgs_ListBoxScrollValue = DoScrollbarV(pID, &Scroll, gs_ListBoxScrollValue);\n\n\t// the list\n\tgs_ListBoxView = gs_ListBoxOriginalView;\n\tUI()->ClipEnable(&gs_ListBoxView);\n\tgs_ListBoxView.y -= gs_ListBoxScrollValue*Num*Row.h;\n}\n\nCMenus::CListboxItem CMenus::UiDoListboxNextRow()\n{\n\tstatic CUIRect s_RowView;\n\tCListboxItem Item = {0};\n\tif(gs_ListBoxItemIndex%gs_ListBoxItemsPerRow == 0)\n\t\tgs_ListBoxView.HSplitTop(gs_ListBoxRowHeight /*-2.0f*/, &s_RowView, &gs_ListBoxView);\n\n\ts_RowView.VSplitLeft(s_RowView.w/(gs_ListBoxItemsPerRow-gs_ListBoxItemIndex%gs_ListBoxItemsPerRow)/(UI()->Scale()), &Item.m_Rect, &s_RowView);\n\n\tItem.m_Visible = 1;\n\t//item.rect = row;\n\n\tItem.m_HitRect = Item.m_Rect;\n\n\t//CUIRect select_hit_box = item.rect;\n\n\tif(gs_ListBoxSelectedIndex == gs_ListBoxItemIndex)\n\t\tItem.m_Selected = 1;\n\n\t// make sure that only those in view can be selected\n\tif(Item.m_Rect.y+Item.m_Rect.h > gs_ListBoxOriginalView.y)\n\t{\n\n\t\tif(Item.m_HitRect.y < Item.m_HitRect.y) // clip the selection\n\t\t{\n\t\t\tItem.m_HitRect.h -= gs_ListBoxOriginalView.y-Item.m_HitRect.y;\n\t\t\tItem.m_HitRect.y = gs_ListBoxOriginalView.y;\n\t\t}\n\n\t}\n\telse\n\t\tItem.m_Visible = 0;\n\n\t// check if we need to do more\n\tif(Item.m_Rect.y > gs_ListBoxOriginalView.y+gs_ListBoxOriginalView.h)\n\t\tItem.m_Visible = 0;\n\n\tgs_ListBoxItemIndex++;\n\treturn Item;\n}\n\nCMenus::CListboxItem CMenus::UiDoListboxNextItem(const void *pId, bool Selected)\n{\n\tint ThisItemIndex = gs_ListBoxItemIndex;\n\tif(Selected)\n\t{\n\t\tif(gs_ListBoxSelectedIndex == gs_ListBoxNewSelected)\n\t\t\tgs_ListBoxNewSelected = ThisItemIndex;\n\t\tgs_ListBoxSelectedIndex = ThisItemIndex;\n\t}\n\n\tCListboxItem Item = UiDoListboxNextRow();\n\n\tif(Item.m_Visible && UI()->DoButtonLogic(pId, \"\", gs_ListBoxSelectedIndex == gs_ListBoxItemIndex, &Item.m_HitRect))\n\t\tgs_ListBoxNewSelected = ThisItemIndex;\n\n\t// process input, regard selected index\n\tif(gs_ListBoxSelectedIndex == ThisItemIndex)\n\t{\n\t\tif(!gs_ListBoxDoneEvents)\n\t\t{\n\t\t\tgs_ListBoxDoneEvents = 1;\n\n\t\t\tif(m_EnterPressed || (UI()->ActiveItem() == pId && Input()->MouseDoubleClick()))\n\t\t\t{\n\t\t\t\tgs_ListBoxItemActivated = true;\n\t\t\t\tUI()->SetActiveItem(0);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfor(int i = 0; i < m_NumInputEvents; i++)\n\t\t\t\t{\n\t\t\t\t\tint NewIndex = -1;\n\t\t\t\t\tif(m_aInputEvents[i].m_Flags&IInput::FLAG_PRESS)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(m_aInputEvents[i].m_Key == KEY_DOWN) NewIndex = gs_ListBoxNewSelected + 1;\n\t\t\t\t\t\tif(m_aInputEvents[i].m_Key == KEY_UP) NewIndex = gs_ListBoxNewSelected - 1;\n\t\t\t\t\t}\n\t\t\t\t\tif(NewIndex > -1 && NewIndex < gs_ListBoxNumItems)\n\t\t\t\t\t{\n\t\t\t\t\t\t// scroll\n\t\t\t\t\t\tfloat Offset = (NewIndex/gs_ListBoxItemsPerRow-gs_ListBoxNewSelected/gs_ListBoxItemsPerRow)*gs_ListBoxRowHeight;\n\t\t\t\t\t\tint Scroll = gs_ListBoxOriginalView.y > Item.m_Rect.y+Offset ? -1 :\n\t\t\t\t\t\t\t\t\t\tgs_ListBoxOriginalView.y+gs_ListBoxOriginalView.h < Item.m_Rect.y+Item.m_Rect.h+Offset ? 1 : 0;\n\t\t\t\t\t\tif(Scroll)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint NumViewable = (int)(gs_ListBoxOriginalView.h/gs_ListBoxRowHeight) + 1;\n\t\t\t\t\t\t\tint ScrollNum = (gs_ListBoxNumItems+gs_ListBoxItemsPerRow-1)/gs_ListBoxItemsPerRow-NumViewable+1;\n\t\t\t\t\t\t\tif(Scroll < 0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tint Num = (gs_ListBoxOriginalView.y-Item.m_Rect.y-Offset+gs_ListBoxRowHeight-1.0f)/gs_ListBoxRowHeight;\n\t\t\t\t\t\t\t\tgs_ListBoxScrollValue -= (1.0f/ScrollNum)*Num;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tint Num = (Item.m_Rect.y+Item.m_Rect.h+Offset-(gs_ListBoxOriginalView.y+gs_ListBoxOriginalView.h)+gs_ListBoxRowHeight-1.0f)/\n\t\t\t\t\t\t\t\t\tgs_ListBoxRowHeight;\n\t\t\t\t\t\t\t\tgs_ListBoxScrollValue += (1.0f/ScrollNum)*Num;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(gs_ListBoxScrollValue < 0.0f) gs_ListBoxScrollValue = 0.0f;\n\t\t\t\t\t\t\tif(gs_ListBoxScrollValue > 1.0f) gs_ListBoxScrollValue = 1.0f;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tgs_ListBoxNewSelected = NewIndex;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//selected_index = i;\n\t\tCUIRect r = Item.m_Rect;\n\t\tRenderTools()->DrawUIRect(&r, vec4(1,1,1,0.5f), CUI::CORNER_ALL, 5.0f);\n\t}\n\n\treturn Item;\n}\n\nint CMenus::UiDoListboxEnd(float *pScrollValue, bool *pItemActivated)\n{\n\tUI()->ClipDisable();\n\tif(pScrollValue)\n\t\t*pScrollValue = gs_ListBoxScrollValue;\n\tif(pItemActivated)\n\t\t*pItemActivated = gs_ListBoxItemActivated;\n\treturn gs_ListBoxNewSelected;\n}\n\nint CMenus::DoKeyReader(void *pID, const CUIRect *pRect, int Key)\n{\n\t// process\n\tstatic void *pGrabbedID = 0;\n\tstatic bool MouseReleased = true;\n\tstatic int ButtonUsed = 0;\n\tint Inside = UI()->MouseInside(pRect);\n\tint NewKey = Key;\n\n\tif(!UI()->MouseButton(0) && !UI()->MouseButton(1) && pGrabbedID == pID)\n\t\tMouseReleased = true;\n\n\tif(UI()->ActiveItem() == pID)\n\t{\n\t\tif(m_Binder.m_GotKey)\n\t\t{\n\t\t\t// abort with escape key\n\t\t\tif(m_Binder.m_Key.m_Key != KEY_ESCAPE)\n\t\t\t\tNewKey = m_Binder.m_Key.m_Key;\n\t\t\tm_Binder.m_GotKey = false;\n\t\t\tUI()->SetActiveItem(0);\n\t\t\tMouseReleased = false;\n\t\t\tpGrabbedID = pID;\n\t\t}\n\n\t\tif(ButtonUsed == 1 && !UI()->MouseButton(1))\n\t\t{\n\t\t\tif(Inside)\n\t\t\t\tNewKey = 0;\n\t\t\tUI()->SetActiveItem(0);\n\t\t}\n\t}\n\telse if(UI()->HotItem() == pID)\n\t{\n\t\tif(MouseReleased)\n\t\t{\n\t\t\tif(UI()->MouseButton(0))\n\t\t\t{\n\t\t\t\tm_Binder.m_TakeKey = true;\n\t\t\t\tm_Binder.m_GotKey = false;\n\t\t\t\tUI()->SetActiveItem(pID);\n\t\t\t\tButtonUsed = 0;\n\t\t\t}\n\n\t\t\tif(UI()->MouseButton(1))\n\t\t\t{\n\t\t\t\tUI()->SetActiveItem(pID);\n\t\t\t\tButtonUsed = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\tif(Inside)\n\t\tUI()->SetHotItem(pID);\n\n\t// draw\n\tif (UI()->ActiveItem() == pID && ButtonUsed == 0)\n\t\tDoButton_KeySelect(pID, \"???\", 0, pRect);\n\telse\n\t{\n\t\tif(Key == 0)\n\t\t\tDoButton_KeySelect(pID, \"\", 0, pRect);\n\t\telse\n\t\t\tDoButton_KeySelect(pID, Input()->KeyName(Key), 0, pRect);\n\t}\n\treturn NewKey;\n}\n\nvoid CMenus::RenderMenubar(CUIRect r)\n{\n\tCUIRect Box = r;\n\tCUIRect Button;\n\n\tm_ActivePage = m_MenuPage;\n\tint NewPage = -1;\n\n\tif(Client()->State() != IClient::STATE_OFFLINE)\n\t\tm_ActivePage = m_GamePage;\n\n\tif(m_MenuPage == PAGE_SETTINGS || m_GamePage == PAGE_SETTINGS)\n\t{\n\t\tfloat Spacing = 3.0f;\n\t\tfloat ButtonWidth = (Box.w/6.0f)-(Spacing*5.0)/6.0f;\n\n\t\t// render header background\n\t\tRenderTools()->DrawUIRect4(&Box, vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f);\n\n\t\tBox.HSplitBottom(25.0f, 0, &Box);\n\n\t\tBox.VSplitLeft(ButtonWidth, &Button, &Box);\n\t\tstatic int s_GeneralButton=0;\n\t\tif(DoButton_MenuTabTop(&s_GeneralButton, Localize(\"General\"), g_Config.m_UiSettingsPage==SETTINGS_GENERAL, &Button))\n\t\t{\n\t\t\tg_Config.m_UiSettingsPage = SETTINGS_GENERAL;\n\t\t}\n\n\t\tBox.VSplitLeft(Spacing, 0, &Box); // little space\n\t\tBox.VSplitLeft(ButtonWidth, &Button, &Box);\n\t\tstatic int s_PlayerButton=0;\n\t\tif(DoButton_MenuTabTop(&s_PlayerButton, Localize(\"Player\"), g_Config.m_UiSettingsPage==SETTINGS_PLAYER, &Button))\n\t\t{\n\t\t\tg_Config.m_UiSettingsPage = SETTINGS_PLAYER;\n\t\t}\n\n\t\tBox.VSplitLeft(Spacing, 0, &Box); // little space\n\t\tBox.VSplitLeft(ButtonWidth, &Button, &Box);\n\t\tstatic int s_TeeButton=0;\n\t\tif(DoButton_MenuTabTop(&s_TeeButton, Localize(\"Tee\"), g_Config.m_UiSettingsPage==SETTINGS_TEE, &Button))\n\t\t{\n\t\t\tg_Config.m_UiSettingsPage = SETTINGS_TEE;\n\t\t}\n\n\t\tBox.VSplitLeft(Spacing, 0, &Box); // little space\n\t\tBox.VSplitLeft(ButtonWidth, &Button, &Box);\n\t\tstatic int s_ControlsButton=0;\n\t\tif(DoButton_MenuTabTop(&s_ControlsButton, Localize(\"Controls\"), g_Config.m_UiSettingsPage==SETTINGS_CONTROLS, &Button))\n\t\t{\n\t\t\tg_Config.m_UiSettingsPage = SETTINGS_CONTROLS;\n\t\t}\n\n\t\tBox.VSplitLeft(Spacing, 0, &Box); // little space\n\t\tBox.VSplitLeft(ButtonWidth, &Button, &Box);\n\t\tstatic int s_GraphicsButton=0;\n\t\tif(DoButton_MenuTabTop(&s_GraphicsButton, Localize(\"Graphics\"), g_Config.m_UiSettingsPage==SETTINGS_GRAPHICS, &Button))\n\t\t{\n\t\t\tg_Config.m_UiSettingsPage = SETTINGS_GRAPHICS;\n\t\t}\n\n\t\tBox.VSplitLeft(Spacing, 0, &Box); // little space\n\t\tBox.VSplitLeft(ButtonWidth, &Button, &Box);\n\t\tstatic int s_SoundButton=0;\n\t\tif(DoButton_MenuTabTop(&s_SoundButton, Localize(\"Sound\"), g_Config.m_UiSettingsPage==SETTINGS_SOUND, &Button))\n\t\t{\n\t\t\tg_Config.m_UiSettingsPage = SETTINGS_SOUND;\n\t\t}\n\t}\n\telse if(Client()->State() == IClient::STATE_OFFLINE)\n\t{\n\t\t// render menu tabs\n\t\tif(m_MenuPage >= PAGE_INTERNET && m_MenuPage <= PAGE_FRIENDS)\n\t\t{\n\t\t\tfloat Spacing = 3.0f;\n\t\t\tfloat ButtonWidth = (Box.w/6.0f)-(Spacing*5.0)/6.0f;\n\n\t\t\tCUIRect Left, Right;\n\t\t\tBox.VSplitLeft(ButtonWidth*2.0f+Spacing, &Left, 0);\n\t\t\tBox.VSplitRight(ButtonWidth, 0, &Right);\n\n\t\t\t// render header backgrounds\n\t\t\tRenderTools()->DrawUIRect4(&Left, vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f);\n\t\t\tRenderTools()->DrawUIRect4(&Right, vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f);\n\n\t\t\tLeft.HSplitBottom(25.0f, 0, &Left);\n\t\t\tRight.HSplitBottom(25.0f, 0, &Right);\n\n\t\t\tLeft.VSplitLeft(ButtonWidth, &Button, &Left);\n\t\t\tstatic int s_InternetButton=0;\n\t\t\tif(DoButton_MenuTabTop(&s_InternetButton, Localize(\"Global\"), m_ActivePage==PAGE_INTERNET, &Button))\n\t\t\t{\n\t\t\t\tm_pClient->m_pCamera->ChangePosition(CCamera::POS_INTERNET);\n\t\t\t\tServerBrowser()->Refresh(IServerBrowser::TYPE_INTERNET);\n\t\t\t\tNewPage = PAGE_INTERNET;\n\t\t\t\tg_Config.m_UiBrowserPage = PAGE_INTERNET;\n\t\t\t}\n\n\t\t\tLeft.VSplitLeft(Spacing, 0, &Left); // little space\n\t\t\tLeft.VSplitLeft(ButtonWidth, &Button, &Left);\n\t\t\tstatic int s_LanButton=0;\n\t\t\tif(DoButton_MenuTabTop(&s_LanButton, Localize(\"Local\"), m_ActivePage==PAGE_LAN, &Button))\n\t\t\t{\n\t\t\t\tm_pClient->m_pCamera->ChangePosition(CCamera::POS_LAN);\n\t\t\t\tServerBrowser()->Refresh(IServerBrowser::TYPE_LAN);\n\t\t\t\tNewPage = PAGE_LAN;\n\t\t\t\tg_Config.m_UiBrowserPage = PAGE_LAN;\n\t\t\t}\n\n\t\t\tchar aBuf[32];\n\t\t\tif(m_BorwserPage == PAGE_BROWSER_BROWSER)\n\t\t\t\tstr_copy(aBuf, Localize(\"Friends\"), sizeof(aBuf));\n\t\t\telse if(m_BorwserPage == PAGE_BROWSER_FRIENDS)\n\t\t\t\tstr_copy(aBuf, Localize(\"Browser\"), sizeof(aBuf));\n\t\t\tstatic int s_FilterButton=0;\n\t\t\tif(DoButton_Menu(&s_FilterButton, aBuf, 0, &Right))\n\t\t\t{\n\t\t\t\tm_BorwserPage++;\n\t\t\t\tif(m_BorwserPage >= NUM_PAGE_BROWSER)\n\t\t\t\t\tm_BorwserPage = 0;\n\t\t\t}\n\t\t}\n\t\telse if(m_MenuPage == PAGE_DEMOS)\n\t\t{\n\t\t\t// render header background\n\t\t\tRenderTools()->DrawUIRect4(&Box, vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f);\n\n\t\t\tBox.HSplitBottom(25.0f, 0, &Box);\n\n\t\t\t// make the header look like an active tab\n\t\t\tRenderTools()->DrawUIRect(&Box, vec4(1.0f, 1.0f, 1.0f, 0.75f), CUI::CORNER_ALL, 5.0f);\n\t\t\tBox.HMargin(2.0f, &Box);\n\t\t\tTextRender()->TextColor(0.0f, 0.0f, 0.0f, 1.0f);\n\t\t\tTextRender()->TextOutlineColor(1.0f, 1.0f, 1.0f, 0.25f);\n\t\t\tUI()->DoLabel(&Box, Localize(\"Demo\"), Box.h*ms_FontmodHeight, 0);\n\t\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\tTextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f);\n\t\t}\n\t}\n\telse\n\t{\n\t\tfloat Spacing = 3.0f;\n\t\tfloat ButtonWidth = (Box.w/6.0f)-(Spacing*5.0)/6.0f;\n\n\t\t// render header backgrounds\n\t\tCUIRect Left, Right;\n\t\tBox.VSplitLeft(ButtonWidth*4.0f+Spacing*3.0f, &Left, 0);\n\t\tBox.VSplitRight(ButtonWidth, 0, &Right);\n\t\tRenderTools()->DrawUIRect4(&Left, vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f);\n\t\tRenderTools()->DrawUIRect4(&Right, vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f);\n\n\t\tLeft.HSplitBottom(25.0f, 0, &Left);\n\t\tRight.HSplitBottom(25.0f, 0, &Right);\n\n\t\t// online menus\n\t\tif(m_GamePage != PAGE_SETTINGS) // Game stuff\n\t\t{\n\t\t\tLeft.VSplitLeft(ButtonWidth, &Button, &Left);\n\t\t\tstatic int s_GameButton=0;\n\t\t\tif(DoButton_MenuTabTop(&s_GameButton, Localize(\"Game\"), m_ActivePage==PAGE_GAME, &Button))\n\t\t\t\tNewPage = PAGE_GAME;\n\n\t\t\tLeft.VSplitLeft(Spacing, 0, &Left); // little space\n\t\t\tLeft.VSplitLeft(ButtonWidth, &Button, &Left);\n\t\t\tstatic int s_PlayersButton=0;\n\t\t\tif(DoButton_MenuTabTop(&s_PlayersButton, Localize(\"Players\"), m_ActivePage==PAGE_PLAYERS, &Button))\n\t\t\t\tNewPage = PAGE_PLAYERS;\n\n\t\t\tLeft.VSplitLeft(Spacing, 0, &Left); // little space\n\t\t\tLeft.VSplitLeft(ButtonWidth, &Button, &Left);\n\t\t\tstatic int s_ServerInfoButton=0;\n\t\t\tif(DoButton_MenuTabTop(&s_ServerInfoButton, Localize(\"Server info\"), m_ActivePage==PAGE_SERVER_INFO, &Button))\n\t\t\t\tNewPage = PAGE_SERVER_INFO;\n\n\t\t\tLeft.VSplitLeft(Spacing, 0, &Left); // little space\n\t\t\tLeft.VSplitLeft(ButtonWidth, &Button, &Left);\n\t\t\tstatic int s_CallVoteButton=0;\n\t\t\tif(DoButton_MenuTabTop(&s_CallVoteButton, Localize(\"Call vote\"), m_ActivePage==PAGE_CALLVOTE, &Button))\n\t\t\t\tNewPage = PAGE_CALLVOTE;\n\n\t\t\tstatic int s_SettingsButton=0;\n\t\t\tif(DoButton_MenuTabTop(&s_SettingsButton, Localize(\"Settings\"), 0, &Right))\n\t\t\t\tNewPage = PAGE_SETTINGS;\n\t\t}\n\t}\n\n\tif(NewPage != -1)\n\t{\n\t\tif(Client()->State() == IClient::STATE_OFFLINE)\n\t\t\tm_MenuPage = NewPage;\n\t\telse\n\t\t\tm_GamePage = NewPage;\n\t}\n}\n\nvoid CMenus::RenderLoading()\n{\n\t// TODO: not supported right now due to separate render thread\n\n\tstatic int64 LastLoadRender = 0;\n\tfloat Percent = m_LoadCurrent++/(float)m_LoadTotal;\n\n\t// make sure that we don't render for each little thing we load\n\t// because that will slow down loading if we have vsync\n\tif(time_get()-LastLoadRender < time_freq()/60)\n\t\treturn;\n\n\tLastLoadRender = time_get();\n\n\tCUIRect Screen = *UI()->Screen();\n\tGraphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h);\n\n\tRenderBackground();\n\n\tfloat w = 700;\n\tfloat h = 200;\n\tfloat x = Screen.w/2-w/2;\n\tfloat y = Screen.h/2-h/2;\n\n\tGraphics()->BlendNormal();\n\n\tGraphics()->TextureClear();\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(0,0,0,0.50f);\n\tRenderTools()->DrawRoundRect(x, y, w, h, 40.0f);\n\tGraphics()->QuadsEnd();\n\n\n\tconst char *pCaption = Localize(\"Loading\");\n\n\tCUIRect r;\n\tr.x = x;\n\tr.y = y+20;\n\tr.w = w;\n\tr.h = h;\n\tUI()->DoLabel(&r, pCaption, 48.0f, 0, -1);\n\n\tGraphics()->TextureClear();\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(1,1,1,0.75f);\n\tRenderTools()->DrawRoundRect(x+40, y+h-75, (w-80)*Percent, 25, 5.0f);\n\tGraphics()->QuadsEnd();\n\n\tGraphics()->Swap();\n}\n\nvoid CMenus::RenderNews(CUIRect MainView)\n{\n\tRenderTools()->DrawUIRect(&MainView, vec4(1.0f, 1.0f, 1.0f, 0.25f), CUI::CORNER_ALL, 10.0f);\n}\n\nvoid CMenus::RenderBackButton(CUIRect MainView)\n{\n\t// same size like tabs in top but variables not really needed\n\tfloat Spacing = 3.0f;\n\tfloat ButtonWidth = (MainView.w/6.0f)-(Spacing*5.0)/6.0f;\n\n\t// render background\n\tMainView.HSplitBottom(60.0f, 0, &MainView);\n\tMainView.VSplitLeft(ButtonWidth, &MainView, 0);\n\tRenderTools()->DrawUIRect4(&MainView, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f);\n\n\t// back to main menu\n\tCUIRect Button;\n\tMainView.HSplitTop(25.0f, &MainView, 0);\n\tButton = MainView;\n\tstatic int s_MenuButton=0;\n\tif(DoButton_Menu(&s_MenuButton, Localize(\"Back\"), 0, &Button) || m_EscapePressed)\n\t{\n\t\tif(Client()->State() != IClient::STATE_OFFLINE)\n\t\t\tm_GamePage = PAGE_GAME;\n\t\telse\n\t\t\tm_MenuPage = PAGE_START;\n\t}\n}\n\nint CMenus::MenuImageScan(const char *pName, int IsDir, int DirType, void *pUser)\n{\n\tCMenus *pSelf = (CMenus *)pUser;\n\tint l = str_length(pName);\n\tif(l < 4 || IsDir || str_comp(pName+l-4, \".png\") != 0)\n\t\treturn 0;\n\n\tchar aBuf[512];\n\tstr_format(aBuf, sizeof(aBuf), \"menuimages/%s\", pName);\n\tCImageInfo Info;\n\tif(!pSelf->Graphics()->LoadPNG(&Info, aBuf, DirType))\n\t{\n\t\tstr_format(aBuf, sizeof(aBuf), \"failed to load menu image from %s\", pName);\n\t\tpSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"game\", aBuf);\n\t\treturn 0;\n\t}\n\n\tCMenuImage MenuImage;\n\tMenuImage.m_OrgTexture = pSelf->Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0);\n\n\tunsigned char *d = (unsigned char *)Info.m_pData;\n\t//int Pitch = Info.m_Width*4;\n\n\t// create colorless version\n\tint Step = Info.m_Format == CImageInfo::FORMAT_RGBA ? 4 : 3;\n\n\t// make the texture gray scale\n\tfor(int i = 0; i < Info.m_Width*Info.m_Height; i++)\n\t{\n\t\tint v = (d[i*Step]+d[i*Step+1]+d[i*Step+2])/3;\n\t\td[i*Step] = v;\n\t\td[i*Step+1] = v;\n\t\td[i*Step+2] = v;\n\t}\n\n\t/* same grey like sinks\n\tint Freq[256] = {0};\n\tint OrgWeight = 0;\n\tint NewWeight = 192;\n\n\t// find most common frequence\n\tfor(int y = 0; y < Info.m_Height; y++)\n\t\tfor(int x = 0; x < Info.m_Width; x++)\n\t\t{\n\t\t\tif(d[y*Pitch+x*4+3] > 128)\n\t\t\t\tFreq[d[y*Pitch+x*4]]++;\n\t\t}\n\n\tfor(int i = 1; i < 256; i++)\n\t{\n\t\tif(Freq[OrgWeight] < Freq[i])\n\t\t\tOrgWeight = i;\n\t}\n\n\t// reorder\n\tint InvOrgWeight = 255-OrgWeight;\n\tint InvNewWeight = 255-NewWeight;\n\tfor(int y = 0; y < Info.m_Height; y++)\n\t\tfor(int x = 0; x < Info.m_Width; x++)\n\t\t{\n\t\t\tint v = d[y*Pitch+x*4];\n\t\t\tif(v <= OrgWeight)\n\t\t\t\tv = (int)(((v/(float)OrgWeight) * NewWeight));\n\t\t\telse\n\t\t\t\tv = (int)(((v-OrgWeight)/(float)InvOrgWeight)*InvNewWeight + NewWeight);\n\t\t\td[y*Pitch+x*4] = v;\n\t\t\td[y*Pitch+x*4+1] = v;\n\t\t\td[y*Pitch+x*4+2] = v;\n\t\t}\n\t*/\n\n\tMenuImage.m_GreyTexture = pSelf->Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0);\n\tmem_free(Info.m_pData);\n\n\t// set menu image data\n\tstr_copy(MenuImage.m_aName, pName, min((int)sizeof(MenuImage.m_aName),l-3));\n\tstr_format(aBuf, sizeof(aBuf), \"load menu image %s\", MenuImage.m_aName);\n\tpSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"game\", aBuf);\n\tpSelf->m_lMenuImages.add(MenuImage);\n\n\treturn 0;\n}\n\nconst CMenus::CMenuImage *CMenus::FindMenuImage(const char *pName)\n{\n\tfor(int i = 0; i < m_lMenuImages.size(); i++)\n\t{\n\t\tif(str_comp(m_lMenuImages[i].m_aName, pName) == 0)\n\t\t\treturn &m_lMenuImages[i];\n\t}\n\treturn 0;\n}\n\nvoid CMenus::UpdateVideoFormats()\n{\n\tm_NumVideoFormats = 0;\n\tfor(int i = 0; i < m_NumModes; i++)\n\t{\n\t\tint G = gcd(m_aModes[i].m_Width, m_aModes[i].m_Height);\n\t\tint Width = m_aModes[i].m_Width/G;\n\t\tint Height = m_aModes[i].m_Height/G;\n\n\t\t// check if we already have the format\n\t\tbool Found = false;\n\t\tfor(int j = 0; j < m_NumVideoFormats; j++)\n\t\t{\n\t\t\tif(Width == m_aVideoFormats[j].m_WidthValue && Height == m_aVideoFormats[j].m_HeightValue)\n\t\t\t{\n\t\t\t\tFound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(!Found)\n\t\t{\n\t\t\tm_aVideoFormats[m_NumVideoFormats].m_WidthValue = Width;\n\t\t\tm_aVideoFormats[m_NumVideoFormats].m_HeightValue = Height;\n\t\t\tm_NumVideoFormats++;\n\n\t\t\t// sort the array\n\t\t\tfor(int k = 0; k < m_NumVideoFormats-1; k++) // ffs, bubblesort\n\t\t\t{\n\t\t\t\tfor(int j = 0; j < m_NumVideoFormats-k-1; j++)\n\t\t\t\t{\n\t\t\t\t\tif((float)m_aVideoFormats[j].m_WidthValue/(float)m_aVideoFormats[j].m_HeightValue > (float)m_aVideoFormats[j+1].m_WidthValue/(float)m_aVideoFormats[j+1].m_HeightValue)\n\t\t\t\t\t{\n\t\t\t\t\t\tCVideoFormat Tmp = m_aVideoFormats[j];\n\t\t\t\t\t\tm_aVideoFormats[j] = m_aVideoFormats[j+1];\n\t\t\t\t\t\tm_aVideoFormats[j+1] = Tmp;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid CMenus::UpdatedFilteredVideoModes()\n{\n\tm_lFilteredVideoModes.clear();\n\tfor(int i = 0; i < m_NumModes; i++)\n\t{\n\t\tint G = gcd(m_aModes[i].m_Width, m_aModes[i].m_Height);\n\t\tif(m_aVideoFormats[m_CurrentVideoFormat].m_WidthValue == m_aModes[i].m_Width/G && m_aVideoFormats[m_CurrentVideoFormat].m_HeightValue == m_aModes[i].m_Height/G)\n\t\t\tm_lFilteredVideoModes.add(m_aModes[i]);\n\t}\n}\n\nvoid CMenus::OnInit()\n{\n\tm_NumModes = Graphics()->GetVideoModes(m_aModes, MAX_RESOLUTIONS);\n\tUpdateVideoFormats();\n\n\tbool Found = false;\n\tfor(int i = 0; i < m_NumVideoFormats; i++)\n\t{\n\t\tint G = gcd(g_Config.m_GfxScreenWidth, g_Config.m_GfxScreenHeight);\n\t\tif(m_aVideoFormats[i].m_WidthValue == g_Config.m_GfxScreenWidth/G && m_aVideoFormats[i].m_HeightValue == g_Config.m_GfxScreenHeight/G)\n\t\t{\n\t\t\tm_CurrentVideoFormat = i;\n\t\t\tFound = true;\n\t\t\tbreak;\n\t\t}\n\n\t}\n\n\tif(!Found)\n\t\tm_CurrentVideoFormat = 0;\n\n\tUpdatedFilteredVideoModes();\n\n\t// load menu images\n\tm_lMenuImages.clear();\n\tStorage()->ListDirectory(IStorage::TYPE_ALL, \"menuimages\", MenuImageScan, this);\n\n\t/*\n\tarray<string> my_strings;\n\tarray<string>::range r2;\n\tmy_strings.add(\"4\");\n\tmy_strings.add(\"6\");\n\tmy_strings.add(\"1\");\n\tmy_strings.add(\"3\");\n\tmy_strings.add(\"7\");\n\tmy_strings.add(\"5\");\n\tmy_strings.add(\"2\");\n\n\tfor(array<string>::range r = my_strings.all(); !r.empty(); r.pop_front())\n\t\tdbg_msg(\"\", \"%s\", r.front().cstr());\n\n\tsort(my_strings.all());\n\n\tdbg_msg(\"\", \"after:\");\n\tfor(array<string>::range r = my_strings.all(); !r.empty(); r.pop_front())\n\t\tdbg_msg(\"\", \"%s\", r.front().cstr());\n\n\n\tarray<int> myarray;\n\tmyarray.add(4);\n\tmyarray.add(6);\n\tmyarray.add(1);\n\tmyarray.add(3);\n\tmyarray.add(7);\n\tmyarray.add(5);\n\tmyarray.add(2);\n\n\tfor(array<int>::range r = myarray.all(); !r.empty(); r.pop_front())\n\t\tdbg_msg(\"\", \"%d\", r.front());\n\n\tsort(myarray.all());\n\tsort_verify(myarray.all());\n\n\tdbg_msg(\"\", \"after:\");\n\tfor(array<int>::range r = myarray.all(); !r.empty(); r.pop_front())\n\t\tdbg_msg(\"\", \"%d\", r.front());\n\n\texit(-1);\n\t// */\n\n\t// clear filter lists\n\t//m_lFilters.clear();\n\n\tif(g_Config.m_ClShowWelcome)\n\t\tm_Popup = POPUP_LANGUAGE;\n\tg_Config.m_ClShowWelcome = 0;\n\n\tConsole()->Chain(\"add_favorite\", ConchainServerbrowserUpdate, this);\n\tConsole()->Chain(\"remove_favorite\", ConchainServerbrowserUpdate, this);\n\tConsole()->Chain(\"add_friend\", ConchainFriendlistUpdate, this);\n\tConsole()->Chain(\"remove_friend\", ConchainFriendlistUpdate, this);\n\n\tm_TextureBlob = Graphics()->LoadTexture(\"blob.png\", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0);\n\n\t// setup load amount\n\tm_LoadCurrent = 0;\n\tm_LoadTotal = g_pData->m_NumImages;\n\tif(!g_Config.m_ClThreadsoundloading)\n\t\tm_LoadTotal += g_pData->m_NumSounds;\n}\n\nvoid CMenus::PopupMessage(const char *pTopic, const char *pBody, const char *pButton, int Next)\n{\n\t// reset active item\n\tUI()->SetActiveItem(0);\n\n\tstr_copy(m_aMessageTopic, pTopic, sizeof(m_aMessageTopic));\n\tstr_copy(m_aMessageBody, pBody, sizeof(m_aMessageBody));\n\tstr_copy(m_aMessageButton, pButton, sizeof(m_aMessageButton));\n\tm_Popup = POPUP_MESSAGE;\n\tm_NextPopup = Next;\n}\n\n\nint CMenus::Render()\n{\n\tCUIRect Screen = *UI()->Screen();\n\tGraphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h);\n\n\tstatic bool s_First = true;\n\tif(s_First)\n\t{\n\t\t// refresh server browser before we are in browser menu to save time\n\t\tm_pClient->m_pCamera->ChangePosition(CCamera::POS_START);\n\t\tif(g_Config.m_UiBrowserPage == PAGE_LAN)\n\t\t\tServerBrowser()->Refresh(IServerBrowser::TYPE_LAN);\n\t\telse\n\t\t\tServerBrowser()->Refresh(IServerBrowser::TYPE_INTERNET);\n\n\t\tm_pClient->m_pSounds->Enqueue(CSounds::CHN_MUSIC, SOUND_MENU);\n\t\ts_First = false;\n\t}\n\n\t// render background only if needed\n\tif(Client()->State() != IClient::STATE_ONLINE && !m_pClient->m_pMapLayersBackGround->MenuMapLoaded())\n\t\tRenderBackground();\n\n\tCUIRect TabBar, MainView;\n\n\t// some margin around the screen\n\t//Screen.Margin(10.0f, &Screen);\n\n\tstatic bool s_SoundCheck = false;\n\tif(!s_SoundCheck && m_Popup == POPUP_NONE)\n\t{\n\t\tif(Client()->SoundInitFailed())\n\t\t\tm_Popup = POPUP_SOUNDERROR;\n\t\ts_SoundCheck = true;\n\t}\n\n\tif(m_Popup == POPUP_NONE)\n\t{\n\t\tif(m_MenuPage == PAGE_START && Client()->State() == IClient::STATE_OFFLINE)\n\t\t{\n\t\t\tRenderStartMenu(Screen);\n\t\t\tRenderLogo(Screen);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// do tab bar\n\t\t\tScreen.VMargin(Screen.w/2-365.0f, &MainView);\n\t\t\tMainView.HSplitTop(60.0f, &TabBar, &MainView);\n\t\t\tRenderMenubar(TabBar);\n\n\t\t\t// news is not implemented yet\n\t\t\t/*if(m_MenuPage <= PAGE_NEWS || m_MenuPage > PAGE_SETTINGS || (Client()->State() == IClient::STATE_OFFLINE && m_MenuPage >= PAGE_GAME && m_MenuPage <= PAGE_CALLVOTE))\n\t\t\t{\n\t\t\t\tServerBrowser()->Refresh(IServerBrowser::TYPE_INTERNET);\n\t\t\t\tm_MenuPage = PAGE_INTERNET;\n\t\t\t}*/\n\n\t\t\t// render current page\n\t\t\tif(Client()->State() != IClient::STATE_OFFLINE)\n\t\t\t{\n\t\t\t\tif(m_GamePage == PAGE_GAME)\n\t\t\t\t\tRenderGame(MainView);\n\t\t\t\telse if(m_GamePage == PAGE_PLAYERS)\n\t\t\t\t\tRenderPlayers(MainView);\n\t\t\t\telse if(m_GamePage == PAGE_SERVER_INFO)\n\t\t\t\t\tRenderServerInfo(MainView);\n\t\t\t\telse if(m_GamePage == PAGE_CALLVOTE)\n\t\t\t\t\tRenderServerControl(MainView);\n\t\t\t\telse if(m_GamePage == PAGE_SETTINGS)\n\t\t\t\t\tRenderSettings(MainView);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(m_MenuPage == PAGE_NEWS)\n\t\t\t\t\tRenderNews(MainView);\n\t\t\t\telse if(m_MenuPage == PAGE_INTERNET)\n\t\t\t\t\tRenderServerbrowser(MainView);\n\t\t\t\telse if(m_MenuPage == PAGE_LAN)\n\t\t\t\t\tRenderServerbrowser(MainView);\n\t\t\t\telse if(m_MenuPage == PAGE_DEMOS)\n\t\t\t\t\tRenderDemoList(MainView);\n\t\t\t\telse if(m_MenuPage == PAGE_FRIENDS)\n\t\t\t\t\tRenderServerbrowser(MainView);\n\t\t\t\telse if(m_MenuPage == PAGE_SETTINGS)\n\t\t\t\t\tRenderSettings(MainView);\n\t\t\t}\n\t\t}\n\n\t\t// do overlay popups\n\t\tDoPopupMenu();\n\t}\n\telse\n\t{\n\t\t// make sure that other windows doesn't do anything funnay!\n\t\t//UI()->SetHotItem(0);\n\t\t//UI()->SetActiveItem(0);\n\t\tconst char *pTitle = \"\";\n\t\tconst char *pExtraText = \"\";\n\t\tconst char *pButtonText = \"\";\n\t\tint ExtraAlign = 0;\n\t\tint NumOptions = 4;\n\n\t\tif(m_Popup == POPUP_MESSAGE)\n\t\t{\n\t\t\tpTitle = m_aMessageTopic;\n\t\t\tpExtraText = m_aMessageBody;\n\t\t\tpButtonText = m_aMessageButton;\n\t\t}\n\t\telse if(m_Popup == POPUP_CONNECTING)\n\t\t{\n\t\t\tpTitle = Localize(\"Connecting to\");\n\t\t\tpButtonText = Localize(\"Abort\");\n\t\t\tif(Client()->MapDownloadTotalsize() > 0)\n\t\t\t{\n\t\t\t\tpTitle = Localize(\"Downloading map\");\n\t\t\t\tpExtraText = \"\";\n\t\t\t\tNumOptions = 5;\n\t\t\t}\n\t\t}\n\t\telse if(m_Popup == POPUP_LANGUAGE)\n\t\t{\n\t\t\tpTitle = Localize(\"Language\");\n\t\t\tpButtonText = Localize(\"Ok\");\n\t\t\tNumOptions = 7;\n\t\t}\n\t\telse if(m_Popup == POPUP_COUNTRY)\n\t\t{\n\t\t\tpTitle = Localize(\"Country\");\n\t\t\tpButtonText = Localize(\"Ok\");\n\t\t\tNumOptions = 8;\n\t\t}\n\t\telse if(m_Popup == POPUP_DISCONNECTED)\n\t\t{\n\t\t\tpTitle = Localize(\"Disconnected\");\n\t\t\tpExtraText = Client()->ErrorString();\n\t\t\tpButtonText = Localize(\"Ok\");\n\t\t}\n\t\telse if(m_Popup == POPUP_PURE)\n\t\t{\n\t\t\tpTitle = Localize(\"Disconnected\");\n\t\t\tpExtraText = Localize(\"The server is running a non-standard tuning on a pure game type.\");\n\t\t\tpButtonText = Localize(\"Ok\");\n\t\t\tExtraAlign = -1;\n\t\t}\n\t\telse if(m_Popup == POPUP_DELETE_DEMO)\n\t\t{\n\t\t\tpTitle = Localize(\"Delete demo\");\n\t\t\tpExtraText = Localize(\"Are you sure that you want to delete the demo?\");\n\t\t}\n\t\telse if(m_Popup == POPUP_RENAME_DEMO)\n\t\t{\n\t\t\tpTitle = Localize(\"Rename demo\");\n\t\t\tpExtraText = Localize(\"Are you sure you want to rename the demo?\");\n\t\t\tNumOptions = 6;\n\t\t}\n\t\telse if(m_Popup == POPUP_REMOVE_FRIEND)\n\t\t{\n\t\t\tpTitle = Localize(\"Remove friend\");\n\t\t\tpExtraText = Localize(\"Are you sure that you want to remove the player from your friends list?\");\n\t\t}\n\t\telse if(m_Popup == POPUP_SAVE_SKIN)\n\t\t{\n\t\t\tpTitle = Localize(\"Save skin\");\n\t\t\tpExtraText = Localize(\"Are you sure you want to save your skin? If a skin with this name already exists, it will be replaced.\");\n\t\t\tNumOptions = 6;\n\t\t\tExtraAlign = -1;\n\t\t}\n\t\telse if(m_Popup == POPUP_DELETE_SKIN)\n\t\t{\n\t\t\tpTitle = Localize(\"Delete skin\");\n\t\t\tpExtraText = Localize(\"Are you sure that you want to delete the skin?\");\n\t\t}\n\t\telse if(m_Popup == POPUP_SOUNDERROR)\n\t\t{\n\t\t\tpTitle = Localize(\"Sound error\");\n\t\t\tpExtraText = Localize(\"The audio device couldn't be initialised.\");\n\t\t\tpButtonText = Localize(\"Ok\");\n\t\t\tExtraAlign = -1;\n\t\t}\n\t\telse if(m_Popup == POPUP_PASSWORD)\n\t\t{\n\t\t\tpTitle = Localize(\"Password incorrect\");\n\t\t\tpExtraText = \"Please enter the password.\";\n\t\t}\n\t\telse if(m_Popup == POPUP_QUIT)\n\t\t{\n\t\t\tpTitle = Localize(\"Quit\");\n\t\t\tpExtraText = Localize(\"Are you sure that you want to quit?\");\n\t\t}\n\t\telse if(m_Popup == POPUP_FIRST_LAUNCH)\n\t\t{\n\t\t\tpTitle = Localize(\"Welcome to Teeworlds\");\n\t\t\tpExtraText = Localize(\"As this is the first time you launch the game, please enter your nick name below. It's recommended that you check the settings to adjust them to your liking before joining a server.\");\n\t\t\tpButtonText = Localize(\"Enter\");\n\t\t\tNumOptions = 6;\n\t\t\tExtraAlign = -1;\n\t\t}\n\n\t\tCUIRect Box, Part, BottomBar;\n\t\tfloat ButtonHeight = 20.0f;\n\t\tfloat ButtonHeightBig = ButtonHeight+5.0f;\n\t\tfloat SpacingH = 2.0f;\n\t\tfloat SpacingW = 3.0f;\n\t\tBox = Screen;\n\t\tBox.VMargin(Box.w/2.0f-(365.0f), &Box);\n\t\tfloat ButtonWidth = (Box.w/6.0f)-(SpacingW*5.0)/6.0f;\n\t\tBox.VMargin(ButtonWidth+SpacingW, &Box);\n\t\tBox.HMargin(Box.h/2.0f-((int)(NumOptions+1)*ButtonHeight+(int)(NumOptions)*SpacingH)/2.0f-10.0f, &Box);\n\n\t\t// render the box\n\t\tRenderTools()->DrawUIRect(&Box, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\t\t// headline\n\t\tBox.HSplitTop(ButtonHeightBig, &Part, &Box);\n\t\tPart.y += 3.0f;\n\t\tUI()->DoLabel(&Part, pTitle, Part.h*ms_FontmodHeight*0.8f, 0);\n\n\t\t// inner box\n\t\tBox.HSplitTop(SpacingH, 0, &Box);\n\t\tBox.HSplitBottom(ButtonHeight+5.0f+SpacingH, &Box, &BottomBar);\n\t\tBottomBar.HSplitTop(SpacingH, 0, &BottomBar);\n\t\tRenderTools()->DrawUIRect(&Box, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\t\tif(m_Popup == POPUP_QUIT)\n\t\t{\n\t\t\tCUIRect Yes, No;\n\n\t\t\t// additional info\n\t\t\tif(m_pClient->Editor()->HasUnsavedData())\n\t\t\t{\n\t\t\t\tBox.HSplitTop(12.0f, 0, &Part);\n\t\t\t\tUI()->DoLabel(&Part, pExtraText, ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign);\n\t\t\t\tPart.HSplitTop(12.0f, 0, &Part);\n\t\t\t\tUI()->DoLabel(&Part, Localize(\"There's an unsaved map in the editor, you might want to save it before you quit the game.\"), ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tBox.HSplitTop(27.0f, 0, &Box);\n\t\t\t\tUI()->DoLabel(&Box, pExtraText, ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign);\n\t\t\t}\n\n\t\t\t// buttons\n\t\t\tBottomBar.VSplitMid(&No, &Yes);\n\t\t\tNo.VSplitRight(SpacingW/2.0f, &No, 0);\n\t\t\tYes.VSplitLeft(SpacingW/2.0f, 0, &Yes);\n\n\t\t\tstatic int s_ButtonAbort = 0;\n\t\t\tif(DoButton_Menu(&s_ButtonAbort, Localize(\"No\"), 0, &No) || m_EscapePressed)\n\t\t\t\tm_Popup = POPUP_NONE;\n\n\t\t\tstatic int s_ButtonTryAgain = 0;\n\t\t\tif(DoButton_Menu(&s_ButtonTryAgain, Localize(\"Yes\"), 0, &Yes) || m_EnterPressed)\n\t\t\t\tClient()->Quit();\n\t\t}\n\t\telse if(m_Popup == POPUP_PASSWORD)\n\t\t{\n\t\t\tCUIRect EditBox, TryAgain, Abort;\n\n\t\t\tBox.HSplitTop(12.0f, 0, &Box);\n\t\t\tUI()->DoLabel(&Box, pExtraText, ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign);\n\n\t\t\tBox.HSplitBottom(ButtonHeight*1.7f, 0, &Box);\n\t\t\tBox.HSplitTop(20.0f, &EditBox, &Box);\n\n\t\t\tstatic float s_OffsetPassword = 0.0f;\n\t\t\tDoEditBoxOption(g_Config.m_Password, g_Config.m_Password, sizeof(g_Config.m_Password), &EditBox, Localize(\"Password\"), ButtonWidth, &s_OffsetPassword, true);\n\n\t\t\t// buttons\n\t\t\tBottomBar.VSplitMid(&Abort, &TryAgain);\n\t\t\tAbort.VSplitRight(SpacingW/2.0f, &Abort, 0);\n\t\t\tTryAgain.VSplitLeft(SpacingW/2.0f, 0, &TryAgain);\n\n\t\t\tstatic int s_ButtonAbort = 0;\n\t\t\tif(DoButton_Menu(&s_ButtonAbort, Localize(\"Abort\"), 0, &Abort) || m_EscapePressed)\n\t\t\t\tm_Popup = POPUP_NONE;\n\n\t\t\tstatic int s_ButtonTryAgain = 0;\n\t\t\tif(DoButton_Menu(&s_ButtonTryAgain, Localize(\"Try again\"), 0, &TryAgain) || m_EnterPressed)\n\t\t\t{\n\t\t\t\tClient()->Connect(g_Config.m_UiServerAddress);\n\t\t\t}\n\t\t}\n\t\telse if(m_Popup == POPUP_CONNECTING)\n\t\t{\n\t\t\tstatic int s_Button = 0;\n\t\t\tif(DoButton_Menu(&s_Button, pButtonText, 0, &BottomBar) || m_EscapePressed || m_EnterPressed)\n\t\t\t{\n\t\t\t\tClient()->Disconnect();\n\t\t\t\tm_Popup = POPUP_NONE;\n\t\t\t}\n\n\t\t\tif(Client()->MapDownloadTotalsize() > 0)\n\t\t\t{\n\t\t\t\tchar aBuf[128];\n\t\t\t\tint64 Now = time_get();\n\t\t\t\tif(Now-m_DownloadLastCheckTime >= time_freq())\n\t\t\t\t{\n\t\t\t\t\tif(m_DownloadLastCheckSize > Client()->MapDownloadAmount())\n\t\t\t\t\t{\n\t\t\t\t\t\t// map downloaded restarted\n\t\t\t\t\t\tm_DownloadLastCheckSize = 0;\n\t\t\t\t\t}\n\n\t\t\t\t\t// update download speed\n\t\t\t\t\tfloat Diff = (Client()->MapDownloadAmount()-m_DownloadLastCheckSize)/((int)((Now-m_DownloadLastCheckTime)/time_freq()));\n\t\t\t\t\tfloat StartDiff = m_DownloadLastCheckSize-0.0f;\n\t\t\t\t\tif(StartDiff+Diff > 0.0f)\n\t\t\t\t\t\tm_DownloadSpeed = (Diff/(StartDiff+Diff))*(Diff/1.0f) + (StartDiff/(Diff+StartDiff))*m_DownloadSpeed;\n\t\t\t\t\telse\n\t\t\t\t\t\tm_DownloadSpeed = 0.0f;\n\t\t\t\t\tm_DownloadLastCheckTime = Now;\n\t\t\t\t\tm_DownloadLastCheckSize = Client()->MapDownloadAmount();\n\t\t\t\t}\n\n\t\t\t\tBox.HSplitTop(15.f, 0, &Box);\n\t\t\t\tBox.HSplitTop(ButtonHeight, &Part, &Box);\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"%d/%d KiB (%.1f KiB/s)\", Client()->MapDownloadAmount()/1024, Client()->MapDownloadTotalsize()/1024,\tm_DownloadSpeed/1024.0f);\n\t\t\t\tUI()->DoLabel(&Part, aBuf, ButtonHeight*ms_FontmodHeight*0.8f, 0, -1);\n\n\t\t\t\t// time left\n\t\t\t\tconst char *pTimeLeftString;\n\t\t\t\tint TimeLeft = max(1, m_DownloadSpeed > 0.0f ? static_cast<int>((Client()->MapDownloadTotalsize()-Client()->MapDownloadAmount())/m_DownloadSpeed) : 1);\n\t\t\t\tif(TimeLeft >= 60)\n\t\t\t\t{\n\t\t\t\t\tTimeLeft /= 60;\n\t\t\t\t\tpTimeLeftString = TimeLeft == 1 ? Localize(\"%i minute left\") : Localize(\"%i minutes left\");\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tpTimeLeftString = TimeLeft == 1 ? Localize(\"%i second left\") : Localize(\"%i seconds left\");\n\t\t\t\tBox.HSplitTop(SpacingH, 0, &Box);\n\t\t\t\tBox.HSplitTop(ButtonHeight, &Part, &Box);\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), pTimeLeftString, TimeLeft);\n\t\t\t\tUI()->DoLabel(&Part, aBuf, ButtonHeight*ms_FontmodHeight*0.8f, 0, -1);\n\n\t\t\t\t// progress bar\n\t\t\t\tBox.HSplitTop(SpacingH, 0, &Box);\n\t\t\t\tBox.HSplitTop(ButtonHeight, &Part, &Box);\n\t\t\t\tPart.VMargin(40.0f, &Part);\n\t\t\t\tRenderTools()->DrawUIRect(&Part, vec4(1.0f, 1.0f, 1.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\t\t\t\tPart.w = max(10.0f, (Part.w*Client()->MapDownloadAmount())/Client()->MapDownloadTotalsize());\n\t\t\t\tRenderTools()->DrawUIRect(&Part, vec4(1.0f, 1.0f, 1.0f, 0.5f), CUI::CORNER_ALL, 5.0f);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tBox.HSplitTop(27.0f, 0, &Box);\n\t\t\t\tUI()->DoLabel(&Box, g_Config.m_UiServerAddress, ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign);\n\t\t\t}\n\t\t}\n\t\telse if(m_Popup == POPUP_LANGUAGE)\n\t\t{\n\t\t\tRenderLanguageSelection(Box, false);\n\n\t\t\tstatic int s_Button = 0;\n\t\t\tif(DoButton_Menu(&s_Button, pButtonText, 0, &BottomBar) || m_EscapePressed || m_EnterPressed)\n\t\t\t\tm_Popup = POPUP_FIRST_LAUNCH;\n\t\t}\n\t\telse if(m_Popup == POPUP_COUNTRY)\n\t\t{\n\t\t\t// selected filter\n\t\t\tCBrowserFilter *pFilter = &m_lFilters[m_SelectedFilter];\n\t\t\tint SortHash = 0;\n\t\t\tint Ping = 0;\n\t\t\tint Country = 0;\n\t\t\tchar aGametype[32];\n\t\t\tchar aServerAddress[16];\n\t\t\tpFilter->GetFilter(&SortHash, &Ping, &Country, aGametype, aServerAddress);\n\n\t\t\tstatic int ActSelection = -2;\n\t\t\tif(ActSelection == -2)\n\t\t\t\tActSelection = Country;\n\t\t\tstatic float s_ScrollValue = 0.0f;\n\t\t\tint OldSelected = -1;\n\t\t\tUiDoListboxStart(&s_ScrollValue, 40.0f, 0, m_pClient->m_pCountryFlags->Num(), 12, OldSelected, s_ScrollValue, &Box, false);\n\n\t\t\tfor(int i = 0; i < m_pClient->m_pCountryFlags->Num(); ++i)\n\t\t\t{\n\t\t\t\tconst CCountryFlags::CCountryFlag *pEntry = m_pClient->m_pCountryFlags->GetByIndex(i);\n\t\t\t\tif(pEntry->m_CountryCode == ActSelection)\n\t\t\t\t\tOldSelected = i;\n\n\t\t\t\tCListboxItem Item = UiDoListboxNextItem(&pEntry->m_CountryCode, OldSelected == i);\n\t\t\t\tif(Item.m_Visible)\n\t\t\t\t{\n\t\t\t\t\tCUIRect Label;\n\t\t\t\t\tItem.m_Rect.Margin(5.0f, &Item.m_Rect);\n\t\t\t\t\tItem.m_Rect.HSplitBottom(10.0f, &Item.m_Rect, &Label);\n\t\t\t\t\tfloat OldWidth = Item.m_Rect.w;\n\t\t\t\t\tItem.m_Rect.w = Item.m_Rect.h*2;\n\t\t\t\t\tItem.m_Rect.x += (OldWidth-Item.m_Rect.w)/ 2.0f;\n\t\t\t\t\tGraphics()->TextureSet(pEntry->m_Texture);\n\t\t\t\t\tGraphics()->QuadsBegin();\n\t\t\t\t\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\t\t\tIGraphics::CQuadItem QuadItem(Item.m_Rect.x, Item.m_Rect.y, Item.m_Rect.w, Item.m_Rect.h);\n\t\t\t\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t\t\t\t\tGraphics()->QuadsEnd();\n\t\t\t\t\tif(i == OldSelected)\n\t\t\t\t\t{\n\t\t\t\t\t\tTextRender()->TextColor(0.0f, 0.0f, 0.0f, 1.0f);\n\t\t\t\t\t\tTextRender()->TextOutlineColor(1.0f, 1.0f, 1.0f, 0.25f);\n\t\t\t\t\t\tUI()->DoLabel(&Label, pEntry->m_aCountryCodeString, 10.0f, 0);\n\t\t\t\t\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\t\t\t\tTextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tUI()->DoLabel(&Label, pEntry->m_aCountryCodeString, 10.0f, 0);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst int NewSelected = UiDoListboxEnd(&s_ScrollValue, 0);\n\t\t\tif(OldSelected != NewSelected)\n\t\t\t\tActSelection = m_pClient->m_pCountryFlags->GetByIndex(NewSelected)->m_CountryCode;\n\n\t\t\tPart.VMargin(120.0f, &Part);\n\n\t\t\tstatic int s_Button = 0;\n\t\t\tif(DoButton_Menu(&s_Button, pButtonText, 0, &BottomBar) || m_EnterPressed)\n\t\t\t{\n\t\t\t\tpFilter->SetFilter(SortHash, Ping, ActSelection, aGametype, aServerAddress);\n\t\t\t\tg_Config.m_BrFilterCountryIndex = ActSelection;\n\t\t\t\tm_Popup = POPUP_NONE;\n\t\t\t}\n\n\t\t\tif(m_EscapePressed)\n\t\t\t{\n\t\t\t\tActSelection = Country;\n\t\t\t\tm_Popup = POPUP_NONE;\n\t\t\t}\n\t\t}\n\t\telse if(m_Popup == POPUP_DELETE_DEMO)\n\t\t{\n\t\t\tCUIRect Yes, No;\n\t\t\tBox.HSplitTop(27.0f, 0, &Box);\n\t\t\tUI()->DoLabel(&Box, pExtraText, ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign);\n\n\t\t\t// buttons\n\t\t\tBottomBar.VSplitMid(&No, &Yes);\n\t\t\tNo.VSplitRight(SpacingW/2.0f, &No, 0);\n\t\t\tYes.VSplitLeft(SpacingW/2.0f, 0, &Yes);\n\n\t\t\tstatic int s_ButtonNo = 0;\n\t\t\tif(DoButton_Menu(&s_ButtonNo, Localize(\"No\"), 0, &No) || m_EscapePressed)\n\t\t\t\tm_Popup = POPUP_NONE;\n\n\t\t\tstatic int s_ButtonYes = 0;\n\t\t\tif(DoButton_Menu(&s_ButtonYes, Localize(\"Yes\"), 0, &Yes) || m_EnterPressed)\n\t\t\t{\n\t\t\t\tm_Popup = POPUP_NONE;\n\t\t\t\t// delete demo\n\t\t\t\tif(m_DemolistSelectedIndex >= 0 && !m_DemolistSelectedIsDir)\n\t\t\t\t{\n\t\t\t\t\tchar aBuf[512];\n\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"%s/%s\", m_aCurrentDemoFolder, m_lDemos[m_DemolistSelectedIndex].m_aFilename);\n\t\t\t\t\tif(Storage()->RemoveFile(aBuf, m_lDemos[m_DemolistSelectedIndex].m_StorageType))\n\t\t\t\t\t{\n\t\t\t\t\t\tDemolistPopulate();\n\t\t\t\t\t\tDemolistOnUpdate(false);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tPopupMessage(Localize(\"Error\"), Localize(\"Unable to delete the demo\"), Localize(\"Ok\"));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if(m_Popup == POPUP_RENAME_DEMO)\n\t\t{\n\t\t\tCUIRect Yes, No, EditBox;\n\n\t\t\tBox.HSplitTop(27.0f, 0, &Box);\n\t\t\tUI()->DoLabel(&Box, pExtraText, ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign);\n\n\t\t\tBox.HSplitBottom(Box.h/2.0f, 0, &Box);\n\t\t\tBox.HSplitTop(20.0f, &EditBox, &Box);\n\n\t\t\tstatic float s_OffsetRenameDemo = 0.0f;\n\t\t\tDoEditBoxOption(m_aCurrentDemoFile, m_aCurrentDemoFile, sizeof(m_aCurrentDemoFile), &EditBox, Localize(\"Name\"), ButtonWidth, &s_OffsetRenameDemo);\n\n\t\t\t// buttons\n\t\t\tBottomBar.VSplitMid(&No, &Yes);\n\t\t\tNo.VSplitRight(SpacingW/2.0f, &No, 0);\n\t\t\tYes.VSplitLeft(SpacingW/2.0f, 0, &Yes);\n\n\t\t\tstatic int s_ButtonNo = 0;\n\t\t\tif(DoButton_Menu(&s_ButtonNo, Localize(\"No\"), 0, &No) || m_EscapePressed)\n\t\t\t\tm_Popup = POPUP_NONE;\n\n\t\t\tstatic int s_ButtonYes = 0;\n\t\t\tif(DoButton_Menu(&s_ButtonYes, Localize(\"Yes\"), !m_aCurrentDemoFile[0], &Yes) || m_EnterPressed)\n\t\t\t{\n\t\t\t\tif(m_aCurrentDemoFile[0])\n\t\t\t\t{\n\t\t\t\t\tm_Popup = POPUP_NONE;\n\t\t\t\t\t// rename demo\n\t\t\t\t\tif(m_DemolistSelectedIndex >= 0 && !m_DemolistSelectedIsDir)\n\t\t\t\t\t{\n\t\t\t\t\t\tchar aBufOld[512];\n\t\t\t\t\t\tstr_format(aBufOld, sizeof(aBufOld), \"%s/%s\", m_aCurrentDemoFolder, m_lDemos[m_DemolistSelectedIndex].m_aFilename);\n\t\t\t\t\t\tint Length = str_length(m_aCurrentDemoFile);\n\t\t\t\t\t\tchar aBufNew[512];\n\t\t\t\t\t\tif(Length <= 4 || m_aCurrentDemoFile[Length-5] != '.' || str_comp_nocase(m_aCurrentDemoFile+Length-4, \"demo\"))\n\t\t\t\t\t\t\tstr_format(aBufNew, sizeof(aBufNew), \"%s/%s.demo\", m_aCurrentDemoFolder, m_aCurrentDemoFile);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tstr_format(aBufNew, sizeof(aBufNew), \"%s/%s\", m_aCurrentDemoFolder, m_aCurrentDemoFile);\n\t\t\t\t\t\tif(Storage()->RenameFile(aBufOld, aBufNew, m_lDemos[m_DemolistSelectedIndex].m_StorageType))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tDemolistPopulate();\n\t\t\t\t\t\t\tDemolistOnUpdate(false);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tPopupMessage(Localize(\"Error\"), Localize(\"Unable to rename the demo\"), Localize(\"Ok\"), POPUP_RENAME_DEMO);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if(m_Popup == POPUP_REMOVE_FRIEND)\n\t\t{\n\t\t\tCUIRect Yes, No;\n\t\t\tBox.HSplitTop(27.0f, 0, &Box);\n\t\t\tUI()->DoLabel(&Box, pExtraText, ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign);\n\n\t\t\t// buttons\n\t\t\tBottomBar.VSplitMid(&No, &Yes);\n\t\t\tNo.VSplitRight(SpacingW/2.0f, &No, 0);\n\t\t\tYes.VSplitLeft(SpacingW/2.0f, 0, &Yes);\n\n\t\t\tstatic int s_ButtonNo = 0;\n\t\t\tif(DoButton_Menu(&s_ButtonNo, Localize(\"No\"), 0, &No) || m_EscapePressed)\n\t\t\t\tm_Popup = POPUP_NONE;\n\n\t\t\tstatic int s_ButtonYes = 0;\n\t\t\tif(DoButton_Menu(&s_ButtonYes, Localize(\"Yes\"), 0, &Yes) || m_EnterPressed)\n\t\t\t{\n\t\t\t\tm_Popup = POPUP_NONE;\n\t\t\t\t// remove friend\n\t\t\t\tif(m_FriendlistSelectedIndex >= 0)\n\t\t\t\t{\n\t\t\t\t\tm_pClient->Friends()->RemoveFriend(m_lFriends[m_FriendlistSelectedIndex].m_pFriendInfo->m_aName,\n\t\t\t\t\t\tm_lFriends[m_FriendlistSelectedIndex].m_pFriendInfo->m_aClan);\n\t\t\t\t\tFriendlistOnUpdate();\n\t\t\t\t\tClient()->ServerBrowserUpdate();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if(m_Popup == POPUP_SAVE_SKIN)\n\t\t{\n\t\t\tCUIRect Yes, No, EditBox;\n\n\t\t\tBox.HSplitTop(24.0f, 0, &Box);\n\t\t\tBox.VMargin(10.0f, &Part);\n\t\t\tUI()->DoLabel(&Part, pExtraText, ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign, Box.w-20.0f);\n\n\t\t\tBox.HSplitBottom(Box.h/2.0f, 0, &Box);\n\t\t\tBox.HSplitTop(20.0f, &EditBox, &Box);\n\n\t\t\tstatic float s_OffsetSaveSkin = 0.0f;\n\t\t\tDoEditBoxOption(m_aSaveSkinName, m_aSaveSkinName, sizeof(m_aSaveSkinName), &EditBox, Localize(\"Name\"), ButtonWidth, &s_OffsetSaveSkin);\n\n\t\t\t// buttons\n\t\t\tBottomBar.VSplitMid(&No, &Yes);\n\t\t\tNo.VSplitRight(SpacingW/2.0f, &No, 0);\n\t\t\tYes.VSplitLeft(SpacingW/2.0f, 0, &Yes);\n\n\t\t\tstatic int s_ButtonAbort = 0;\n\t\t\tif(DoButton_Menu(&s_ButtonAbort, Localize(\"No\"), 0, &No) || m_EscapePressed)\n\t\t\t\tm_Popup = POPUP_NONE;\n\n\t\t\tstatic int s_ButtonTryAgain = 0;\n\t\t\tif(DoButton_Menu(&s_ButtonTryAgain, Localize(\"Yes\"), !m_aSaveSkinName[0], &Yes) || m_EnterPressed)\n\t\t\t{\n\t\t\t\tif(m_aSaveSkinName[0])\n\t\t\t\t{\n\t\t\t\t\tm_Popup = POPUP_NONE;\n\t\t\t\t\tSaveSkinfile();\n\t\t\t\t\tm_aSaveSkinName[0] = 0;\n\t\t\t\t\tm_RefreshSkinSelector = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if(m_Popup == POPUP_DELETE_SKIN)\n\t\t{\n\t\t\tCUIRect Yes, No;\n\t\t\tBox.HSplitTop(27.0f, 0, &Box);\n\t\t\tUI()->DoLabel(&Box, pExtraText, ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign);\n\n\t\t\t// buttons\n\t\t\tBottomBar.VSplitMid(&No, &Yes);\n\t\t\tNo.VSplitRight(SpacingW/2.0f, &No, 0);\n\t\t\tYes.VSplitLeft(SpacingW/2.0f, 0, &Yes);\n\n\t\t\tstatic int s_ButtonNo = 0;\n\t\t\tif(DoButton_Menu(&s_ButtonNo, Localize(\"No\"), 0, &No) || m_EscapePressed)\n\t\t\t\tm_Popup = POPUP_NONE;\n\n\t\t\tstatic int s_ButtonYes = 0;\n\t\t\tif(DoButton_Menu(&s_ButtonYes, Localize(\"Yes\"), 0, &Yes) || m_EnterPressed)\n\t\t\t{\n\t\t\t\tm_Popup = POPUP_NONE;\n\t\t\t\t// delete demo\n\t\t\t\tif(m_pSelectedSkin)\n\t\t\t\t{\n\t\t\t\t\tchar aBuf[512];\n\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"skins/%s.json\", m_pSelectedSkin->m_aName);\n\t\t\t\t\tif(Storage()->RemoveFile(aBuf, IStorage::TYPE_SAVE))\n\t\t\t\t\t{\n\t\t\t\t\t\tm_pClient->m_pSkins->RemoveSkin(m_pSelectedSkin);\n\t\t\t\t\t\tm_RefreshSkinSelector = true;\n\t\t\t\t\t\tm_pSelectedSkin = 0;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tPopupMessage(Localize(\"Error\"), Localize(\"Unable to delete the skin\"), Localize(\"Ok\"));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if(m_Popup == POPUP_FIRST_LAUNCH)\n\t\t{\n\t\t\tCUIRect EditBox;\n\n\t\t\tBox.HSplitTop(20.0f, 0, &Box);\n\t\t\tBox.VMargin(10.0f, &Part);\n\t\t\tUI()->DoLabel(&Part, pExtraText, ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign, Box.w-20.0f);\n\n\t\t\tBox.HSplitBottom(ButtonHeight*2.0f, 0, &Box);\n\t\t\tBox.HSplitTop(ButtonHeight, &EditBox, &Box);\n\n\t\t\tstatic float s_OffsetName = 0.0f;\n\t\t\tDoEditBoxOption(g_Config.m_PlayerName, g_Config.m_PlayerName, sizeof(g_Config.m_PlayerName), &EditBox, Localize(\"Nickname\"), ButtonWidth, &s_OffsetName);\n\n\t\t\t// button\n\t\t\tstatic int s_EnterButton = 0;\n\t\t\tif(DoButton_Menu(&s_EnterButton, pButtonText, 0, &BottomBar) || m_EnterPressed)\n\t\t\t{\n\t\t\t\tif(g_Config.m_PlayerName[0])\n\t\t\t\t\tm_Popup = POPUP_NONE;\n\t\t\t\telse\n\t\t\t\t\tPopupMessage(Localize(\"Error\"), Localize(\"Nickname is empty.\"), Localize(\"Ok\"), POPUP_FIRST_LAUNCH);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tBox.HSplitTop(27.0f, 0, &Box);\n\t\t\tBox.VMargin(10.0f, &Part);\n\t\t\tUI()->DoLabel(&Part, pExtraText, ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign, -1);\n\n\t\t\t// button\n\t\t\tstatic int s_Button = 0;\n\t\t\tif(DoButton_Menu(&s_Button, pButtonText, 0, &BottomBar) || m_EscapePressed || m_EnterPressed)\n\t\t\t\tm_Popup = m_NextPopup;\n\t\t}\n\n\t\tif(m_Popup == POPUP_NONE)\n\t\t\tUI()->SetActiveItem(0);\n\t}\n\n\treturn 0;\n}\n\n\nvoid CMenus::SetActive(bool Active)\n{\n\tm_MenuActive = Active;\n\tif(!m_MenuActive)\n\t{\n\t\tif(Client()->State() == IClient::STATE_ONLINE)\n\t\t{\n\t\t\tm_pClient->OnRelease();\n\t\t}\n\t}\n\telse if(Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tm_pClient->OnRelease();\n\t}\n}\n\nvoid CMenus::OnReset()\n{\n}\n\nbool CMenus::OnMouseMove(float x, float y)\n{\n\tm_LastInput = time_get();\n\n\tif(!m_MenuActive)\n\t\treturn false;\n\n\t// prev mouse position\n\tm_PrevMousePos = m_MousePos;\n\n\tUI()->ConvertMouseMove(&x, &y);\n\tm_MousePos.x += x;\n\tm_MousePos.y += y;\n\tif(m_MousePos.x < 0) m_MousePos.x = 0;\n\tif(m_MousePos.y < 0) m_MousePos.y = 0;\n\tif(m_MousePos.x > Graphics()->ScreenWidth()) m_MousePos.x = Graphics()->ScreenWidth();\n\tif(m_MousePos.y > Graphics()->ScreenHeight()) m_MousePos.y = Graphics()->ScreenHeight();\n\n\treturn true;\n}\n\nbool CMenus::OnInput(IInput::CEvent e)\n{\n\tm_LastInput = time_get();\n\n\t// special handle esc and enter for popup purposes\n\tif(e.m_Flags&IInput::FLAG_PRESS)\n\t{\n\t\tif(e.m_Key == KEY_ESCAPE)\n\t\t{\n\t\t\tm_EscapePressed = true;\n\t\t\tSetActive(!IsActive());\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tif(IsActive())\n\t{\n\t\tif(e.m_Flags&IInput::FLAG_PRESS)\n\t\t{\n\t\t\t// special for popups\n\t\t\tif(e.m_Key == KEY_RETURN || e.m_Key == KEY_KP_ENTER)\n\t\t\t\tm_EnterPressed = true;\n\t\t\telse if(e.m_Key == KEY_DELETE)\n\t\t\t\tm_DeletePressed = true;\n\t\t}\n\n\t\tif(m_NumInputEvents < MAX_INPUTEVENTS)\n\t\t\tm_aInputEvents[m_NumInputEvents++] = e;\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid CMenus::OnConsoleInit()\n{\n\t// add filters\n\tm_lFilters.add(CBrowserFilter(CBrowserFilter::FILTER_ALL, Localize(\"All\"), ServerBrowser(), IServerBrowser::FILTER_PING, 999, -1, \"\", \"\"));\n\tm_lFilters.add(CBrowserFilter(CBrowserFilter::FILTER_STANDARD, Localize(\"Standard Gametype\"), ServerBrowser(), IServerBrowser::FILTER_COMPAT_VERSION|IServerBrowser::FILTER_PURE|IServerBrowser::FILTER_PURE_MAP|IServerBrowser::FILTER_PING, 999, -1, \"\", \"\"));\n\tm_lFilters.add(CBrowserFilter(CBrowserFilter::FILTER_FAVORITES, Localize(\"Favorites\"), ServerBrowser(), IServerBrowser::FILTER_FAVORITE|IServerBrowser::FILTER_PING, 999, -1, \"\", \"\"));\n}\n\nvoid CMenus::OnStateChange(int NewState, int OldState)\n{\n\t// reset active item\n\tUI()->SetActiveItem(0);\n\n\tif(NewState == IClient::STATE_OFFLINE)\n\t{\n\t\tif(OldState >= IClient::STATE_ONLINE && NewState < IClient::STATE_QUITING)\n\t\t\tm_pClient->m_pSounds->Play(CSounds::CHN_MUSIC, SOUND_MENU, 1.0f);\n\t\tm_Popup = POPUP_NONE;\n\t\tif(Client()->ErrorString() && Client()->ErrorString()[0] != 0)\n\t\t{\n\t\t\tif(str_find(Client()->ErrorString(), \"password\"))\n\t\t\t{\n\t\t\t\tm_Popup = POPUP_PASSWORD;\n\t\t\t\tUI()->SetHotItem(&g_Config.m_Password);\n\t\t\t\tUI()->SetActiveItem(&g_Config.m_Password);\n\t\t\t}\n\t\t\telse\n\t\t\t\tm_Popup = POPUP_DISCONNECTED;\n\t\t}\n\t}\n\telse if(NewState == IClient::STATE_LOADING)\n\t{\n\t\tm_Popup = POPUP_CONNECTING;\n\t\tm_DownloadLastCheckTime = time_get();\n\t\tm_DownloadLastCheckSize = 0;\n\t\tm_DownloadSpeed = 0.0f;\n\t\t//client_serverinfo_request();\n\t}\n\telse if(NewState == IClient::STATE_CONNECTING)\n\t\tm_Popup = POPUP_CONNECTING;\n\telse if (NewState == IClient::STATE_ONLINE || NewState == IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tm_Popup = POPUP_NONE;\n\t\tSetActive(false);\n\t}\n}\n\nextern \"C\" void font_debug_render();\n\nvoid CMenus::OnRender()\n{\n\t/*\n\t// text rendering test stuff\n\trender_background();\n\n\tCTextCursor cursor;\n\tTextRender()->SetCursor(&cursor, 10, 10, 20, TEXTFLAG_RENDER);\n\tTextRender()->TextEx(&cursor, \"ようこそ - ガイド\", -1);\n\n\tTextRender()->SetCursor(&cursor, 10, 30, 15, TEXTFLAG_RENDER);\n\tTextRender()->TextEx(&cursor, \"ようこそ - ガイド\", -1);\n\n\t//Graphics()->TextureSet(-1);\n\tGraphics()->QuadsBegin();\n\tGraphics()->QuadsDrawTL(60, 60, 5000, 5000);\n\tGraphics()->QuadsEnd();\n\treturn;*/\n\n\tif(Client()->State() != IClient::STATE_ONLINE && Client()->State() != IClient::STATE_DEMOPLAYBACK)\n\t\tSetActive(true);\n\n\tif(Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tCUIRect Screen = *UI()->Screen();\n\t\tGraphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h);\n\t\tRenderDemoPlayer(Screen);\n\t}\n\n\tif(Client()->State() == IClient::STATE_ONLINE && m_pClient->m_ServerMode == m_pClient->SERVERMODE_PUREMOD)\n\t{\n\t\tClient()->Disconnect();\n\t\tSetActive(true);\n\t\tm_Popup = POPUP_PURE;\n\t}\n\n\tif(!IsActive())\n\t{\n\t\tm_EscapePressed = false;\n\t\tm_EnterPressed = false;\n\t\tm_DeletePressed = false;\n\t\tm_NumInputEvents = 0;\n\t\treturn;\n\t}\n\n\t// update the ui\n\tCUIRect *pScreen = UI()->Screen();\n\tfloat mx = (m_MousePos.x/(float)Graphics()->ScreenWidth())*pScreen->w;\n\tfloat my = (m_MousePos.y/(float)Graphics()->ScreenHeight())*pScreen->h;\n\n\tint Buttons = 0;\n\tif(m_UseMouseButtons)\n\t{\n\t\tif(Input()->KeyPressed(KEY_MOUSE_1)) Buttons |= 1;\n\t\tif(Input()->KeyPressed(KEY_MOUSE_2)) Buttons |= 2;\n\t\tif(Input()->KeyPressed(KEY_MOUSE_3)) Buttons |= 4;\n\t}\n\n\tUI()->Update(mx,my,mx*3.0f,my*3.0f,Buttons);\n\n\t// render\n\tif(Client()->State() != IClient::STATE_DEMOPLAYBACK)\n\t\tRender();\n\n\t// render cursor\n\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_CURSOR].m_Id);\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(1,1,1,1);\n\tIGraphics::CQuadItem QuadItem(mx, my, 24, 24);\n\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n\n\t// render debug information\n\tif(g_Config.m_Debug)\n\t{\n\t\tCUIRect Screen = *UI()->Screen();\n\t\tGraphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h);\n\n\t\tchar aBuf[512];\n\t\tstr_format(aBuf, sizeof(aBuf), \"%p %p %p\", UI()->HotItem(), UI()->ActiveItem(), UI()->LastActiveItem());\n\t\tCTextCursor Cursor;\n\t\tTextRender()->SetCursor(&Cursor, 10, 10, 10, TEXTFLAG_RENDER);\n\t\tTextRender()->TextEx(&Cursor, aBuf, -1);\n\t}\n\n\tm_EscapePressed = false;\n\tm_EnterPressed = false;\n\tm_DeletePressed = false;\n\tm_NumInputEvents = 0;\n}\n\nvoid CMenus::RenderBackground()\n{\n\t//Graphics()->Clear(1,1,1);\n\t//render_sunrays(0,0);\n\n\tfloat sw = 300*Graphics()->ScreenAspect();\n\tfloat sh = 300;\n\tGraphics()->MapScreen(0, 0, sw, sh);\n\n\t// render background color\n\tGraphics()->TextureClear();\n\tGraphics()->QuadsBegin();\n\t\t//vec4 bottom(gui_color.r*0.3f, gui_color.g*0.3f, gui_color.b*0.3f, 1.0f);\n\t\t//vec4 bottom(0, 0, 0, 1.0f);\n\t\tvec4 Bottom(0.45f, 0.45f, 0.45f, 1.0f);\n\t\tvec4 Top(0.45f, 0.45f, 0.45f, 1.0f);\n\t\tIGraphics::CColorVertex Array[4] = {\n\t\t\tIGraphics::CColorVertex(0, Top.r, Top.g, Top.b, Top.a),\n\t\t\tIGraphics::CColorVertex(1, Top.r, Top.g, Top.b, Top.a),\n\t\t\tIGraphics::CColorVertex(2, Bottom.r, Bottom.g, Bottom.b, Bottom.a),\n\t\t\tIGraphics::CColorVertex(3, Bottom.r, Bottom.g, Bottom.b, Bottom.a)};\n\t\tGraphics()->SetColorVertex(Array, 4);\n\t\tIGraphics::CQuadItem QuadItem(0, 0, sw, sh);\n\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n\n\t// render the tiles\n\tGraphics()->TextureClear();\n\tGraphics()->QuadsBegin();\n\t\tfloat Size = 15.0f;\n\t\tfloat OffsetTime = fmod(Client()->LocalTime()*0.15f, 2.0f);\n\t\tfor(int y = -2; y < (int)(sw/Size); y++)\n\t\t\tfor(int x = -2; x < (int)(sh/Size); x++)\n\t\t\t{\n\t\t\t\tGraphics()->SetColor(0,0,0,0.045f);\n\t\t\t\tIGraphics::CQuadItem QuadItem((x-OffsetTime)*Size*2+(y&1)*Size, (y+OffsetTime)*Size, Size, Size);\n\t\t\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t\t\t}\n\tGraphics()->QuadsEnd();\n\n\t// render border fade\n\tGraphics()->TextureSet(m_TextureBlob);\n\tGraphics()->QuadsBegin();\n\t\tGraphics()->SetColor(0,0,0,0.5f);\n\t\tQuadItem = IGraphics::CQuadItem(-100, -100, sw+200, sh+200);\n\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n\n\t// restore screen\n\t{CUIRect Screen = *UI()->Screen();\n\tGraphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h);}\n}\n"
  },
  {
    "path": "src/game/client/components/menus.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_MENUS_H\n#define GAME_CLIENT_COMPONENTS_MENUS_H\n\n#include <base/vmath.h>\n#include <base/tl/sorted_array.h>\n\n#include <engine/graphics.h>\n#include <engine/demo.h>\n#include <engine/friends.h>\n\n#include <game/voting.h>\n#include <game/client/component.h>\n#include <game/client/localization.h>\n#include <game/client/ui.h>\n\n#include \"skins.h\"\n\n\n// compnent to fetch keypresses, override all other input\nclass CMenusKeyBinder : public CComponent\n{\npublic:\n\tbool m_TakeKey;\n\tbool m_GotKey;\n\tIInput::CEvent m_Key;\n\tCMenusKeyBinder();\n\tvirtual bool OnInput(IInput::CEvent Event);\n};\n\nclass CMenus : public CComponent\n{\n\ttypedef float (*FDropdownCallback)(CUIRect View, void *pUser);\n\n\tfloat *ButtonFade(const void *pID, float Seconds, int Checked=0);\n\n\n\tint DoButton_DemoPlayer(const void *pID, const char *pText, const CUIRect *pRect);\n\tint DoButton_SpriteID(const void *pID, int ImageID, int SpriteID, const CUIRect *pRect, int Corners=CUI::CORNER_ALL, float r=5.0f, bool Fade=true);\n\tint DoButton_SpriteClean(int ImageID, int SpriteID, const CUIRect *pRect);\n\tint DoButton_SpriteCleanID(const void *pID, int ImageID, int SpriteID, const CUIRect *pRect, bool Blend=true);\n\tint DoButton_Toggle(const void *pID, int Checked, const CUIRect *pRect, bool Active);\n\tint DoButton_Menu(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Corners=CUI::CORNER_ALL, float r=5.0f, float FontFactor=0.0f, vec4 ColorHot=vec4(1.0f, 1.0f, 1.0f, 0.75f), bool TextFade=true);\n\tint DoButton_MenuImage(const void *pID, const char *pText, int Checked, const CUIRect *pRect, const char *pImageName, float r=5.0f, float FontFactor=0.0f);\n\tint DoButton_MenuTab(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Corners);\n\tint DoButton_MenuTabTop(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Corners=CUI::CORNER_ALL, float r=5.0f, float FontFactor=0.0f);\n\tint DoButton_Customize(const void *pID, IGraphics::CTextureHandle Texture, int SpriteID, const CUIRect *pRect, float ImageRatio);\n\n\tint DoButton_CheckBox_Common(const void *pID, const char *pText, const char *pBoxText, const CUIRect *pRect, bool Checked=false);\n\tint DoButton_CheckBox(const void *pID, const char *pText, int Checked, const CUIRect *pRect);\n\tint DoButton_CheckBox_Number(const void *pID, const char *pText, int Checked, const CUIRect *pRect);\n\n\tint DoButton_MouseOver(int ImageID, int SpriteID, const CUIRect *pRect);\n\n\t/*static void ui_draw_menu_button(const void *id, const char *text, int checked, const CUIRect *r, const void *extra);\n\tstatic void ui_draw_keyselect_button(const void *id, const char *text, int checked, const CUIRect *r, const void *extra);\n\tstatic void ui_draw_menu_tab_button(const void *id, const char *text, int checked, const CUIRect *r, const void *extra);\n\tstatic void ui_draw_settings_tab_button(const void *id, const char *text, int checked, const CUIRect *r, const void *extra);\n\t*/\n\n\tint DoIcon(int ImageId, int SpriteId, const CUIRect *pRect);\n\tint DoButton_GridHeader(const void *pID, const char *pText, int Checked, const CUIRect *pRect);\n\tint DoButton_GridHeaderIcon(const void *pID, int ImageID, int SpriteID, const CUIRect *pRect, int Corners);\n\n\t//static void ui_draw_browse_icon(int what, const CUIRect *r);\n\t//static void ui_draw_grid_header(const void *id, const char *text, int checked, const CUIRect *r, const void *extra);\n\n\t/*static void ui_draw_checkbox_common(const void *id, const char *text, const char *boxtext, const CUIRect *r, const void *extra);\n\tstatic void ui_draw_checkbox(const void *id, const char *text, int checked, const CUIRect *r, const void *extra);\n\tstatic void ui_draw_checkbox_number(const void *id, const char *text, int checked, const CUIRect *r, const void *extra);\n\t*/\n\tint DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned StrSize, float FontSize, float *pOffset, bool Hidden=false, int Corners=CUI::CORNER_ALL);\n\tvoid DoEditBoxOption(void *pID, char *pOption, int OptionLength, const CUIRect *pRect, const char *pStr, float VSplitVal, float *pOffset, bool Hidden=false);\n\tvoid DoScrollbarOption(void *pID, int *pOption, const CUIRect *pRect, const char *pStr, float VSplitVal, int Min, int Max, bool infinite=false);\n\tfloat DoDropdownMenu(void *pID, const CUIRect *pRect, const char *pStr, float HeaderHeight, FDropdownCallback pfnCallback);\n\tvoid DoInfoBox(const CUIRect *pRect, const char *pLable, const char *pValue);\n\t//static int ui_do_edit_box(void *id, const CUIRect *rect, char *str, unsigned str_size, float font_size, bool hidden=false);\n\n\tfloat DoScrollbarV(const void *pID, const CUIRect *pRect, float Current);\n\tfloat DoScrollbarH(const void *pID, const CUIRect *pRect, float Current);\n\tvoid DoButton_KeySelect(const void *pID, const char *pText, int Checked, const CUIRect *pRect);\n\tint DoKeyReader(void *pID, const CUIRect *pRect, int Key);\n\n\t//static int ui_do_key_reader(void *id, const CUIRect *rect, int key);\n\tvoid UiDoGetButtons(int Start, int Stop, CUIRect View, float ButtonHeight, float Spacing);\n\n\tstruct CListboxItem\n\t{\n\t\tint m_Visible;\n\t\tint m_Selected;\n\t\tCUIRect m_Rect;\n\t\tCUIRect m_HitRect;\n\t};\n\n\tvoid UiDoListboxHeader(const CUIRect *pRect, const char *pTitle, float HeaderHeight, float Spacing);\n\tvoid UiDoListboxStart(const void *pID, float RowHeight, const char *pBottomText, int NumItems,\n\t\t\t\t\t\tint ItemsPerRow, int SelectedIndex, float ScrollValue, const CUIRect *pRect=0, bool Background=true);\n\tCListboxItem UiDoListboxNextItem(const void *pID, bool Selected = false);\n\tCListboxItem UiDoListboxNextRow();\n\tint UiDoListboxEnd(float *pScrollValue, bool *pItemActivated);\n\n\t//static void demolist_listdir_callback(const char *name, int is_dir, void *user);\n\t//static void demolist_list_callback(const CUIRect *rect, int index, void *user);\n\n\tenum\n\t{\n\t\tPOPUP_NONE=0,\n\t\tPOPUP_FIRST_LAUNCH,\n\t\tPOPUP_CONNECTING,\n\t\tPOPUP_MESSAGE,\n\t\tPOPUP_DISCONNECTED,\n\t\tPOPUP_PURE,\n\t\tPOPUP_LANGUAGE,\n\t\tPOPUP_COUNTRY,\n\t\tPOPUP_DELETE_DEMO,\n\t\tPOPUP_RENAME_DEMO,\n\t\tPOPUP_REMOVE_FRIEND,\n\t\tPOPUP_SAVE_SKIN,\n\t\tPOPUP_DELETE_SKIN,\n\t\tPOPUP_SOUNDERROR,\n\t\tPOPUP_PASSWORD,\n\t\tPOPUP_QUIT,\n\t};\n\n\tenum\n\t{\n\t\tPAGE_NEWS=0,\n\t\tPAGE_GAME,\n\t\tPAGE_PLAYERS,\n\t\tPAGE_SERVER_INFO,\n\t\tPAGE_CALLVOTE,\n\t\tPAGE_INTERNET,\n\t\tPAGE_LAN,\n\t\tPAGE_FRIENDS,\n\t\tPAGE_DEMOS,\n\t\tPAGE_SETTINGS,\n\t\tPAGE_SYSTEM,\n\t\tPAGE_START,\n\n\t\tPAGE_BROWSER_BROWSER=0,\n\t\tPAGE_BROWSER_FRIENDS,\n\t\tNUM_PAGE_BROWSER,\n\n\t\tSETTINGS_GENERAL=0,\n\t\tSETTINGS_PLAYER,\n\t\tSETTINGS_TEE,\n\t\tSETTINGS_CONTROLS,\n\t\tSETTINGS_GRAPHICS,\n\t\tSETTINGS_SOUND,\n\t};\n\n\tint m_GamePage;\n\tint m_Popup;\n\tint m_ActivePage;\n\tint m_MenuPage;\n\tint m_BorwserPage;\n\tbool m_MenuActive;\n\tbool m_UseMouseButtons;\n\tvec2 m_MousePos;\n\tvec2 m_PrevMousePos;\n\tbool m_InfoMode;\n\n\t// images\n\tstruct CMenuImage\n\t{\n\t\tchar m_aName[64];\n\t\tIGraphics::CTextureHandle m_OrgTexture;\n\t\tIGraphics::CTextureHandle m_GreyTexture;\n\t};\n\tarray<CMenuImage> m_lMenuImages;\n\n\tstatic int MenuImageScan(const char *pName, int IsDir, int DirType, void *pUser);\n\n\tconst CMenuImage *FindMenuImage(const char* pName);\n\n\tint64 m_LastInput;\n\n\t// loading\n\tint m_LoadCurrent;\n\tint m_LoadTotal;\n\n\t//\n\tchar m_aMessageTopic[512];\n\tchar m_aMessageBody[512];\n\tchar m_aMessageButton[512];\n\tint m_NextPopup;\n\n\tvoid PopupMessage(const char *pTopic, const char *pBody, const char *pButton, int Next=POPUP_NONE);\n\n\t// TODO: this is a bit ugly but.. well.. yeah\n\tenum { MAX_INPUTEVENTS = 32 };\n\tstatic IInput::CEvent m_aInputEvents[MAX_INPUTEVENTS];\n\tstatic int m_NumInputEvents;\n\n\t// some settings\n\tstatic float ms_ButtonHeight;\n\tstatic float ms_ListheaderHeight;\n\tstatic float ms_FontmodHeight;\n\n\t// for settings\n\tbool m_NeedRestartGraphics;\n\tbool m_NeedRestartSound;\n\tint m_TeePartSelected;\n\tchar m_aSaveSkinName[24];\n\n\tvoid SaveSkinfile();\n\tbool m_RefreshSkinSelector;\n\tconst CSkins::CSkin *m_pSelectedSkin;\n\n\t//\n\tbool m_EscapePressed;\n\tbool m_EnterPressed;\n\tbool m_DeletePressed;\n\n\t// for map download popup\n\tint64 m_DownloadLastCheckTime;\n\tint m_DownloadLastCheckSize;\n\tfloat m_DownloadSpeed;\n\n\t// for call vote\n\tint m_CallvoteSelectedOption;\n\tint m_CallvoteSelectedPlayer;\n\tchar m_aCallvoteReason[VOTE_REASON_LENGTH];\n\n\t// for callbacks\n\tint *m_pActiveDropdown;\n\n\t// demo\n\tstruct CDemoItem\n\t{\n\t\tchar m_aFilename[128];\n\t\tchar m_aName[128];\n\t\tbool m_IsDir;\n\t\tint m_StorageType;\n\n\t\tbool m_InfosLoaded;\n\t\tbool m_Valid;\n\t\tCDemoHeader m_Info;\n\n\t\tbool operator<(const CDemoItem &Other) { return !str_comp(m_aFilename, \"..\") ? true : !str_comp(Other.m_aFilename, \"..\") ? false :\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tm_IsDir && !Other.m_IsDir ? true : !m_IsDir && Other.m_IsDir ? false :\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr_comp_filenames(m_aFilename, Other.m_aFilename) < 0; }\n\t};\n\n\tsorted_array<CDemoItem> m_lDemos;\n\tchar m_aCurrentDemoFolder[256];\n\tchar m_aCurrentDemoFile[64];\n\tint m_DemolistSelectedIndex;\n\tbool m_DemolistSelectedIsDir;\n\tint m_DemolistStorageType;\n\n\tvoid DemolistOnUpdate(bool Reset);\n\tvoid DemolistPopulate();\n\tstatic int DemolistFetchCallback(const char *pName, int IsDir, int StorageType, void *pUser);\n\n\t// friends\n\tstruct CFriendItem\n\t{\n\t\tconst CFriendInfo *m_pFriendInfo;\n\t\tint m_NumFound;\n\n\t\tbool operator<(const CFriendItem &Other)\n\t\t{\n\t\t\tif(m_NumFound && !Other.m_NumFound)\n\t\t\t\treturn true;\n\t\t\telse if(!m_NumFound && Other.m_NumFound)\n\t\t\t\treturn false;\n\t\t\telse\n\t\t\t{\n\t\t\t\tint Result = str_comp_nocase(m_pFriendInfo->m_aName, Other.m_pFriendInfo->m_aName);\n\t\t\t\tif(Result)\n\t\t\t\t\treturn Result < 0;\n\t\t\t\telse\n\t\t\t\t\treturn str_comp_nocase(m_pFriendInfo->m_aClan, Other.m_pFriendInfo->m_aClan) < 0;\n\t\t\t}\n\t\t}\n\t};\n\n\tsorted_array<CFriendItem> m_lFriends;\n\tint m_FriendlistSelectedIndex;\n\n\tvoid FriendlistOnUpdate();\n\n\tclass CBrowserFilter\n\t{\n\t\tbool m_Extended;\n\t\tint m_Custom;\n\t\tchar m_aName[64];\n\t\tint m_Filter;\n\t\tclass IServerBrowser *m_pServerBrowser;\n\n\tpublic:\n\n\t\tenum\n\t\t{\n\t\t\tFILTER_CUSTOM=0,\n\t\t\tFILTER_ALL,\n\t\t\tFILTER_STANDARD,\n\t\t\tFILTER_FAVORITES,\n\t\t};\n\t\t// buttons var\n\t\tint m_SwitchButton;\n\n\t\tCBrowserFilter() {}\n\t\tCBrowserFilter(int Custom, const char* pName, IServerBrowser *pServerBrowser, int Filter, int Ping, int Country, const char* pGametype, const char* pServerAddress);\n\t\tvoid Switch();\n\t\tbool Extended() const;\n\t\tint Custom() const;\n\t\tint Filter() const;\n\t\tconst char* Name() const;\n\n\t\tvoid SetFilterNum(int Num);\n\n\t\tint NumSortedServers() const;\n\t\tint NumPlayers() const;\n\t\tconst CServerInfo *SortedGet(int Index) const;\n\t\tconst void *ID(int Index) const;\n\n\t\tvoid GetFilter(int *pSortHash, int *pPing, int *pCountry, char* pGametype, char* pServerAddress);\n\t\tvoid SetFilter(int SortHash, int Ping, int Country, const char* pGametype, const char* pServerAddress);\n\t};\n\n\tarray<CBrowserFilter> m_lFilters;\n\n\tint m_SelectedFilter;\n\n\tvoid RemoveFilter(int FilterIndex);\n\tvoid Move(bool Up, int Filter);\n\n\tclass CInfoOverlay\n\t{\n\tpublic:\n\t\tenum\n\t\t{\n\t\t\tOVERLAY_SERVERINFO=0,\n\t\t\tOVERLAY_HEADERINFO,\n\t\t\tOVERLAY_PLAYERSINFO,\n\t\t};\n\n\t\tint m_Type;\n\t\tconst void *m_pData;\n\t\tfloat m_X;\n\t\tfloat m_Y;\n\t\tbool m_Reset;\n\t};\n\n\tCInfoOverlay m_InfoOverlay;\n\tbool m_InfoOverlayActive;\n\n\tclass CServerEntry\n\t{\n\tpublic:\n\t\tint m_Filter;\n\t\tint m_Index;\n\t};\n\n\tCServerEntry m_SelectedServer;\n\n\tenum\n\t{\n\t\tFIXED=1,\n\t\tSPACER=2,\n\n\t\tCOL_FLAG=0,\n\t\tCOL_NAME,\n\t\tCOL_GAMETYPE,\n\t\tCOL_MAP,\n\t\tCOL_PLAYERS,\n\t\tCOL_PING,\n\t\t//COL_FAVORITE,\n\t\t//COL_INFO,\n\n\t\tNUM_COLS,\n\t};\n\n\tstruct CColumn\n\t{\n\t\tint m_ID;\n\t\tint m_Sort;\n\t\tCLocConstString m_Caption;\n\t\tint m_Direction;\n\t\tfloat m_Width;\n\t\tint m_Flags;\n\t\tCUIRect m_Rect;\n\t\tCUIRect m_Spacer;\n\t};\n\n\tstatic CColumn ms_aCols[NUM_COLS];\n\n\tenum\n\t{\n\t\tMAX_RESOLUTIONS=256,\n\t};\n\n\tCVideoMode m_aModes[MAX_RESOLUTIONS];\n\tint m_NumModes;\n\n\tstruct CVideoFormat\n\t{\n\t\tint m_WidthValue;\n\t\tint m_HeightValue;\n\t};\n\t\n\tCVideoFormat m_aVideoFormats[MAX_RESOLUTIONS];\n\tsorted_array<CVideoMode> m_lFilteredVideoModes;\n\tint m_NumVideoFormats;\n\tint m_CurrentVideoFormat;\n\tvoid UpdateVideoFormats();\n\tvoid UpdatedFilteredVideoModes();\n\n\t// found in menus.cpp\n\tint Render();\n\t//void render_background();\n\t//void render_loading(float percent);\n\tvoid RenderMenubar(CUIRect r);\n\tvoid RenderNews(CUIRect MainView);\n\tvoid RenderBackButton(CUIRect MainView);\n\n\t// found in menus_demo.cpp\n\tvoid RenderDemoPlayer(CUIRect MainView);\n\tvoid RenderDemoList(CUIRect MainView);\n\n\t// found in menus_start.cpp\n\tvoid RenderStartMenu(CUIRect MainView);\n\tvoid RenderLogo(CUIRect MainView);\n\n\t// found in menus_ingame.cpp\n\tvoid RenderGame(CUIRect MainView);\n\tvoid RenderPlayers(CUIRect MainView);\n\tvoid RenderServerInfo(CUIRect MainView);\n\tvoid HandleCallvote(int Page, bool Force);\n\tvoid RenderServerControl(CUIRect MainView);\n\tvoid RenderServerControlKick(CUIRect MainView, bool FilterSpectators);\n\tvoid RenderServerControlServer(CUIRect MainView);\n\n\t// found in menus_browser.cpp\n\tint m_ScrollOffset;\n\tvoid RenderServerbrowserServerList(CUIRect View);\n\tvoid RenderServerbrowserFriendList(CUIRect View);\n\tvoid RenderServerbrowserServerDetail(CUIRect View, const CServerInfo *pInfo);\n\tvoid RenderServerbrowserFilters(CUIRect View);\n\tvoid RenderServerbrowserFriends(CUIRect View);\n\tvoid RenderServerbrowserBottomBox(CUIRect View);\n\tvoid RenderServerbrowserOverlay();\n\tbool RenderFilterHeader(CUIRect View, int FilterIndex);\n\tint DoBrowserEntry(const void *pID, CUIRect *pRect, const CServerInfo *pEntry, bool Selected);\n\tvoid RenderServerbrowser(CUIRect MainView);\n\tstatic void ConchainFriendlistUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData);\n\tstatic void ConchainServerbrowserUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData);\n\tvoid SetOverlay(int Type, float x, float y, const void *pData);\n\n\t// found in menus_settings.cpp\n\tvoid RenderLanguageSelection(CUIRect MainView, bool Header=true);\n\tvoid RenderHSLPicker(CUIRect Picker);\n\tvoid RenderSkinSelection(CUIRect MainView);\n\tvoid RenderSkinPartSelection(CUIRect MainView);\n\tvoid RenderSettingsGeneral(CUIRect MainView);\n\tvoid RenderSettingsPlayer(CUIRect MainView);\n\tvoid RenderSettingsTee(CUIRect MainView);\n\tvoid RenderSettingsTeeBasic(CUIRect MainView);\n\tvoid RenderSettingsTeeCustom(CUIRect MainView);\n\tvoid RenderSettingsControls(CUIRect MainView);\n\tvoid RenderSettingsGraphics(CUIRect MainView);\n\tvoid RenderSettingsSound(CUIRect MainView);\n\tvoid RenderSettings(CUIRect MainView);\n\n\t// found in menu_callback.cpp\n\tstatic float RenderSettingsControlsMovement(CUIRect View, void *pUser);\n\tstatic float RenderSettingsControlsWeapon(CUIRect View, void *pUser);\n\tstatic float RenderSettingsControlsVoting(CUIRect View, void *pUser);\n\tstatic float RenderSettingsControlsChat(CUIRect View, void *pUser);\n\tstatic float RenderSettingsControlsMisc(CUIRect View, void *pUser);\n\n\tvoid SetActive(bool Active);\n\n\tvoid InvokePopupMenu(void *pID, int Flags, float X, float Y, float W, float H, int (*pfnFunc)(CMenus *pMenu, CUIRect Rect), void *pExtra=0);\n\tvoid DoPopupMenu();\n\n\tstatic int PopupFilter(CMenus *pMenus, CUIRect View);\n\n\tIGraphics::CTextureHandle m_TextureBlob;\npublic:\n\tvoid RenderBackground();\n\n\tvoid UseMouseButtons(bool Use) { m_UseMouseButtons = Use; }\n\n\tstatic CMenusKeyBinder m_Binder;\n\n\tCMenus();\n\n\tvoid RenderLoading();\n\n\tbool IsActive() const { return m_MenuActive; }\n\n\tvirtual void OnInit();\n\n\tvirtual void OnConsoleInit();\n\tvirtual void OnStateChange(int NewState, int OldState);\n\tvirtual void OnReset();\n\tvirtual void OnRender();\n\tvirtual bool OnInput(IInput::CEvent Event);\n\tvirtual bool OnMouseMove(float x, float y);\n};\n#endif\n"
  },
  {
    "path": "src/game/client/components/menus_browser.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/config.h>\n#include <engine/friends.h>\n#include <engine/graphics.h>\n#include <engine/keys.h>\n#include <engine/serverbrowser.h>\n#include <engine/textrender.h>\n#include <engine/shared/config.h>\n\n#include <game/generated/client_data.h>\n#include <game/generated/protocol.h>\n\n#include <game/version.h>\n#include <game/client/render.h>\n#include <game/client/ui.h>\n#include <game/client/components/countryflags.h>\n\n#include \"menus.h\"\n\nCMenus::CColumn CMenus::ms_aCols[] = {\n\t{COL_FLAG,\t\t-1,\t\t\t\t\t\t\t\t\t\" \",\t\t-1, 87.0f, 0, {0}, {0}}, // Localize - these strings are localized within CLocConstString\n\t{COL_NAME,\t\tIServerBrowser::SORT_NAME,\t\t\t\"Server\",\t\t0, 300.0f, 0, {0}, {0}},\n\t{COL_GAMETYPE,\tIServerBrowser::SORT_GAMETYPE,\t\t\"Type\",\t\t1, 70.0f, 0, {0}, {0}},\n\t{COL_MAP,\t\tIServerBrowser::SORT_MAP,\t\t\t\"Map\",\t\t1, 100.0f, 0, {0}, {0}},\n\t{COL_PLAYERS,\tIServerBrowser::SORT_NUMPLAYERS,\t\"Players\",\t1, 60.0f, 0, {0}, {0}},\n\t{COL_PING,\t\tIServerBrowser::SORT_PING,\t\t\t\"Ping\",\t\t1, 40.0f, 0, {0}, {0}},\n\t//{COL_FAVORITE,\t-1,\t\t\t\t\t\t\t\t\t\" \",\t\t1, 14.0f, 0, {0}, {0}},\n\t//{COL_INFO,\t\t-1,\t\t\t\t\t\t\t\t\t\" \",\t\t1, 14.0f, 0, {0}, {0}},\n};\n\n\t\n// filters\nCMenus::CBrowserFilter::CBrowserFilter(int Custom, const char* pName, IServerBrowser *pServerBrowser, int Filter, int Ping, int Country, const char* pGametype, const char* pServerAddress)\n: m_pServerBrowser(pServerBrowser)\n{\n\tm_Extended = true;\n\tm_Custom = Custom;\n\tstr_copy(m_aName, pName, sizeof(m_aName));\n\tm_Filter = pServerBrowser->AddFilter(Filter, Ping, Country, pGametype, pServerAddress);\n\n\t// init buttons\n\tm_SwitchButton = 0;\n}\n\nvoid CMenus::CBrowserFilter::Switch()\n{\n\tm_Extended ^= 1;\n}\n\nbool CMenus::CBrowserFilter::Extended() const\n{\n\treturn m_Extended;\n}\n\nint CMenus::CBrowserFilter::Custom() const\n{\n\treturn m_Custom;\n}\n\nint CMenus::CBrowserFilter::Filter() const\n{\n\treturn m_Filter;\n}\n\nconst char* CMenus::CBrowserFilter::Name() const\n{\n\treturn m_aName;\n}\n\nconst void *CMenus::CBrowserFilter::ID(int Index) const\n{\n\treturn m_pServerBrowser->GetID(m_Filter, Index);\n}\n\nint CMenus::CBrowserFilter::NumSortedServers() const\n{\n\treturn m_pServerBrowser->NumSortedServers(m_Filter);\n}\n\nint CMenus::CBrowserFilter::NumPlayers() const\n{\n\treturn m_pServerBrowser->NumSortedPlayers(m_Filter);\n}\n\nconst CServerInfo *CMenus::CBrowserFilter::SortedGet(int Index) const\n{\n\treturn m_pServerBrowser->SortedGet(m_Filter, Index);\n}\n\nvoid CMenus::CBrowserFilter::SetFilterNum(int Num)\n{\n\tm_Filter = Num;\n}\n\nvoid CMenus::CBrowserFilter::GetFilter(int *pSortHash, int *pPing, int *pCountry, char* pGametype, char* pServerAddress)\n{\n\tm_pServerBrowser->GetFilter(m_Filter, pSortHash, pPing, pCountry, pGametype, pServerAddress);\n}\n\nvoid CMenus::CBrowserFilter::SetFilter(int SortHash, int Ping, int Country, const char* pGametype, const char* pServerAddress)\n{\n\tm_pServerBrowser->SetFilter(m_Filter, SortHash, Ping, Country, pGametype, pServerAddress);\n}\n\nvoid CMenus::RemoveFilter(int FilterIndex)\n{\n\tint Filter = m_lFilters[FilterIndex].Filter();\n\tServerBrowser()->RemoveFilter(Filter);\n\tm_lFilters.remove_index(FilterIndex);\n\n\t// update filter indexes\n\tfor(int i = 0; i < m_lFilters.size(); i++)\n\t{\n\t\tCBrowserFilter *pFilter = &m_lFilters[i];\n\t\tif(pFilter->Filter() > Filter)\n\t\t\tpFilter->SetFilterNum(pFilter->Filter()-1);\n\t}\n}\n\nvoid CMenus::Move(bool Up, int Filter)\n{\n\t// move up\n\tCBrowserFilter Temp = m_lFilters[Filter];\n\tif(Up)\n\t{\n\t\tif(Filter > 0)\n\t\t{\n\t\t\tm_lFilters[Filter] = m_lFilters[Filter-1];\n\t\t\tm_lFilters[Filter-1] = Temp;\n\t\t}\n\t}\n\telse // move down\n\t{\n\t\tif(Filter < m_lFilters.size()-1)\n\t\t{\n\t\t\tm_lFilters[Filter] = m_lFilters[Filter+1];\n\t\t\tm_lFilters[Filter+1] = Temp;\n\t\t}\n\t}\n}\n\nvoid CMenus::SetOverlay(int Type, float x, float y, const void *pData)\n{\n\tif(m_InfoOverlay.m_Reset)\n\t{\n\t\tm_InfoOverlayActive = true;\n\t\tm_InfoOverlay.m_Type = Type;\n\t\tm_InfoOverlay.m_X = x;\n\t\tm_InfoOverlay.m_Y = y;\n\t\tm_InfoOverlay.m_pData = pData;\n\t\tm_InfoOverlay.m_Reset = false;\n\t}\n}\n\nint CMenus::DoBrowserEntry(const void *pID, CUIRect *pRect, const CServerInfo *pEntry, bool Selected)\n{\n\t// logic\n\tint ReturnValue = 0;\n\tint Inside = UI()->MouseInside(pRect);\n\n\tif(UI()->ActiveItem() == pID)\n\t{\n\t\tif(!UI()->MouseButton(0))\n\t\t{\n\t\t\tif(Inside >= 0)\n\t\t\t\tReturnValue = 1;\n\t\t\tUI()->SetActiveItem(0);\n\t\t}\n\t}\n\tif(UI()->HotItem() == pID)\n\t{\n\t\tif(UI()->MouseButton(0))\n\t\t\tUI()->SetActiveItem(pID);\n\n\t\tCUIRect r = *pRect;\n\t\tRenderTools()->DrawUIRect(&r, vec4(1.0f, 1.0f, 1.0f, 0.5f), CUI::CORNER_ALL, 4.0f);\n\t}\n\n\tif(Inside)\n\t\tUI()->SetHotItem(pID);\n\n\t// update friend counter\n\tif(pEntry->m_FriendState != IFriends::FRIEND_NO)\n\t{\n\t\tfor(int j = 0; j < pEntry->m_NumClients; ++j)\n\t\t{\n\t\t\tif(pEntry->m_aClients[j].m_FriendState != IFriends::FRIEND_NO)\n\t\t\t{\n\t\t\t\tunsigned NameHash = str_quickhash(pEntry->m_aClients[j].m_aName);\n\t\t\t\tunsigned ClanHash = str_quickhash(pEntry->m_aClients[j].m_aClan);\n\t\t\t\tfor(int f = 0; f < m_lFriends.size(); ++f)\n\t\t\t\t{\n\t\t\t\t\tif(ClanHash == m_lFriends[f].m_pFriendInfo->m_ClanHash &&\n\t\t\t\t\t\t(!m_lFriends[f].m_pFriendInfo->m_aName[0] || NameHash == m_lFriends[f].m_pFriendInfo->m_NameHash))\n\t\t\t\t\t{\n\t\t\t\t\t\tm_lFriends[f].m_NumFound++;\n\t\t\t\t\t\tif(m_lFriends[f].m_pFriendInfo->m_aName[0])\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvec3 TextBaseColor = vec3(1.0f, 1.0f, 1.0f);\n\tif(Selected || Inside)\n\t{\n\t\tTextBaseColor = vec3(0.0f, 0.0f, 0.0f);\n\t\tTextRender()->TextOutlineColor(1.0f, 1.0f, 1.0f, 0.25f);\n\t}\n\n\tfloat TextAplpha = (pEntry->m_NumPlayers == pEntry->m_MaxPlayers || pEntry->m_NumClients == pEntry->m_MaxClients) ? 0.5f : 1.0f;\n\tfor(int c = 0; c < NUM_COLS; c++)\n\t{\n\t\tCUIRect Button;\n\t\tchar aTemp[64];\n\t\tButton.x = ms_aCols[c].m_Rect.x;\n\t\tButton.y = pRect->y;\n\t\tButton.h = pRect->h;\n\t\tButton.w = ms_aCols[c].m_Rect.w;\n\n\t\tint ID = ms_aCols[c].m_ID;\n\n\t\tif(ID == COL_FLAG)\n\t\t{\n\t\t\tCUIRect Rect = Button;\n\t\t\tCUIRect Icon;\n\n\t\t\tRect.VSplitLeft(2.0f, 0, &Rect);\n\t\t\tRect.VSplitLeft(Rect.h, &Icon, &Rect);\n\t\t\tif(pEntry->m_Flags&IServerBrowser::FLAG_PASSWORD)\n\t\t\t{\n\t\t\t\tIcon.Margin(2.0f, &Icon);\n\t\t\t\tDoIcon(IMAGE_BROWSEICONS, Selected ? SPRITE_BROWSE_LOCK_B : SPRITE_BROWSE_LOCK_A, &Icon);\n\t\t\t}\n\n\t\t\tRect.VSplitLeft(2.0f, 0, &Rect);\n\t\t\tRect.VSplitLeft(Rect.h, &Icon, &Rect);\n\t\t\tif(!(pEntry->m_Flags&IServerBrowser::FLAG_PURE))\n\t\t\t{\n\t\t\t\tIcon.Margin(2.0f, &Icon);\n\t\t\t\tDoIcon(IMAGE_BROWSEICONS, Selected ? SPRITE_BROWSE_UNPURE_B : SPRITE_BROWSE_UNPURE_A, &Icon);\n\t\t\t}\n\n\t\t\tRect.VSplitLeft(2.0f, 0, &Rect);\n\t\t\tRect.VSplitLeft(Rect.h, &Icon, &Rect);\n\t\t\tif(pEntry->m_Favorite)\n\t\t\t{\n\t\t\t\tIcon.Margin(2.0f, &Icon);\n\t\t\t\tDoIcon(IMAGE_BROWSEICONS, Selected ? SPRITE_BROWSE_STAR_B : SPRITE_BROWSE_STAR_A, &Icon);\n\t\t\t}\n\n\t\t\tRect.VSplitLeft(2.0f, 0, &Rect);\n\t\t\tRect.VSplitLeft(Rect.h, &Icon, &Rect);\n\t\t\tif(pEntry->m_FriendState != IFriends::FRIEND_NO)\n\t\t\t{\n\t\t\t\tIcon.Margin(2.0f, &Icon);\n\t\t\t\tDoIcon(IMAGE_BROWSEICONS, Selected ? SPRITE_BROWSE_HEART_B : SPRITE_BROWSE_HEART_A, &Icon);\n\t\t\t}\n\t\t}\n\t\telse if(ID == COL_NAME)\n\t\t{\n\t\t\tCTextCursor Cursor;\n\t\t\tfloat tw = TextRender()->TextWidth(0, 12.0f, pEntry->m_aName, -1);\n\t\t\tif(tw < Button.w)\n\t\t\t\tTextRender()->SetCursor(&Cursor, Button.x+Button.w/2.0f-tw/2.0f, Button.y, 12.0f, TEXTFLAG_RENDER);\n\t\t\telse\n\t\t\t{\n\t\t\t\tTextRender()->SetCursor(&Cursor, Button.x, Button.y, 12.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\t\t\t\tCursor.m_LineWidth = Button.w;\n\t\t\t}\n\t\t\t\n\t\t\tTextRender()->TextColor(TextBaseColor.r, TextBaseColor.g, TextBaseColor.b, TextAplpha);\n\n\t\t\tif(g_Config.m_BrFilterString[0] && (pEntry->m_QuickSearchHit&IServerBrowser::QUICK_SERVERNAME))\n\t\t\t{\n\t\t\t\t// highlight the parts that matches\n\t\t\t\tconst char *pStr = str_find_nocase(pEntry->m_aName, g_Config.m_BrFilterString);\n\t\t\t\tif(pStr)\n\t\t\t\t{\n\t\t\t\t\tTextRender()->TextEx(&Cursor, pEntry->m_aName, (int)(pStr-pEntry->m_aName));\n\t\t\t\t\tTextRender()->TextColor(0.4f, 0.4f, 1.0f, TextAplpha);\n\t\t\t\t\tTextRender()->TextEx(&Cursor, pStr, str_length(g_Config.m_BrFilterString));\n\t\t\t\t\tTextRender()->TextColor(TextBaseColor.r, TextBaseColor.g, TextBaseColor.b, TextAplpha);\n\t\t\t\t\tTextRender()->TextEx(&Cursor, pStr+str_length(g_Config.m_BrFilterString), -1);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tTextRender()->TextEx(&Cursor, pEntry->m_aName, -1);\n\t\t\t}\n\t\t\telse\n\t\t\t\tTextRender()->TextEx(&Cursor, pEntry->m_aName, -1);\n\t\t}\n\t\telse if(ID == COL_MAP)\n\t\t{\n\t\t\tCTextCursor Cursor;\n\t\t\tfloat tw = TextRender()->TextWidth(0, 12.0f, pEntry->m_aMap, -1);\n\t\t\tif(tw < Button.w)\n\t\t\t\tTextRender()->SetCursor(&Cursor, Button.x+Button.w/2.0f-tw/2.0f, Button.y, 12.0f, TEXTFLAG_RENDER);\n\t\t\telse\n\t\t\t{\n\t\t\t\tTextRender()->SetCursor(&Cursor, Button.x, Button.y, 12.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\t\t\t\tCursor.m_LineWidth = Button.w;\n\t\t\t}\n\n\t\t\tTextRender()->TextColor(TextBaseColor.r, TextBaseColor.g, TextBaseColor.b, TextAplpha);\n\n\t\t\tif(g_Config.m_BrFilterString[0] && (pEntry->m_QuickSearchHit&IServerBrowser::QUICK_MAPNAME))\n\t\t\t{\n\t\t\t\t// highlight the parts that matches\n\t\t\t\tconst char *pStr = str_find_nocase(pEntry->m_aMap, g_Config.m_BrFilterString);\n\t\t\t\tif(pStr)\n\t\t\t\t{\n\t\t\t\t\tTextRender()->TextEx(&Cursor, pEntry->m_aMap, (int)(pStr-pEntry->m_aMap));\n\t\t\t\t\tTextRender()->TextColor(0.4f, 0.4f, 1.0f, TextAplpha);\n\t\t\t\t\tTextRender()->TextEx(&Cursor, pStr, str_length(g_Config.m_BrFilterString));\n\t\t\t\t\tTextRender()->TextColor(TextBaseColor.r, TextBaseColor.g, TextBaseColor.b, TextAplpha);\n\t\t\t\t\tTextRender()->TextEx(&Cursor, pStr+str_length(g_Config.m_BrFilterString), -1);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tTextRender()->TextEx(&Cursor, pEntry->m_aMap, -1);\n\t\t\t}\n\t\t\telse\n\t\t\t\tTextRender()->TextEx(&Cursor, pEntry->m_aMap, -1);\n\t\t}\n\t\telse if(ID == COL_PLAYERS)\n\t\t{\n\t\t\t// handle mouse over\n\t\t\tif(m_InfoMode && UI()->MouseInside(&Button))\n\t\t\t{\n\t\t\t\t// overlay\n\t\t\t\tSetOverlay(CInfoOverlay::OVERLAY_PLAYERSINFO, UI()->MouseX(), UI()->MouseY(), pEntry);\n\n\t\t\t\t// rect\n\t\t\t\tRenderTools()->DrawUIRect(&Button, vec4(0.973f, 0.863f, 0.207, 0.75f), CUI::CORNER_ALL, 5.0f);\n\t\t\t}\n\n\t\t\tTextRender()->TextColor(TextBaseColor.r, TextBaseColor.g, TextBaseColor.b, TextAplpha);\n\n\t\t\tif(g_Config.m_BrFilterSpectators)\n\t\t\t\tstr_format(aTemp, sizeof(aTemp), \"%d/%d\", pEntry->m_NumPlayers, pEntry->m_MaxPlayers);\n\t\t\telse\n\t\t\t\tstr_format(aTemp, sizeof(aTemp), \"%d/%d\", pEntry->m_NumClients, pEntry->m_MaxClients);\n\t\t\tif(g_Config.m_BrFilterString[0] && (pEntry->m_QuickSearchHit&IServerBrowser::QUICK_PLAYER))\n\t\t\t\tTextRender()->TextColor(0.4f, 0.4f, 1.0f, TextAplpha);\n\t\t\tButton.y += 2.0f;\n\t\t\tUI()->DoLabel(&Button, aTemp, 12.0f, 0);\n\t\t}\n\t\telse if(ID == COL_PING)\n\t\t{\n\t\t\tint Ping = pEntry->m_Latency;\n\n\t\t\tvec4 Color;\n\t\t\tif(Selected || Inside)\n\t\t\t{\n\t\t\t\tColor = vec4(TextBaseColor.r, TextBaseColor.g, TextBaseColor.b, TextAplpha);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tvec4 StartColor;\n\t\t\t\tvec4 EndColor;\n\t\t\t\tfloat MixVal;\n\t\t\t\tif(Ping <= 125)\n\t\t\t\t{\n\t\t\t\t\tStartColor = vec4(0.0f, 1.0f, 0.0f, TextAplpha);\n\t\t\t\t\tEndColor = vec4(1.0f, 1.0f, 0.0f, TextAplpha);\n\t\t\t\t\t\n\t\t\t\t\tMixVal = (Ping-50.0f)/75.0f;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tStartColor = vec4(1.0f, 1.0f, 0.0f, TextAplpha);\n\t\t\t\t\tEndColor = vec4(1.0f, 0.0f, 0.0f, TextAplpha);\n\t\t\t\t\t\n\t\t\t\t\tMixVal = (Ping-125.0f)/75.0f;\n\t\t\t\t}\n\t\t\t\tColor = mix(StartColor, EndColor, MixVal);\n\t\t\t}\n\t\t\t\n\t\t\tstr_format(aTemp, sizeof(aTemp), \"%d\", pEntry->m_Latency);\n\t\t\tTextRender()->TextColor(Color.r, Color.g, Color.b, Color.a);\n\t\t\tButton.y += 2.0f;\n\t\t\tUI()->DoLabel(&Button, aTemp, 12.0f, 0);\n\t\t}\n\t\telse if(ID == COL_GAMETYPE)\n\t\t{\n\t\t\tCTextCursor Cursor;\n\t\t\tfloat tw = TextRender()->TextWidth(0, 12.0f, pEntry->m_aGameType, -1);\n\t\t\tif(tw < Button.w)\n\t\t\t\tTextRender()->SetCursor(&Cursor, Button.x+Button.w/2.0f-tw/2.0f, Button.y, 12.0f, TEXTFLAG_RENDER);\n\t\t\telse\n\t\t\t{\n\t\t\t\tTextRender()->SetCursor(&Cursor, Button.x, Button.y, 12.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\t\t\t\tCursor.m_LineWidth = Button.w;\n\t\t\t}\n\n\t\t\tTextRender()->TextColor(TextBaseColor.r, TextBaseColor.g, TextBaseColor.b, TextAplpha);\n\t\t\tTextRender()->TextEx(&Cursor, pEntry->m_aGameType, -1);\n\t\t}\n\t\t/*else if(ID == COL_FAVORITE)\n\t\t{\n\t\t\tButton.HMargin(1.5f, &Button);\n\t\t\tif(DoButton_SpriteClean(IMAGE_BROWSEICONS, pEntry->m_Favorite ? SPRITE_BROWSE_STAR_A : SPRITE_BROWSE_STAR_B, &Button))\n\t\t\t{\n\t\t\t\tif(!pEntry->m_Favorite)\n\t\t\t\t\tServerBrowser()->AddFavorite(pEntry);\n\t\t\t\telse\n\t\t\t\t\tServerBrowser()->RemoveFavorite(pEntry);\n\t\t\t}\n\t\t}\n\t\telse if(ID == COL_INFO)\n\t\t{\n\t\t\tButton.HMargin(1.5f, &Button);\n\t\t\tif(DoButton_MouseOver(IMAGE_BROWSEICONS, SPRITE_BROWSE_HEART_A, &Button))\n\t\t\t\tSetOverlay(CInfoOverlay::OVERLAY_SERVERINFO, Button.x, Button.y, pEntry);\n\t\t}*/\n\t}\n\n\tTextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f);\n\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\n\treturn ReturnValue;\n}\n\nbool CMenus::RenderFilterHeader(CUIRect View, int FilterIndex)\n{\n\tCBrowserFilter *pFilter = &m_lFilters[FilterIndex];\n\n\tfloat ButtonHeight = 20.0f;\n\tfloat Spacing = 3.0f;\n\n\tRenderTools()->DrawUIRect(&View, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\tCUIRect Button, EditButtons;\n\tView.VSplitLeft(20.0f, &Button, &View);\n\tButton.Margin(2.0f, &Button);\n\tif(DoButton_SpriteClean(IMAGE_MENUICONS, pFilter->Extended() ? SPRITE_MENU_EXPANDED : SPRITE_MENU_COLLAPSED, &Button))\n\t\tpFilter->Switch();\n\n\t// split buttons from label\n\tView.VSplitLeft(Spacing, 0, &View);\n\tView.VSplitRight((ButtonHeight+Spacing)*4.0f, &View, &EditButtons);\n\n\tView.VSplitLeft(20.0f, 0, &View); // little space\n\tView.y += 2.0f;\n\tUI()->DoLabel(&View, pFilter->Name(), ButtonHeight*ms_FontmodHeight*0.8f, -1);\n\n\t/*if(pFilter->Custom() <= CBrowserFilter::FILTER_ALL)\n\t\tUI()->DoLabel(&View, pFilter->Name(), 12.0f, -1);\n\telse\n\t{\n\t\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_BROWSEICONS].m_Id);\n\t\tGraphics()->QuadsBegin();\n\t\tif(pFilter->Custom() == CBrowserFilter::FILTER_STANDARD)\n\t\t\tRenderTools()->SelectSprite(SPRITE_BROWSE_STAR_B);\n\t\telse if(pFilter->Custom() == CBrowserFilter::FILTER_FAVORITES)\n\t\t\tRenderTools()->SelectSprite(SPRITE_BROWSE_STAR_A);\n\t\tIGraphics::CQuadItem QuadItem(Label.x, View.y, 18.0f, 18.0f);\n\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t\tGraphics()->QuadsEnd();\n\n\t\tLabel.VSplitLeft(25.0f, 0, &Label);\n\t\tUI()->DoLabel(&Label, pFilter->Name(), 12.0f, -1);\n\t}*/\n\n\tEditButtons.VSplitRight(ButtonHeight, &EditButtons, &Button);\n\tButton.Margin(2.0f, &Button);\n\tif(pFilter->Custom() == CBrowserFilter::FILTER_CUSTOM)\n\t{\n\t\tif(DoButton_SpriteClean(IMAGE_TOOLICONS, SPRITE_TOOL_X_A, &Button))\n\t\t{\n\t\t\tRemoveFilter(FilterIndex);\n\t\t\treturn true;\n\t\t}\n\t}\n\telse\n\t\tDoIcon(IMAGE_TOOLICONS, SPRITE_TOOL_X_B, &Button);\n\n\tEditButtons.VSplitRight(Spacing, &EditButtons, 0);\n\tEditButtons.VSplitRight(ButtonHeight, &EditButtons, &Button);\n\tButton.Margin(2.0f, &Button);\n\tif(pFilter->Custom() == CBrowserFilter::FILTER_CUSTOM)\n\t{\n\t\tif(DoButton_SpriteClean(IMAGE_TOOLICONS, SPRITE_TOOL_EDIT_A, &Button))\n\t\t{\n\t\t\tRemoveFilter(FilterIndex);\n\t\t\treturn true;\n\t\t}\n\t}\n\telse\n\t\tDoIcon(IMAGE_TOOLICONS, SPRITE_TOOL_EDIT_B, &Button);\n\n\t/*EditButtons.VSplitRight(Spacing, &EditButtons, 0):\n\tEditButtons.VSplitRight(ButtonHeight, &EditButtons, &Button);\n\tButton.VSplitRight(18.0f, &View, &Button);\n\tif(DoButton_SpriteCleanID(pFilter, IMAGE_BROWSEICONS, SPRITE_BROWSE_STAR_A, &Button)) // TODO: using the address of filter as ID is prolly a bad idea\n\t{\n\t\tstatic int s_EditPopupID = 0;\n\t\tm_SelectedFilter = FilterIndex;\n\t\tInvokePopupMenu(&s_EditPopupID, 0, UI()->MouseX(), UI()->MouseY(), 200.0f, 310.0f, PopupFilter);\n\t}*/\n\n\tEditButtons.VSplitRight(Spacing, &EditButtons, 0);\n\tEditButtons.VSplitRight(ButtonHeight, &EditButtons, &Button);\n\tButton.Margin(2.0f, &Button);\n\tif(FilterIndex < m_lFilters.size()-1)\n\t{\n\t\tif(DoButton_SpriteClean(IMAGE_TOOLICONS, SPRITE_TOOL_UP_A, &Button))\n\t\t\tMove(false, FilterIndex);\n\t}\n\telse\n\t\tDoIcon(IMAGE_TOOLICONS, SPRITE_TOOL_UP_B, &Button);\n\n\tEditButtons.VSplitRight(Spacing, &EditButtons, 0);\n\tEditButtons.VSplitRight(ButtonHeight, &EditButtons, &Button);\n\tButton.Margin(2.0f, &Button);\n\tif(FilterIndex > 0)\n\t{\n\t\tif(DoButton_SpriteClean(IMAGE_TOOLICONS, SPRITE_TOOL_DOWN_A, &Button))\n\t\t\tMove(true, FilterIndex);\n\t}\n\telse\n\t\tDoIcon(IMAGE_TOOLICONS, SPRITE_TOOL_DOWN_B, &Button);\n\n\treturn false;\n}\n\nvoid CMenus::RenderServerbrowserOverlay()\n{\n\tif(!m_InfoOverlayActive)\n\t{\n\t\tm_InfoOverlay.m_Reset = true;\n\t\treturn;\n\t}\n\n\tint Type = m_InfoOverlay.m_Type;\n\tCUIRect View;\n\n\tif(Type == CInfoOverlay::OVERLAY_HEADERINFO)\n\t{\n\t\tCBrowserFilter *pFilter = (CBrowserFilter*)m_InfoOverlay.m_pData;\n\n\t\t// get position\n\t\tView.x = m_InfoOverlay.m_X-100.0f;\n\t\tView.y = m_InfoOverlay.m_Y;\n\t\tView.w = 100.0f;\n\t\tView.h = 30.0f;\n\n\t\t// render background\n\t\tRenderTools()->DrawUIRect(&View, vec4(0.25f, 0.25f, 0.25f, 1.0f), CUI::CORNER_ALL, 6.0f);\n\n\t\tView.Margin(2.0f, &View);\n\n\t\tchar aBuf[128];\n\t\tstr_format(aBuf, sizeof(aBuf), \"%s: %d\", Localize(\"Servers\"), pFilter->NumSortedServers());\n\t\tUI()->DoLabel(&View, aBuf, 12.0f, 0);\n\n\t\tView.HSplitMid(0, &View);\n\t\tstr_format(aBuf, sizeof(aBuf), \"%s: %d\", Localize(\"Players\"), pFilter->NumPlayers());\n\t\tUI()->DoLabel(&View, aBuf, 12.0f, 0);\n\t}\n\telse if(Type == CInfoOverlay::OVERLAY_SERVERINFO)\n\t{\n\t\tconst CServerInfo *pInfo = (CServerInfo*)m_InfoOverlay.m_pData;\n\n\t\t// get position\n\t\tView.x = m_InfoOverlay.m_X-210.0f;\n\t\tView.y = m_InfoOverlay.m_Y;\n\t\tView.w = 210.0f;\n\t\tView.h = pInfo->m_NumClients ? 98.0f + pInfo->m_NumClients*25.0f : 72.0f;\n\t\tif(View.y+View.h >= 590.0f)\n\t\t\tView.y -= View.y+View.h - 590.0f;\n\n\t\t// render background\n\t\tRenderTools()->DrawUIRect(&View, vec4(0.25f, 0.25f, 0.25f, 1.0f), CUI::CORNER_ALL, 6.0f);\n\n\t\tRenderServerbrowserServerDetail(View, pInfo);\n\t}\n\telse if(Type == CInfoOverlay::OVERLAY_PLAYERSINFO)\n\t{\n\t\tconst CServerInfo *pInfo = (CServerInfo*)m_InfoOverlay.m_pData;\n\n\t\tCUIRect Screen = *UI()->Screen();\n\t\tfloat ButtonHeight = 20.0f;\n\n\t\tTextRender()->TextOutlineColor(1.0f, 1.0f, 1.0f, 0.25f);\n\t\tTextRender()->TextColor(0.0f, 0.0f, 0.0f, 1.0f);\n\n\t\tif(pInfo && pInfo->m_NumClients)\n\t\t{\n\t\t\t// get position\n\t\t\tView.x = m_InfoOverlay.m_X+25.0f;\n\t\t\tView.y = m_InfoOverlay.m_Y;\n\t\t\tView.w = 250.0f;\n\t\t\tView.h = pInfo->m_NumClients*ButtonHeight;\n\t\t\tif(View.x+View.w > Screen.w-5.0f)\n\t\t\t{\n\t\t\t\tView.y += 25.0f;\n\t\t\t\tView.x -= View.x+View.w-Screen.w+5.0f;\n\t\t\t}\n\t\t\tif(View.y+View.h >= 590.0f)\n\t\t\t\tView.y -= View.y+View.h - 590.0f;\n\n\t\t\t// render background\n\t\t\tRenderTools()->DrawUIRect(&View, vec4(1.0f, 1.0f, 1.0f, 0.75f), CUI::CORNER_ALL, 6.0f);\n\n\t\t\tCUIRect ServerScoreBoard = View;\n\t\t\tCTextCursor Cursor;\n\t\t\tconst float FontSize = 12.0f;\n\t\t\tfor (int i = 0; i < pInfo->m_NumClients; i++)\n\t\t\t{\n\t\t\t\tCUIRect Name, Clan, Score, Flag;\n\t\t\t\tServerScoreBoard.HSplitTop(ButtonHeight, &Name, &ServerScoreBoard);\n\t\t\t\tif(UI()->DoButtonLogic(&pInfo->m_aClients[i], \"\", 0, &Name))\n\t\t\t\t{\n\t\t\t\t\tif(pInfo->m_aClients[i].m_FriendState == IFriends::FRIEND_PLAYER)\n\t\t\t\t\t\tm_pClient->Friends()->RemoveFriend(pInfo->m_aClients[i].m_aName, pInfo->m_aClients[i].m_aClan);\n\t\t\t\t\telse\n\t\t\t\t\t\tm_pClient->Friends()->AddFriend(pInfo->m_aClients[i].m_aName, pInfo->m_aClients[i].m_aClan);\n\t\t\t\t\tFriendlistOnUpdate();\n\t\t\t\t\tClient()->ServerBrowserUpdate();\n\t\t\t\t}\n\n\t\t\t\tvec4 Colour = pInfo->m_aClients[i].m_FriendState == IFriends::FRIEND_NO ? vec4(1.0f, 1.0f, 1.0f, (i%2+1)*0.05f) :\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvec4(0.5f, 1.0f, 0.5f, 0.15f+(i%2+1)*0.05f);\n\t\t\t\tRenderTools()->DrawUIRect(&Name, Colour, CUI::CORNER_ALL, 4.0f);\n\t\t\t\tName.VSplitLeft(5.0f, 0, &Name);\n\t\t\t\tName.VSplitLeft(30.0f, &Score, &Name);\n\t\t\t\tName.VSplitRight(34.0f, &Name, &Flag);\n\t\t\t\tFlag.HMargin(4.0f, &Flag);\n\t\t\t\tName.VSplitRight(40.0f, &Name, &Clan);\n\n\t\t\t\t// score\n\t\t\t\tif(pInfo->m_aClients[i].m_Player)\n\t\t\t\t{\n\t\t\t\t\tchar aTemp[16];\n\t\t\t\t\tstr_format(aTemp, sizeof(aTemp), \"%d\", pInfo->m_aClients[i].m_Score);\n\t\t\t\t\tTextRender()->SetCursor(&Cursor, Score.x, Score.y+(Score.h-FontSize)/4.0f, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\t\t\t\t\tCursor.m_LineWidth = Score.w;\n\t\t\t\t\tTextRender()->TextEx(&Cursor, aTemp, -1);\n\t\t\t\t}\n\n\t\t\t\t// name\n\t\t\t\tTextRender()->SetCursor(&Cursor, Name.x, Name.y+(Name.h-FontSize)/4.0f, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\t\t\t\tCursor.m_LineWidth = Name.w;\n\t\t\t\tconst char *pName = pInfo->m_aClients[i].m_aName;\n\t\t\t\tif(g_Config.m_BrFilterString[0])\n\t\t\t\t{\n\t\t\t\t\t// highlight the parts that matches\n\t\t\t\t\tconst char *s = str_find_nocase(pName, g_Config.m_BrFilterString);\n\t\t\t\t\tif(s)\n\t\t\t\t\t{\n\t\t\t\t\t\tTextRender()->TextEx(&Cursor, pName, (int)(s-pName));\n\t\t\t\t\t\tTextRender()->TextColor(0.4f, 0.4f, 1.0f, 1.0f);\n\t\t\t\t\t\tTextRender()->TextEx(&Cursor, s, str_length(g_Config.m_BrFilterString));\n\t\t\t\t\t\tTextRender()->TextColor(0.0f, 0.0f, 0.0f, 1.0f);\n\t\t\t\t\t\tTextRender()->TextEx(&Cursor, s+str_length(g_Config.m_BrFilterString), -1);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tTextRender()->TextEx(&Cursor, pName, -1);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tTextRender()->TextEx(&Cursor, pName, -1);\n\n\t\t\t\t// clan\n\t\t\t\tTextRender()->SetCursor(&Cursor, Clan.x, Clan.y+(Clan.h-FontSize)/4.0f, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\t\t\t\tCursor.m_LineWidth = Clan.w;\n\t\t\t\tconst char *pClan = pInfo->m_aClients[i].m_aClan;\n\t\t\t\tif(g_Config.m_BrFilterString[0])\n\t\t\t\t{\n\t\t\t\t\t// highlight the parts that matches\n\t\t\t\t\tconst char *s = str_find_nocase(pClan, g_Config.m_BrFilterString);\n\t\t\t\t\tif(s)\n\t\t\t\t\t{\n\t\t\t\t\t\tTextRender()->TextEx(&Cursor, pClan, (int)(s-pClan));\n\t\t\t\t\t\tTextRender()->TextColor(0.4f, 0.4f, 1.0f, 1.0f);\n\t\t\t\t\t\tTextRender()->TextEx(&Cursor, s, str_length(g_Config.m_BrFilterString));\n\t\t\t\t\t\tTextRender()->TextColor(0.0f, 0.0f, 0.0f, 1.0f);\n\t\t\t\t\t\tTextRender()->TextEx(&Cursor, s+str_length(g_Config.m_BrFilterString), -1);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tTextRender()->TextEx(&Cursor, pClan, -1);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tTextRender()->TextEx(&Cursor, pClan, -1);\n\n\t\t\t\t// flag\n\t\t\t\tvec4 Color(1.0f, 1.0f, 1.0f, 0.75f);\n\t\t\t\tm_pClient->m_pCountryFlags->Render(pInfo->m_aClients[i].m_Country, &Color, Flag.x, Flag.y, Flag.w, Flag.h);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tView.x = m_InfoOverlay.m_X+25.0f;\n\t\t\tView.y = m_InfoOverlay.m_Y;\n\t\t\tView.w = 150.0f;\n\t\t\tView.h = ButtonHeight;\n\t\t\tif(View.x+View.w > Screen.w-5.0f)\n\t\t\t{\n\t\t\t\tView.y += 25.0f;\n\t\t\t\tView.x -= View.x+View.w-Screen.w+5.0f;\n\t\t\t}\n\t\t\tif(View.y+View.h >= 590.0f)\n\t\t\t\tView.y -= View.y+View.h - 590.0f;\n\n\t\t\t// render background\n\t\t\tRenderTools()->DrawUIRect(&View, vec4(1.0f, 1.0f, 1.0f, 0.75f), CUI::CORNER_ALL, 6.0f);\n\n\t\t\tView.y += 2.0f;\n\t\t\tUI()->DoLabel(&View, Localize(\"no players\"), View.h*ms_FontmodHeight*0.8f, 0);\n\t\t}\n\n\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\tTextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f);\n\t}\n\n\t// deactivate it\n\tvec2 OverlayCenter = vec2(View.x+View.w/2.0f, View.y+View.h/2.0f);\n\tfloat MouseDistance = distance(m_MousePos, OverlayCenter);\n\tfloat PrefMouseDistance = distance(m_PrevMousePos, OverlayCenter);\n\tif(PrefMouseDistance > MouseDistance && !UI()->MouseInside(&View))\n\t{\n\t\tm_InfoOverlayActive = false;\n\t\tm_InfoOverlay.m_Reset = true;\n\t}\n}\n\nvoid CMenus::RenderServerbrowserServerList(CUIRect View)\n{\n\tCUIRect Headers, Status, InfoButton;\n\n\tfloat SpacingH = 2.0f;\n\tfloat ButtonHeight = 20.0f;\n\n\t// background\n\tRenderTools()->DrawUIRect(&View, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\tView.HSplitTop(ms_ListheaderHeight, &Headers, &View);\n\tView.HSplitBottom(ButtonHeight*3.0f+SpacingH*2.0f, &View, &Status);\n\n\tHeaders.VSplitRight(ms_ListheaderHeight, &Headers, &InfoButton); // split for info button\n\n\t// do layout\n\tfor(int i = 0; i < NUM_COLS; i++)\n\t{\n\t\tif(ms_aCols[i].m_Direction == -1)\n\t\t{\n\t\t\tHeaders.VSplitLeft(ms_aCols[i].m_Width, &ms_aCols[i].m_Rect, &Headers);\n\n\t\t\tif(i+1 < NUM_COLS)\n\t\t\t{\n\t\t\t\t//Cols[i].flags |= SPACER;\n\t\t\t\tHeaders.VSplitLeft(2, &ms_aCols[i].m_Spacer, &Headers);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor(int i = NUM_COLS-1; i >= 0; i--)\n\t{\n\t\tif(ms_aCols[i].m_Direction == 1)\n\t\t{\n\t\t\tHeaders.VSplitRight(ms_aCols[i].m_Width, &Headers, &ms_aCols[i].m_Rect);\n\t\t\tHeaders.VSplitRight(2, &Headers, &ms_aCols[i].m_Spacer);\n\t\t}\n\t}\n\n\tfor(int i = 0; i < NUM_COLS; i++)\n\t{\n\t\tif(ms_aCols[i].m_Direction == 0)\n\t\t\tms_aCols[i].m_Rect = Headers;\n\t}\n\n\t// do headers\n\tfor(int i = 0; i < NUM_COLS; i++)\n\t{\n\t\tif(i == COL_FLAG)\n\t\t{\n\t\t\tCUIRect Rect = ms_aCols[i].m_Rect;\n\t\t\tCUIRect Icon;\n\n\t\t\tRect.VSplitLeft(2.0f, 0, &Rect);\n\t\t\tRect.VSplitLeft(Rect.h, &Icon, &Rect);\n\t\t\tIcon.Margin(2.0f, &Icon);\n\t\t\tDoIcon(IMAGE_BROWSEICONS, SPRITE_BROWSE_LOCK_A, &Icon);\n\n\t\t\tRect.VSplitLeft(2.0f, 0, &Rect);\n\t\t\tRect.VSplitLeft(Rect.h, &Icon, &Rect);\n\t\t\tIcon.Margin(2.0f, &Icon);\n\t\t\tDoIcon(IMAGE_BROWSEICONS, SPRITE_BROWSE_UNPURE_A, &Icon);\n\n\t\t\tRect.VSplitLeft(2.0f, 0, &Rect);\n\t\t\tRect.VSplitLeft(Rect.h, &Icon, &Rect);\n\t\t\tIcon.Margin(2.0f, &Icon);\n\t\t\tDoIcon(IMAGE_BROWSEICONS, SPRITE_BROWSE_STAR_A, &Icon);\n\n\t\t\tRect.VSplitLeft(2.0f, 0, &Rect);\n\t\t\tRect.VSplitLeft(Rect.h, &Icon, &Rect);\n\t\t\tIcon.Margin(2.0f, &Icon);\n\t\t\tDoIcon(IMAGE_BROWSEICONS, SPRITE_BROWSE_HEART_A, &Icon);\n\t\t}\n\t\telse if(DoButton_GridHeader(ms_aCols[i].m_Caption, ms_aCols[i].m_Caption, g_Config.m_BrSort == ms_aCols[i].m_Sort, &ms_aCols[i].m_Rect))\n\t\t{\n\t\t\tif(ms_aCols[i].m_Sort != -1)\n\t\t\t{\n\t\t\t\tif(g_Config.m_BrSort == ms_aCols[i].m_Sort)\n\t\t\t\t\tg_Config.m_BrSortOrder ^= 1;\n\t\t\t\telse\n\t\t\t\t\tg_Config.m_BrSortOrder = 0;\n\t\t\t\tg_Config.m_BrSort = ms_aCols[i].m_Sort;\n\t\t\t}\n\t\t}\n\t}\n\n\t// do info icon at the end of the list header\n\t{\n\t\tInfoButton.Margin(2.0f, &InfoButton);\n\t\tstatic int s_InfoButton = 0;\n\t\tif(DoButton_SpriteCleanID(&s_InfoButton, IMAGE_INFOICONS, ((m_InfoMode && !UI()->MouseInside(&InfoButton)) || (!m_InfoMode && UI()->MouseInside(&InfoButton))) ? SPRITE_INFO_B : SPRITE_INFO_A, &InfoButton, false))\n\t\t{\n\t\t\tm_InfoMode ^= 1;\n\t\t}\n\t}\n\n\t// split scrollbar from view\n\tCUIRect Scroll;\n\tView.VSplitRight(20.0f, &View, &Scroll);\n\n\t// scrollbar background\n\tRenderTools()->DrawUIRect(&Scroll, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\t// list background\n\tRenderTools()->DrawUIRect(&View, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\t{\n\t\tint Column = COL_PING;\n\t\tswitch(g_Config.m_BrSort)\n\t\t{\n\t\t\tcase IServerBrowser::SORT_NAME:\n\t\t\t\tColumn = COL_NAME;\n\t\t\t\tbreak;\n\t\t\tcase IServerBrowser::SORT_GAMETYPE:\n\t\t\t\tColumn = COL_GAMETYPE;\n\t\t\t\tbreak;\n\t\t\tcase IServerBrowser::SORT_MAP:\n\t\t\t\tColumn = COL_MAP;\n\t\t\t\tbreak;\n\t\t\tcase IServerBrowser::SORT_NUMPLAYERS:\n\t\t\t\tColumn = COL_PLAYERS;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tCUIRect Rect = View;\n\t\tRect.x = CMenus::ms_aCols[Column].m_Rect.x;\n\t\tRect.w = CMenus::ms_aCols[Column].m_Rect.w;\n\t\tRenderTools()->DrawUIRect(&Rect, vec4(0.0f, 0.0f, 0.0f, 0.05f), CUI::CORNER_ALL, 5.0f);\n\t}\n\n\t// display important messages in the middle of the screen so no\n\t// users misses it\n\t{\n\t\tCUIRect MsgBox = View;\n\t\tMsgBox.y += View.h/3;\n\n\t\tif(m_ActivePage == PAGE_INTERNET && ServerBrowser()->IsRefreshingMasters())\n\t\t\tUI()->DoLabelScaled(&MsgBox, Localize(\"Refreshing master servers\"), 16.0f, 0);\n\t\telse if(!ServerBrowser()->NumServers())\n\t\t\tUI()->DoLabelScaled(&MsgBox, Localize(\"No servers found\"), 16.0f, 0);\n\t\t/*else if(ServerBrowser()->NumServers() && !NumServers)\n\t\t\tUI()->DoLabelScaled(&MsgBox, Localize(\"No servers match your filter criteria\"), 16.0f, 0);*/\n\t}\n\n\t// count all the servers\n\tint NumServers = 0;\n\tfor(int i = 0; i < m_lFilters.size(); i++)\n\t\tif(m_lFilters[i].Extended())\n\t\t\tNumServers += m_lFilters[i].NumSortedServers();\n\n\tint NumFilters = m_lFilters.size();\n\tfloat ListHeight = (NumServers+(NumFilters-1)) * ms_aCols[0].m_Rect.h + NumFilters * 20.0f;\n\n\t//int Num = (int)((ListHeight-View.h)/ms_aCols[0].m_Rect.h))+1;\n\t//int Num = (int)(View.h/ms_aCols[0].m_Rect.h) + 1;\n\tstatic int s_ScrollBar = 0;\n\tstatic float s_ScrollValue = 0;\n\n\tScroll.HMargin(5.0f, &Scroll);\n\ts_ScrollValue = DoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue);\n\n\tint ScrollNum = (int)((ListHeight-View.h)/ms_aCols[0].m_Rect.h)+1;\n\tif(ScrollNum > 0)\n\t{\n\t\tif(m_ScrollOffset)\n\t\t{\n\t\t\ts_ScrollValue = (float)(m_ScrollOffset)/ScrollNum;\n\t\t\tm_ScrollOffset = 0;\n\t\t}\n\t\tif(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP) && UI()->MouseInside(&View))\n\t\t\ts_ScrollValue -= 3.0f/ScrollNum;\n\t\tif(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN) && UI()->MouseInside(&View))\n\t\t\ts_ScrollValue += 3.0f/ScrollNum;\n\t}\n\telse\n\t\tScrollNum = 0;\n\n\tint SelectedFilter = m_SelectedServer.m_Filter;\n\tint SelectedIndex = m_SelectedServer.m_Index;\n\tif(SelectedFilter > -1)\n\t{\n\t\tfor(int i = 0; i < m_NumInputEvents; i++)\n\t\t{\n\t\t\tint NewIndex = -1;\n\t\t\tint NewFilter = SelectedFilter;\n\t\t\tif(m_aInputEvents[i].m_Flags&IInput::FLAG_PRESS)\n\t\t\t{\n\t\t\t\tif(m_aInputEvents[i].m_Key == KEY_DOWN)\n\t\t\t\t{\n\t\t\t\t\tNewIndex = SelectedIndex + 1;\n\t\t\t\t\tif(NewIndex >= m_lFilters[SelectedFilter].NumSortedServers())\n\t\t\t\t\t{\n\t\t\t\t\t\t// try to move to next filter\n\t\t\t\t\t\tfor(int j = SelectedFilter+1; j < m_lFilters.size(); j++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tCBrowserFilter *pFilter = &m_lFilters[j];\n\t\t\t\t\t\t\tif(pFilter->Extended() && pFilter->NumSortedServers())\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tNewFilter = j;\n\t\t\t\t\t\t\t\tNewIndex = 0;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if(m_aInputEvents[i].m_Key == KEY_UP)\n\t\t\t\t{\n\t\t\t\t\tNewIndex = SelectedIndex - 1;\n\t\t\t\t\tif(NewIndex < 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t// try to move to prev filter\n\t\t\t\t\t\tfor(int j = SelectedFilter-1; j >= 0; j--)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tCBrowserFilter *pFilter = &m_lFilters[j];\n\t\t\t\t\t\t\tif(pFilter->Extended() && pFilter->NumSortedServers())\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tNewFilter = j;\n\t\t\t\t\t\t\t\tNewIndex = pFilter->NumSortedServers()-1;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(NewIndex > -1 && NewIndex < m_lFilters[NewFilter].NumSortedServers())\n\t\t\t{\n\t\t\t\t// get index depending on all filters\n\t\t\t\tint TotalIndex = 0;\n\t\t\t\tint Filter = 0;\n\t\t\t\twhile(Filter != NewFilter)\n\t\t\t\t{\n\t\t\t\t\tCBrowserFilter *pFilter = &m_lFilters[Filter];\n\t\t\t\t\tif(pFilter->Extended())\n\t\t\t\t\t\tTotalIndex += m_lFilters[Filter].NumSortedServers();\n\t\t\t\t\tFilter++;\n\t\t\t\t}\n\t\t\t\tTotalIndex += NewIndex+1;\n\n\t\t\t\t//scroll\n\t\t\t\tfloat IndexY = View.y - s_ScrollValue*ScrollNum*ms_aCols[0].m_Rect.h + TotalIndex*ms_aCols[0].m_Rect.h + Filter*ms_aCols[0].m_Rect.h + Filter*20.0f;\n\t\t\t\tint Scroll = View.y > IndexY ? -1 : View.y+View.h < IndexY+ms_aCols[0].m_Rect.h ? 1 : 0;\n\t\t\t\tif(Scroll)\n\t\t\t\t{\n\t\t\t\t\tif(Scroll < 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tint NumScrolls = (View.y-IndexY+ms_aCols[0].m_Rect.h-1.0f)/ms_aCols[0].m_Rect.h;\n\t\t\t\t\t\ts_ScrollValue -= (1.0f/ScrollNum)*NumScrolls;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tint NumScrolls = (IndexY+ms_aCols[0].m_Rect.h-(View.y+View.h)+ms_aCols[0].m_Rect.h-1.0f)/ms_aCols[0].m_Rect.h;\n\t\t\t\t\t\ts_ScrollValue += (1.0f/ScrollNum)*NumScrolls;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tm_SelectedServer.m_Filter = NewFilter;\n\t\t\t\tm_SelectedServer.m_Index = NewIndex;\n\n\t\t\t\tconst CServerInfo *pItem = ServerBrowser()->SortedGet(NewFilter, NewIndex);\n\t\t\t\tstr_copy(g_Config.m_UiServerAddress, pItem->m_aAddress, sizeof(g_Config.m_UiServerAddress));\n\t\t\t}\n\t\t}\n\t}\n\n\tif(s_ScrollValue < 0) s_ScrollValue = 0;\n\tif(s_ScrollValue > 1) s_ScrollValue = 1;\n\n\t// set clipping\n\tUI()->ClipEnable(&View);\n\n\tCUIRect OriginalView = View;\n\tView.y -= s_ScrollValue*ScrollNum*ms_aCols[0].m_Rect.h;\n\n\tint NumPlayers = ServerBrowser()->NumPlayers();\n\n\t// reset friend counter\n\tfor(int i = 0; i < m_lFriends.size(); m_lFriends[i++].m_NumFound = 0);\n\n\tfor(int s = 0; s < m_lFilters.size(); s++)\n\t{\n\t\tCBrowserFilter *pFilter = &m_lFilters[s];\n\n\t\t// dont do anything if the filter is empty\n\t\tif(!pFilter->NumSortedServers())\n\t\t\tcontinue;\n\n\t\t// filter header\n\t\tCUIRect Row;\n\t\tView.HSplitTop(20.0f, &Row, &View);\n\n\t\t// render header\n\t\tbool Deleted = RenderFilterHeader(Row, s);\n\t\tif(Deleted && s >= m_lFilters.size())\n\t\t\tbreak;\n\n\t\tif(pFilter->Extended())\n\t\t{\n\t\t\tfor (int i = 0; i < pFilter->NumSortedServers(); i++)\n\t\t\t{\n\t\t\t\tint ItemIndex = i;\n\t\t\t\tconst CServerInfo *pItem = pFilter->SortedGet(ItemIndex);\n\t\t\t\t\n\t\t\t\tCUIRect SelectHitBox;\n\n\t\t\t\tView.HSplitTop(ms_ListheaderHeight, &Row, &View);\n\t\t\t\tSelectHitBox = Row;\n\n\t\t\t\t// select server\n\t\t\t\tif(m_SelectedServer.m_Filter == -1 || m_SelectedServer.m_Filter == s)\n\t\t\t\t{\n\t\t\t\t\tif(!str_comp(pItem->m_aAddress, g_Config.m_UiServerAddress))\n\t\t\t\t\t{\n\t\t\t\t\t\tm_SelectedServer.m_Filter = s;\n\t\t\t\t\t\tm_SelectedServer.m_Index = ItemIndex;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// make sure that only those in view can be selected\n\t\t\t\tif(Row.y+Row.h > OriginalView.y && Row.y < OriginalView.y+OriginalView.h)\n\t\t\t\t{\n\t\t\t\t\tif(m_SelectedServer.m_Filter == s && m_SelectedServer.m_Index == i)\n\t\t\t\t\t{\n\t\t\t\t\t\tCUIRect r = Row;\n\t\t\t\t\t\tRenderTools()->DrawUIRect(&r, vec4(1.0f, 1.0f, 1.0f, 0.5f), CUI::CORNER_ALL, 4.0f);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// reset active item, if not visible\n\t\t\t\t\tif(UI()->ActiveItem() == pItem)\n\t\t\t\t\t\tUI()->SetActiveItem(0);\n\n\t\t\t\t\t// don't render invisible items\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif(DoBrowserEntry(pFilter->ID(ItemIndex), &Row, pItem, m_SelectedServer.m_Filter == s && m_SelectedServer.m_Index == i))\n\t\t\t\t{\n\t\t\t\t\tm_SelectedServer.m_Filter = s;\n\t\t\t\t\tm_SelectedServer.m_Index = i;\n\t\t\t\t\tstr_copy(g_Config.m_UiServerAddress, pItem->m_aAddress, sizeof(g_Config.m_UiServerAddress));\n\t\t\t\t\tif(Input()->MouseDoubleClick())\n\t\t\t\t\t\tClient()->Connect(g_Config.m_UiServerAddress);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t}\n\n\t\tif(s < m_lFilters.size()-1)\n\t\t\tView.HSplitTop(ms_ListheaderHeight, &Row, &View);\n\t}\n\n\tUI()->ClipDisable();\n\n\t// bottom\n\tfloat SpacingW = 3.0f;\n\tfloat ButtonWidth = (Status.w/6.0f)-(SpacingW*5.0)/6.0f;\n\n\t// cut view\n\tCUIRect Left, Label, EditBox, Button;\n\tStatus.VSplitLeft(ButtonWidth*3.0f+SpacingH*2.0f, &Left, &Status);\n\n\t// render quick search and host address\n\tLeft.HSplitTop(((ButtonHeight*3.0f+SpacingH*2.0f)-(ButtonHeight*2.0f+SpacingH))/2.0f, 0, &Left);\n\tLeft.HSplitTop(ButtonHeight, &Label, &Left);\n\tLabel.VSplitRight(ButtonWidth*2.0f+SpacingH, &Label, &EditBox);\n\tLabel.y += 2.0f;\n\tUI()->DoLabel(&Label, Localize(\"Search:\"), ButtonHeight*ms_FontmodHeight*0.8f, 0);\n\tEditBox.VSplitRight(EditBox.h, &EditBox, &Button);\n\tstatic float s_ClearOffset = 0.0f;\n\tif(DoEditBox(&g_Config.m_BrFilterString, &EditBox, g_Config.m_BrFilterString, sizeof(g_Config.m_BrFilterString), ButtonHeight*ms_FontmodHeight*0.8f, &s_ClearOffset, false, CUI::CORNER_ALL))\n\t\tClient()->ServerBrowserUpdate();\n\n\t// clear button\n\t{\n\t\tstatic int s_ClearButton = 0;\n\t\tif(DoButton_SpriteID(&s_ClearButton, IMAGE_TOOLICONS, SPRITE_TOOL_X_A, &Button, CUI::CORNER_ALL, 5.0f, false))\n\t\t{\n\t\t\tg_Config.m_BrFilterString[0] = 0;\n\t\t\tUI()->SetActiveItem(&g_Config.m_BrFilterString);\n\t\t\tClient()->ServerBrowserUpdate();\n\t\t}\n\t}\n\n\tLeft.HSplitTop(SpacingH, 0, &Left);\n\tLeft.HSplitTop(ButtonHeight, &Label, 0);\n\tLabel.VSplitRight(ButtonWidth*2.0f+SpacingH, &Label, &EditBox);\n\tLabel.y += 2.0f;\n\tUI()->DoLabel(&Label, Localize(\"Host address:\"), ButtonHeight*ms_FontmodHeight*0.8f, 0);\n\tstatic float s_AddressOffset = 0.0f;\n\tDoEditBox(&g_Config.m_UiServerAddress, &EditBox, g_Config.m_UiServerAddress, sizeof(g_Config.m_UiServerAddress), ButtonHeight*ms_FontmodHeight*0.8f, &s_AddressOffset, false, CUI::CORNER_ALL);\n\n\t// render status\n\tStatus.HSplitTop(ButtonHeight+SpacingH, 0, &Status);\n\tStatus.HSplitTop(ButtonHeight, &Status, 0);\n\tchar aBuf[128];\n\tif(ServerBrowser()->IsRefreshing())\n\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"%d%% loaded\"), ServerBrowser()->LoadingProgression());\n\telse\n\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"%d servers, %d players\"), ServerBrowser()->NumServers(), NumPlayers);\n\tStatus.y += 2.0f;\n\tUI()->DoLabel(&Status, aBuf, 14.0f, 0);\n}\n\nvoid CMenus::RenderServerbrowserFilters(CUIRect View)\n{\n\tCUIRect ServerFilter = View, FilterHeader;\n\tconst float FontSize = 12.0f;\n\tServerFilter.HSplitBottom(42.5f, &ServerFilter, 0);\n\n\t// server filter\n\tServerFilter.HSplitTop(ms_ListheaderHeight, &FilterHeader, &ServerFilter);\n\tRenderTools()->DrawUIRect(&FilterHeader, vec4(1,1,1,0.25f), CUI::CORNER_T, 4.0f);\n\tRenderTools()->DrawUIRect(&ServerFilter, vec4(0,0,0,0.15f), CUI::CORNER_B, 4.0f);\n\tUI()->DoLabelScaled(&FilterHeader, Localize(\"Server filter\"), FontSize+2.0f, 0);\n\tCUIRect Button;\n\n\tServerFilter.VSplitLeft(5.0f, 0, &ServerFilter);\n\tServerFilter.Margin(3.0f, &ServerFilter);\n\tServerFilter.VMargin(5.0f, &ServerFilter);\n\n\tServerFilter.HSplitTop(20.0f, &Button, &ServerFilter);\n\tstatic int s_BrFilterEmpty = 0;\n\tif(DoButton_CheckBox(&s_BrFilterEmpty, Localize(\"Has people playing\"), g_Config.m_BrFilterEmpty, &Button))\n\t\tg_Config.m_BrFilterEmpty ^= 1;\n\n\tServerFilter.HSplitTop(20.0f, &Button, &ServerFilter);\n\tstatic int s_BrFilterSpectators = 0;\n\tif(DoButton_CheckBox(&s_BrFilterSpectators, Localize(\"Count players only\"), g_Config.m_BrFilterSpectators, &Button))\n\t\tg_Config.m_BrFilterSpectators ^= 1;\n\n\tServerFilter.HSplitTop(20.0f, &Button, &ServerFilter);\n\tstatic int s_BrFilterFull = 0;\n\tif(DoButton_CheckBox(&s_BrFilterFull, Localize(\"Server not full\"), g_Config.m_BrFilterFull, &Button))\n\t\tg_Config.m_BrFilterFull ^= 1;\n\n\tServerFilter.HSplitTop(20.0f, &Button, &ServerFilter);\n\tstatic int s_BrFilterFriends = 0;\n\tif(DoButton_CheckBox(&s_BrFilterFriends, Localize(\"Show friends only\"), g_Config.m_BrFilterFriends, &Button))\n\t\tg_Config.m_BrFilterFriends ^= 1;\n\n\tServerFilter.HSplitTop(20.0f, &Button, &ServerFilter);\n\tstatic int s_BrFilterPw = 0;\n\tif(DoButton_CheckBox(&s_BrFilterPw, Localize(\"No password\"), g_Config.m_BrFilterPw, &Button))\n\t\tg_Config.m_BrFilterPw ^= 1;\n\n\tServerFilter.HSplitTop(20.0f, &Button, &ServerFilter);\n\tstatic int s_BrFilterCompatversion = 0;\n\tif(DoButton_CheckBox(&s_BrFilterCompatversion, Localize(\"Compatible version\"), g_Config.m_BrFilterCompatversion, &Button))\n\t\tg_Config.m_BrFilterCompatversion ^= 1;\n\n\tServerFilter.HSplitTop(20.0f, &Button, &ServerFilter);\n\tstatic int s_BrFilterPure = 0;\n\tif(DoButton_CheckBox(&s_BrFilterPure, Localize(\"Standard gametype\"), g_Config.m_BrFilterPure, &Button))\n\t\tg_Config.m_BrFilterPure ^= 1;\n\n\tServerFilter.HSplitTop(20.0f, &Button, &ServerFilter);\n\tstatic int s_BrFilterPureMap = 0;\n\tif(DoButton_CheckBox(&s_BrFilterPureMap, Localize(\"Standard map\"), g_Config.m_BrFilterPureMap, &Button))\n\t\tg_Config.m_BrFilterPureMap ^= 1;\n\n\tServerFilter.HSplitTop(20.0f, &Button, &ServerFilter);\n\tstatic int s_BrFilterGametypeStrict = 0;\n\tif(DoButton_CheckBox(&s_BrFilterGametypeStrict, Localize(\"Strict gametype filter\"), g_Config.m_BrFilterGametypeStrict, &Button))\n\t\tg_Config.m_BrFilterGametypeStrict ^= 1;\n\n\tServerFilter.HSplitTop(5.0f, 0, &ServerFilter);\n\n\tServerFilter.HSplitTop(19.0f, &Button, &ServerFilter);\n\tUI()->DoLabelScaled(&Button, Localize(\"Game types:\"), FontSize, -1);\n\tButton.VSplitRight(60.0f, 0, &Button);\n\tServerFilter.HSplitTop(3.0f, 0, &ServerFilter);\n\tstatic float Offset = 0.0f;\n\tif(DoEditBox(&g_Config.m_BrFilterGametype, &Button, g_Config.m_BrFilterGametype, sizeof(g_Config.m_BrFilterGametype), FontSize, &Offset))\n\t\tClient()->ServerBrowserUpdate();\n\n\t{\n\t\tServerFilter.HSplitTop(19.0f, &Button, &ServerFilter);\n\t\tCUIRect EditBox;\n\t\tButton.VSplitRight(60.0f, &Button, &EditBox);\n\n\t\tUI()->DoLabelScaled(&Button, Localize(\"Maximum ping:\"), FontSize, -1);\n\n\t\tchar aBuf[5];\n\t\tstr_format(aBuf, sizeof(aBuf), \"%d\", g_Config.m_BrFilterPing);\n\t\tstatic float Offset = 0.0f;\n\t\tDoEditBox(&g_Config.m_BrFilterPing, &EditBox, aBuf, sizeof(aBuf), FontSize, &Offset);\n\t\tg_Config.m_BrFilterPing = clamp(str_toint(aBuf), 0, 999);\n\t}\n\n\t// server address\n\tServerFilter.HSplitTop(3.0f, 0, &ServerFilter);\n\tServerFilter.HSplitTop(19.0f, &Button, &ServerFilter);\n\tUI()->DoLabelScaled(&Button, Localize(\"Server address:\"), FontSize, -1);\n\tButton.VSplitRight(60.0f, 0, &Button);\n\tstatic float OffsetAddr = 0.0f;\n\tif(DoEditBox(&g_Config.m_BrFilterServerAddress, &Button, g_Config.m_BrFilterServerAddress, sizeof(g_Config.m_BrFilterServerAddress), FontSize, &OffsetAddr))\n\t\tClient()->ServerBrowserUpdate();\n\n\t// player country\n\t{\n\t\tCUIRect Rect;\n\t\tServerFilter.HSplitTop(3.0f, 0, &ServerFilter);\n\t\tServerFilter.HSplitTop(26.0f, &Button, &ServerFilter);\n\t\tButton.VSplitRight(60.0f, &Button, &Rect);\n\t\tButton.HMargin(3.0f, &Button);\n\t\tstatic int s_BrFilterCountry = 0;\n\t\tif(DoButton_CheckBox(&s_BrFilterCountry, Localize(\"Player country:\"), g_Config.m_BrFilterCountry, &Button))\n\t\t\tg_Config.m_BrFilterCountry ^= 1;\n\n\t\tfloat OldWidth = Rect.w;\n\t\tRect.w = Rect.h*2;\n\t\tRect.x += (OldWidth-Rect.w)/2.0f;\n\t\tvec4 Color(1.0f, 1.0f, 1.0f, g_Config.m_BrFilterCountry?1.0f: 0.5f);\n\t\tm_pClient->m_pCountryFlags->Render(g_Config.m_BrFilterCountryIndex, &Color, Rect.x, Rect.y, Rect.w, Rect.h);\n\n\t\tif(g_Config.m_BrFilterCountry && UI()->DoButtonLogic(&g_Config.m_BrFilterCountryIndex, \"\", 0, &Rect))\n\t\t\tm_Popup = POPUP_COUNTRY;\n\t}\n\n\tServerFilter.HSplitBottom(5.0f, &ServerFilter, 0);\n\tServerFilter.HSplitBottom(ms_ButtonHeight-2.0f, &ServerFilter, &Button);\n\tstatic int s_ClearButton = 0;\n\tif(DoButton_Menu(&s_ClearButton, Localize(\"Reset filter\"), 0, &Button))\n\t{\n\t\tg_Config.m_BrFilterString[0] = 0;\n\t\tg_Config.m_BrFilterFull = 0;\n\t\tg_Config.m_BrFilterEmpty = 0;\n\t\tg_Config.m_BrFilterSpectators = 0;\n\t\tg_Config.m_BrFilterFriends = 0;\n\t\tg_Config.m_BrFilterCountry = 0;\n\t\tg_Config.m_BrFilterCountryIndex = -1;\n\t\tg_Config.m_BrFilterPw = 0;\n\t\tg_Config.m_BrFilterPing = 999;\n\t\tg_Config.m_BrFilterGametype[0] = 0;\n\t\tg_Config.m_BrFilterGametypeStrict = 0;\n\t\tg_Config.m_BrFilterServerAddress[0] = 0;\n\t\tg_Config.m_BrFilterPure = 1;\n\t\tg_Config.m_BrFilterPureMap = 1;\n\t\tg_Config.m_BrFilterCompatversion = 1;\n\t\tClient()->ServerBrowserUpdate();\n\t}\n}\n\nvoid CMenus::RenderServerbrowserServerDetail(CUIRect View, const CServerInfo *pInfo)\n{\n\tView.Margin(2.0f, &View);\n\n\tCUIRect ServerDetails = View;\n\tCUIRect ServerScoreBoard, ServerHeader;\n\n\t// split off a piece to use for scoreboard\n\tServerDetails.HSplitTop(70.0f, &ServerDetails, &ServerScoreBoard);\n\tServerDetails.HSplitBottom(2.5f, &ServerDetails, 0x0);\n\n\t// server details\n\tCTextCursor Cursor;\n\tconst float FontSize = 12.0f;\n\tServerDetails.HSplitTop(ms_ListheaderHeight, &ServerHeader, &ServerDetails);\n\tRenderTools()->DrawUIRect(&ServerHeader, vec4(1,1,1,0.25f), CUI::CORNER_T, 4.0f);\n\tRenderTools()->DrawUIRect(&ServerDetails, vec4(0,0,0,0.15f), CUI::CORNER_B, 4.0f);\n\tUI()->DoLabelScaled(&ServerHeader, Localize(\"Server details\"), FontSize+2.0f, 0);\n\n\tif(pInfo)\n\t{\n\t\tServerDetails.VSplitLeft(5.0f, 0, &ServerDetails);\n\t\tServerDetails.Margin(3.0f, &ServerDetails);\n\n\t\tCUIRect Row;\n\t\tstatic CLocConstString s_aLabels[] = {\n\t\t\t\"Version\",\t// Localize - these strings are localized within CLocConstString\n\t\t\t\"Game type\",\n\t\t\t\"Ping\"};\n\n\t\tCUIRect LeftColumn;\n\t\tCUIRect RightColumn;\n\n\t\tServerDetails.VSplitLeft(5.0f, 0x0, &ServerDetails);\n\t\tServerDetails.VSplitLeft(80.0f, &LeftColumn, &RightColumn);\n\n\t\tfor (unsigned int i = 0; i < sizeof(s_aLabels) / sizeof(s_aLabels[0]); i++)\n\t\t{\n\t\t\tLeftColumn.HSplitTop(15.0f, &Row, &LeftColumn);\n\t\t\tUI()->DoLabelScaled(&Row, s_aLabels[i], FontSize, -1);\n\t\t}\n\n\t\tRightColumn.HSplitTop(15.0f, &Row, &RightColumn);\n\t\tTextRender()->SetCursor(&Cursor, Row.x, Row.y, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\t\tCursor.m_LineWidth = Row.w;\n\t\tTextRender()->TextEx(&Cursor, pInfo->m_aVersion, -1);\n\n\t\tRightColumn.HSplitTop(15.0f, &Row, &RightColumn);\n\t\tTextRender()->SetCursor(&Cursor, Row.x, Row.y, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\t\tCursor.m_LineWidth = Row.w;\n\t\tTextRender()->TextEx(&Cursor, pInfo->m_aGameType, -1);\n\n\t\tchar aTemp[16];\n\t\tstr_format(aTemp, sizeof(aTemp), \"%d\", pInfo->m_Latency);\n\t\tRightColumn.HSplitTop(15.0f, &Row, &RightColumn);\n\t\tTextRender()->SetCursor(&Cursor, Row.x, Row.y, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\t\tCursor.m_LineWidth = Row.w;\n\t\tTextRender()->TextEx(&Cursor, aTemp, -1);\n\n\t}\n\n\tif(pInfo && pInfo->m_NumClients)\n\t{\n\t\t// server scoreboard\n\t\tServerScoreBoard.HSplitTop(ms_ListheaderHeight, &ServerHeader, &ServerScoreBoard);\n\t\tRenderTools()->DrawUIRect(&ServerHeader, vec4(1,1,1,0.25f), CUI::CORNER_T, 4.0f);\n\t\tRenderTools()->DrawUIRect(&ServerScoreBoard, vec4(0,0,0,0.15f), CUI::CORNER_B, 4.0f);\n\t\tUI()->DoLabelScaled(&ServerHeader, Localize(\"Scoreboard\"), FontSize+2.0f, 0);\n\n\t\tServerScoreBoard.Margin(3.0f, &ServerScoreBoard);\n\t\tfor (int i = 0; i < pInfo->m_NumClients; i++)\n\t\t{\n\t\t\tCUIRect Name, Clan, Score, Flag;\n\t\t\tServerScoreBoard.HSplitTop(25.0f, &Name, &ServerScoreBoard);\n\t\t\tif(UI()->DoButtonLogic(&pInfo->m_aClients[i], \"\", 0, &Name))\n\t\t\t{\n\t\t\t\tif(pInfo->m_aClients[i].m_FriendState == IFriends::FRIEND_PLAYER)\n\t\t\t\t\tm_pClient->Friends()->RemoveFriend(pInfo->m_aClients[i].m_aName, pInfo->m_aClients[i].m_aClan);\n\t\t\t\telse\n\t\t\t\t\tm_pClient->Friends()->AddFriend(pInfo->m_aClients[i].m_aName, pInfo->m_aClients[i].m_aClan);\n\t\t\t\tFriendlistOnUpdate();\n\t\t\t\tClient()->ServerBrowserUpdate();\n\t\t\t}\n\n\t\t\tvec4 Colour = pInfo->m_aClients[i].m_FriendState == IFriends::FRIEND_NO ? vec4(1.0f, 1.0f, 1.0f, (i%2+1)*0.05f) :\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvec4(0.5f, 1.0f, 0.5f, 0.15f+(i%2+1)*0.05f);\n\t\t\tRenderTools()->DrawUIRect(&Name, Colour, CUI::CORNER_ALL, 4.0f);\n\t\t\tName.VSplitLeft(5.0f, 0, &Name);\n\t\t\tName.VSplitLeft(30.0f, &Score, &Name);\n\t\t\tName.VSplitRight(34.0f, &Name, &Flag);\n\t\t\tFlag.HMargin(4.0f, &Flag);\n\t\t\tName.HSplitTop(11.0f, &Name, &Clan);\n\n\t\t\t// score\n\t\t\tif(pInfo->m_aClients[i].m_Player)\n\t\t\t{\n\t\t\t\tchar aTemp[16];\n\t\t\t\tstr_format(aTemp, sizeof(aTemp), \"%d\", pInfo->m_aClients[i].m_Score);\n\t\t\t\tTextRender()->SetCursor(&Cursor, Score.x, Score.y+(Score.h-FontSize)/4.0f, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\t\t\t\tCursor.m_LineWidth = Score.w;\n\t\t\t\tTextRender()->TextEx(&Cursor, aTemp, -1);\n\t\t\t}\n\n\t\t\t// name\n\t\t\tTextRender()->SetCursor(&Cursor, Name.x, Name.y, FontSize-2, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\t\t\tCursor.m_LineWidth = Name.w;\n\t\t\tconst char *pName = pInfo->m_aClients[i].m_aName;\n\t\t\tif(g_Config.m_BrFilterString[0])\n\t\t\t{\n\t\t\t\t// highlight the parts that matches\n\t\t\t\tconst char *s = str_find_nocase(pName, g_Config.m_BrFilterString);\n\t\t\t\tif(s)\n\t\t\t\t{\n\t\t\t\t\tTextRender()->TextEx(&Cursor, pName, (int)(s-pName));\n\t\t\t\t\tTextRender()->TextColor(0.4f, 0.4f, 1.0f, 1.0f);\n\t\t\t\t\tTextRender()->TextEx(&Cursor, s, str_length(g_Config.m_BrFilterString));\n\t\t\t\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\t\t\tTextRender()->TextEx(&Cursor, s+str_length(g_Config.m_BrFilterString), -1);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tTextRender()->TextEx(&Cursor, pName, -1);\n\t\t\t}\n\t\t\telse\n\t\t\t\tTextRender()->TextEx(&Cursor, pName, -1);\n\n\t\t\t// clan\n\t\t\tTextRender()->SetCursor(&Cursor, Clan.x, Clan.y, FontSize-2, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\t\t\tCursor.m_LineWidth = Clan.w;\n\t\t\tconst char *pClan = pInfo->m_aClients[i].m_aClan;\n\t\t\tif(g_Config.m_BrFilterString[0])\n\t\t\t{\n\t\t\t\t// highlight the parts that matches\n\t\t\t\tconst char *s = str_find_nocase(pClan, g_Config.m_BrFilterString);\n\t\t\t\tif(s)\n\t\t\t\t{\n\t\t\t\t\tTextRender()->TextEx(&Cursor, pClan, (int)(s-pClan));\n\t\t\t\t\tTextRender()->TextColor(0.4f, 0.4f, 1.0f, 1.0f);\n\t\t\t\t\tTextRender()->TextEx(&Cursor, s, str_length(g_Config.m_BrFilterString));\n\t\t\t\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\t\t\tTextRender()->TextEx(&Cursor, s+str_length(g_Config.m_BrFilterString), -1);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tTextRender()->TextEx(&Cursor, pClan, -1);\n\t\t\t}\n\t\t\telse\n\t\t\t\tTextRender()->TextEx(&Cursor, pClan, -1);\n\n\t\t\t// flag\n\t\t\tvec4 Color(1.0f, 1.0f, 1.0f, 0.5f);\n\t\t\tm_pClient->m_pCountryFlags->Render(pInfo->m_aClients[i].m_Country, &Color, Flag.x, Flag.y, Flag.w, Flag.h);\n\t\t}\n\t}\n}\n\nvoid CMenus::FriendlistOnUpdate()\n{\n\tm_lFriends.clear();\n\tfor(int i = 0; i < m_pClient->Friends()->NumFriends(); ++i)\n\t{\n\t\tCFriendItem Item;\n\t\tItem.m_pFriendInfo = m_pClient->Friends()->GetFriend(i);\n\t\tItem.m_NumFound = 0;\n\t\tm_lFriends.add_unsorted(Item);\n\t}\n\tm_lFriends.sort_range();\n}\n\nvoid CMenus::RenderServerbrowserFriends(CUIRect View)\n{\n\tstatic int s_Inited = 0;\n\tif(!s_Inited)\n\t{\n\t\tFriendlistOnUpdate();\n\t\ts_Inited = 1;\n\t}\n\n\tCUIRect ServerFriends = View, FilterHeader;\n\tconst float FontSize = 10.0f;\n\n\t// header\n\tServerFriends.HSplitTop(ms_ListheaderHeight, &FilterHeader, &ServerFriends);\n\tRenderTools()->DrawUIRect(&FilterHeader, vec4(1,1,1,0.25f), CUI::CORNER_T, 4.0f);\n\tRenderTools()->DrawUIRect(&ServerFriends, vec4(0,0,0,0.15f), 0, 4.0f);\n\tUI()->DoLabelScaled(&FilterHeader, Localize(\"Friends\"), FontSize+4.0f, 0);\n\tCUIRect Button, List;\n\n\tServerFriends.Margin(3.0f, &ServerFriends);\n\tServerFriends.VMargin(3.0f, &ServerFriends);\n\tServerFriends.HSplitBottom(100.0f, &List, &ServerFriends);\n\n\t// friends list(remove friend)\n\tstatic float s_ScrollValue = 0;\n\tstatic int s_FriendsList = 0;\n\tif(m_FriendlistSelectedIndex >= m_lFriends.size())\n\t\tm_FriendlistSelectedIndex = m_lFriends.size()-1;\n\tUiDoListboxHeader(&List, \"\", 20.0f, 2.0f);\n\tUiDoListboxStart(&s_FriendsList, 30.0f, \"\", m_lFriends.size(), 1, m_FriendlistSelectedIndex, s_ScrollValue);\n\n\tm_lFriends.sort_range();\n\tfor(int i = 0; i < m_lFriends.size(); ++i)\n\t{\n\t\tCListboxItem Item = UiDoListboxNextItem(&m_lFriends[i]);\n\n\t\tif(Item.m_Visible)\n\t\t{\n\t\t\tItem.m_Rect.Margin(1.5f, &Item.m_Rect);\n\t\t\tCUIRect OnState;\n\t\t\tItem.m_Rect.VSplitRight(30.0f, &Item.m_Rect, &OnState);\n\t\t\tRenderTools()->DrawUIRect(&Item.m_Rect, vec4(1.0f, 1.0f, 1.0f, 0.1f), CUI::CORNER_L, 4.0f);\n\n\t\t\tItem.m_Rect.VMargin(2.5f, &Item.m_Rect);\n\t\t\tItem.m_Rect.HSplitTop(12.0f, &Item.m_Rect, &Button);\n\t\t\tUI()->DoLabelScaled(&Item.m_Rect, m_lFriends[i].m_pFriendInfo->m_aName, FontSize, -1);\n\t\t\tUI()->DoLabelScaled(&Button, m_lFriends[i].m_pFriendInfo->m_aClan, FontSize, -1);\n\n\t\t\tRenderTools()->DrawUIRect(&OnState, m_lFriends[i].m_NumFound ? vec4(0.0f, 1.0f, 0.0f, 0.25f) : vec4(1.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_R, 4.0f);\n\t\t\tOnState.HMargin((OnState.h-FontSize)/3, &OnState);\n\t\t\tOnState.VMargin(5.0f, &OnState);\n\t\t\tchar aBuf[64];\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"%i\", m_lFriends[i].m_NumFound);\n\t\t\tUI()->DoLabelScaled(&OnState, aBuf, FontSize+2, 1);\n\t\t}\n\t}\n\n\tbool Activated = false;\n\tm_FriendlistSelectedIndex = UiDoListboxEnd(&s_ScrollValue, &Activated);\n\n\t// activate found server with friend\n\tif(Activated && !m_EnterPressed && m_lFriends[m_FriendlistSelectedIndex].m_NumFound)\n\t{\n\t\tbool Found = false;\n\t\tfor(int s = 0; s < m_lFilters.size(); s++)\n\t\t{\n\t\t\tCBrowserFilter *pFilter = &m_lFilters[s];\n\n\t\t\tint NumServers = pFilter->NumSortedServers();\n\t\t\tfor (int i = 0; i < NumServers && !Found; i++)\n\t\t\t{\n\t\t\t\tint ItemIndex = m_SelectedServer.m_Filter != -1 ? (m_SelectedServer.m_Index+i+1)%NumServers : i;\n\t\t\t\tconst CServerInfo *pItem = pFilter->SortedGet(ItemIndex);\n\t\t\t\tif(pItem->m_FriendState != IFriends::FRIEND_NO)\n\t\t\t\t{\n\t\t\t\t\tfor(int j = 0; j < pItem->m_NumClients && !Found; ++j)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(pItem->m_aClients[j].m_FriendState != IFriends::FRIEND_NO &&\n\t\t\t\t\t\t\tstr_quickhash(pItem->m_aClients[j].m_aClan) == m_lFriends[m_FriendlistSelectedIndex].m_pFriendInfo->m_ClanHash &&\n\t\t\t\t\t\t\t(!m_lFriends[m_FriendlistSelectedIndex].m_pFriendInfo->m_aName[0] ||\n\t\t\t\t\t\t\tstr_quickhash(pItem->m_aClients[j].m_aName) == m_lFriends[m_FriendlistSelectedIndex].m_pFriendInfo->m_NameHash))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstr_copy(g_Config.m_UiServerAddress, pItem->m_aAddress, sizeof(g_Config.m_UiServerAddress));\n\t\t\t\t\t\t\tm_ScrollOffset = ItemIndex;\n\t\t\t\t\t\t\tm_SelectedServer.m_Filter = s;\n\t\t\t\t\t\t\tm_SelectedServer.m_Index = ItemIndex;\n\t\t\t\t\t\t\tFound = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tServerFriends.HSplitTop(2.5f, 0, &ServerFriends);\n\tServerFriends.HSplitTop(20.0f, &Button, &ServerFriends);\n\tif(m_FriendlistSelectedIndex != -1)\n\t{\n\t\tstatic int s_RemoveButton = 0;\n\t\tif(DoButton_Menu(&s_RemoveButton, Localize(\"Remove\"), 0, &Button))\n\t\t\tm_Popup = POPUP_REMOVE_FRIEND;\n\t}\n\n\t// add friend\n\tif(m_pClient->Friends()->NumFriends() < IFriends::MAX_FRIENDS)\n\t{\n\t\tServerFriends.HSplitTop(10.0f, 0, &ServerFriends);\n\t\tServerFriends.HSplitTop(19.0f, &Button, &ServerFriends);\n\t\tchar aBuf[64];\n\t\tstr_format(aBuf, sizeof(aBuf), \"%s:\", Localize(\"Name\"));\n\t\tUI()->DoLabelScaled(&Button, aBuf, FontSize, -1);\n\t\tButton.VSplitLeft(80.0f, 0, &Button);\n\t\tstatic char s_aName[MAX_NAME_LENGTH] = {0};\n\t\tstatic float s_OffsetName = 0.0f;\n\t\tDoEditBox(&s_aName, &Button, s_aName, sizeof(s_aName), FontSize, &s_OffsetName);\n\n\t\tServerFriends.HSplitTop(3.0f, 0, &ServerFriends);\n\t\tServerFriends.HSplitTop(19.0f, &Button, &ServerFriends);\n\t\tstr_format(aBuf, sizeof(aBuf), \"%s:\", Localize(\"Clan\"));\n\t\tUI()->DoLabelScaled(&Button, aBuf, FontSize, -1);\n\t\tButton.VSplitLeft(80.0f, 0, &Button);\n\t\tstatic char s_aClan[MAX_CLAN_LENGTH] = {0};\n\t\tstatic float s_OffsetClan = 0.0f;\n\t\tDoEditBox(&s_aClan, &Button, s_aClan, sizeof(s_aClan), FontSize, &s_OffsetClan);\n\n\t\tServerFriends.HSplitTop(3.0f, 0, &ServerFriends);\n\t\tServerFriends.HSplitTop(20.0f, &Button, &ServerFriends);\n\t\tstatic int s_AddButton = 0;\n\t\tif(DoButton_Menu(&s_AddButton, Localize(\"Add Friend\"), 0, &Button))\n\t\t{\n\t\t\tm_pClient->Friends()->AddFriend(s_aName, s_aClan);\n\t\t\tFriendlistOnUpdate();\n\t\t\tClient()->ServerBrowserUpdate();\n\t\t}\n\t}\n}\n\nvoid CMenus::RenderServerbrowserBottomBox(CUIRect MainView)\n{\n\t// same size like tabs in top but variables not really needed\n\tfloat Spacing = 3.0f;\n\tfloat ButtonWidth = MainView.w/2.0f-Spacing/2.0f;\n\n\t// render background\n\tRenderTools()->DrawUIRect4(&MainView, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f);\n\n\t// back to main menu\n\tCUIRect Button;\n\tMainView.HSplitTop(25.0f, &MainView, 0);\n\tMainView.VSplitLeft(ButtonWidth, &Button, &MainView);\n\tstatic int s_RefreshButton=0;\n\tif(DoButton_Menu(&s_RefreshButton, Localize(\"Refresh\"), 0, &Button))\n\t{\n\t\tif(m_MenuPage == PAGE_INTERNET)\n\t\t\tServerBrowser()->Refresh(IServerBrowser::TYPE_INTERNET);\n\t\telse if(m_MenuPage == PAGE_LAN)\n\t\t\tServerBrowser()->Refresh(IServerBrowser::TYPE_LAN);\n\t}\n\n\tMainView.VSplitLeft(Spacing, 0, &MainView); // little space\n\tMainView.VSplitLeft(ButtonWidth, &Button, &MainView);\n\tstatic int s_JoinButton = 0;\n\tif(DoButton_Menu(&s_JoinButton, Localize(\"Connect\"), 0, &Button) || m_EnterPressed)\n\t{\n\t\tClient()->Connect(g_Config.m_UiServerAddress);\n\t\tm_EnterPressed = false;\n\t}\n}\n\nvoid CMenus::RenderServerbrowser(CUIRect MainView)\n{\n\t/*\n\t\t+---------------------------+\n\t\t|\t\t\t\t\t\t\t|\n\t\t|\t\t\t\t\t\t\t|\n\t\t|\t\tserver list\t\t\t|\n\t\t|\t\t\t\t\t\t\t|\n\t\t|---------------------------+\n\t\t| back |\t   | bottom box |\n\t\t+------+       +------------+\n\t*/\n\n\tCUIRect ServerList, BottomBox;\n\n\tMainView.HSplitTop(20.0f, 0, &MainView);\n\tMainView.HSplitBottom(80.0f, &ServerList, &MainView);\n\n\n\t// server list\n\tif(m_BorwserPage == PAGE_BROWSER_BROWSER)\n\t\tRenderServerbrowserServerList(ServerList);\n\telse if(m_BorwserPage == PAGE_BROWSER_FRIENDS)\n\t\tRenderServerbrowserFriendList(ServerList);\n\n\t/*// background\n\tRenderTools()->DrawUIRect(&MainView, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 12.0f);\n\tMainView.Margin(10.0f, &MainView);\n\n\t// create server list, status box, tab bar and tool box area\n\tMainView.VSplitRight(205.0f, &ServerList, &ToolBox);\n\tServerList.VSplitRight(5.0f, &ServerList, 0);\n\tToolBox.HSplitBottom(80.0f, &ToolBox, &ConnectBox);\n\n\t// tool box\n\t{\n\t\tRenderTools()->DrawUIRect(&ToolBox, vec4(0.0f, 0.0f, 0.0f, 0.15f), CUI::CORNER_T, 4.0f);\n\n\t\tRenderServerbrowserFilters(ToolBox);\n\t}*/\n\n\tfloat Spacing = 3.0f;\n\tfloat ButtonWidth = (MainView.w/6.0f)-(Spacing*5.0)/6.0f;\n\n\tMainView.HSplitBottom(60.0f, 0, &BottomBox);\n\tBottomBox.VSplitRight(ButtonWidth*2.0f+Spacing, 0, &BottomBox);\n\n\t// connect box\n\t{\n\t\tRenderServerbrowserBottomBox(BottomBox);\n\t}\n\n\t// back button\n\tRenderBackButton(MainView);\n\n\t// render overlay if there is any\n\tRenderServerbrowserOverlay();\n}\n\n// firend list\n\nvoid CMenus::RenderServerbrowserFriendList(CUIRect View)\n{\n\t//CUIRect Headers, Status, InfoButton;\n\n\t//float SpacingH = 2.0f;\n\t//float ButtonHeight = 20.0f;\n\n\t// background\n\tRenderTools()->DrawUIRect(&View, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n}\n\nvoid CMenus::ConchainFriendlistUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)\n{\n\tpfnCallback(pResult, pCallbackUserData);\n\tif(pResult->NumArguments() == 2 && ((CMenus *)pUserData)->Client()->State() == IClient::STATE_OFFLINE)\n\t{\n\t\t((CMenus *)pUserData)->FriendlistOnUpdate();\n\t\t((CMenus *)pUserData)->Client()->ServerBrowserUpdate();\n\t}\n}\n\nvoid CMenus::ConchainServerbrowserUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)\n{\n\tpfnCallback(pResult, pCallbackUserData);\n\t/*if(pResult->NumArguments() && ((CMenus *)pUserData)->m_MenuPage == PAGE_FAVORITES && ((CMenus *)pUserData)->Client()->State() == IClient::STATE_OFFLINE)\n\t\t((CMenus *)pUserData)->ServerBrowser()->Refresh(IServerBrowser::TYPE_FAVORITES);*/\n}\n"
  },
  {
    "path": "src/game/client/components/menus_callback.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/shared/config.h>\n\n#include \"binds.h\"\n#include \"menus.h\"\n\ntypedef struct\n{\n\tCLocConstString m_Name;\n\tconst char *m_pCommand;\n\tint m_KeyId;\n} CKeyInfo;\n\nstatic CKeyInfo gs_aKeys[] =\n{\n\t{ \"Move left\", \"+left\", 0},\t\t// Localize - these strings are localized within CLocConstString\n\t{ \"Move right\", \"+right\", 0 },\n\t{ \"Jump\", \"+jump\", 0 },\n\t{ \"Fire\", \"+fire\", 0 },\n\t{ \"Hook\", \"+hook\", 0 },\n\t{ \"Hammer\", \"+weapon1\", 0 },\n\t{ \"Pistol\", \"+weapon2\", 0 },\n\t{ \"Shotgun\", \"+weapon3\", 0 },\n\t{ \"Grenade\", \"+weapon4\", 0 },\n\t{ \"Laser\", \"+weapon5\", 0 },\n\t{ \"Next weapon\", \"+nextweapon\", 0 },\n\t{ \"Prev. weapon\", \"+prevweapon\", 0 },\n\t{ \"Vote yes\", \"vote yes\", 0 },\n\t{ \"Vote no\", \"vote no\", 0 },\n\t{ \"Chat\", \"chat all\", 0 },\n\t{ \"Team chat\", \"chat team\", 0 },\n\t{ \"Show chat\", \"+show_chat\", 0 },\n\t{ \"Emoticon\", \"+emote\", 0 },\n\t{ \"Spectator mode\", \"+spectate\", 0 },\n\t{ \"Spectate next\", \"spectate_next\", 0 },\n\t{ \"Spectate previous\", \"spectate_previous\", 0 },\n\t{ \"Console\", \"toggle_local_console\", 0 },\n\t{ \"Remote console\", \"toggle_remote_console\", 0 },\n\t{ \"Screenshot\", \"screenshot\", 0 },\n\t{ \"Scoreboard\", \"+scoreboard\", 0 },\n\t{ \"Respawn\", \"kill\", 0 },\n\t{ \"Ready\", \"ready_change\", 0 },\n};\n\n/*\tThis is for scripts/update_localization.py to work, don't remove!\n\tLocalize(\"Move left\");Localize(\"Move right\");Localize(\"Jump\");Localize(\"Fire\");Localize(\"Hook\");Localize(\"Hammer\");\n\tLocalize(\"Pistol\");Localize(\"Shotgun\");Localize(\"Grenade\");Localize(\"Laser\");Localize(\"Next weapon\");Localize(\"Prev. weapon\");\n\tLocalize(\"Vote yes\");Localize(\"Vote no\");Localize(\"Chat\");Localize(\"Team chat\");Localize(\"Show chat\");Localize(\"Emoticon\");\n\tLocalize(\"Spectator mode\");Localize(\"Spectate next\");Localize(\"Spectate previous\");Localize(\"Console\");Localize(\"Remote console\");\n\tLocalize(\"Screenshot\");Localize(\"Scoreboard\");Localize(\"Respawn\");Localize(\"Ready\");\n*/\n\nconst int g_KeyCount = sizeof(gs_aKeys) / sizeof(CKeyInfo);\n\nvoid CMenus::UiDoGetButtons(int Start, int Stop, CUIRect View, float ButtonHeight, float Spaceing)\n{\n\tfor (int i = Start; i < Stop; i++)\n\t{\n\t\tView.HSplitTop(Spaceing, 0, &View);\n\n\t\tCKeyInfo &Key = gs_aKeys[i];\n\t\tCUIRect Button, Label;\n\t\tView.HSplitTop(ButtonHeight, &Button, &View);\n\t\tRenderTools()->DrawUIRect(&Button, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\t\tButton.VSplitMid(&Label, &Button);\n\n\t\tchar aBuf[64];\n\t\tstr_format(aBuf, sizeof(aBuf), \"%s:\", (const char *)Key.m_Name);\n\n\t\tLabel.y += 2.0f;\n\t\tUI()->DoLabelScaled(&Label, aBuf, 13.0f, 0);\n\t\tint OldId = Key.m_KeyId;\n\t\tint NewId = DoKeyReader((void *)&gs_aKeys[i].m_Name, &Button, OldId);\n\t\tif(NewId != OldId)\n\t\t{\n\t\t\tif(OldId != 0 || NewId == 0)\n\t\t\t\tm_pClient->m_pBinds->Bind(OldId, \"\");\n\t\t\tif(NewId != 0)\n\t\t\t\tm_pClient->m_pBinds->Bind(NewId, gs_aKeys[i].m_pCommand);\n\t\t}\n\t}\n}\n\nfloat CMenus::RenderSettingsControlsMovement(CUIRect View, void *pUser)\n{\n\tCMenus *pSelf = (CMenus*)pUser;\n\n\t// this is kinda slow, but whatever\n\tfor(int i = 0; i < g_KeyCount; i++)\n\t\tgs_aKeys[i].m_KeyId = 0;\n\n\tfor(int KeyId = 0; KeyId < KEY_LAST; KeyId++)\n\t{\n\t\tconst char *pBind = pSelf->m_pClient->m_pBinds->Get(KeyId);\n\t\tif(!pBind[0])\n\t\t\tcontinue;\n\n\t\tfor(int i = 0; i < g_KeyCount; i++)\n\t\t\tif(str_comp(pBind, gs_aKeys[i].m_pCommand) == 0)\n\t\t\t{\n\t\t\t\tgs_aKeys[i].m_KeyId = KeyId;\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n\n\tint NumOptions = 6;\n\tfloat ButtonHeight = 20.0f;\n\tfloat Spaceing = 2.0f;\n\tfloat BackgroundHeight = (float)NumOptions*ButtonHeight+(float)NumOptions*Spaceing;\n\n\tView.HSplitTop(BackgroundHeight, &View, 0);\n\tpSelf->RenderTools()->DrawUIRect(&View, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f);\n\n\tCUIRect Button;\n\tView.HSplitTop(Spaceing, 0, &View);\n\tView.HSplitTop(ButtonHeight, &Button, &View);\n\tpSelf->DoScrollbarOption(&g_Config.m_InpMousesens, &g_Config.m_InpMousesens, &Button, Localize(\"Mouse sens.\"), 150.0f, 5, 500);\n\n\tpSelf->UiDoGetButtons(0, 5, View, ButtonHeight, Spaceing);\n\n\treturn BackgroundHeight;\n}\n\nfloat CMenus::RenderSettingsControlsWeapon(CUIRect View, void *pUser)\n{\n\tCMenus *pSelf = (CMenus*)pUser;\n\n\t// this is kinda slow, but whatever\n\tfor(int i = 0; i < g_KeyCount; i++)\n\t\tgs_aKeys[i].m_KeyId = 0;\n\n\tfor(int KeyId = 0; KeyId < KEY_LAST; KeyId++)\n\t{\n\t\tconst char *pBind = pSelf->m_pClient->m_pBinds->Get(KeyId);\n\t\tif(!pBind[0])\n\t\t\tcontinue;\n\n\t\tfor(int i = 0; i < g_KeyCount; i++)\n\t\t\tif(str_comp(pBind, gs_aKeys[i].m_pCommand) == 0)\n\t\t\t{\n\t\t\t\tgs_aKeys[i].m_KeyId = KeyId;\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n\n\tint NumOptions = 7;\n\tfloat ButtonHeight = 20.0f;\n\tfloat Spaceing = 2.0f;\n\tfloat BackgroundHeight = (float)NumOptions*ButtonHeight+(float)NumOptions*Spaceing;\n\n\tView.HSplitTop(BackgroundHeight, &View, 0);\n\tpSelf->RenderTools()->DrawUIRect(&View, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f);\n\n\tpSelf->UiDoGetButtons(5, 12, View, ButtonHeight, Spaceing);\n\n\treturn BackgroundHeight;\n}\n\nfloat CMenus::RenderSettingsControlsVoting(CUIRect View, void *pUser)\n{\n\tCMenus *pSelf = (CMenus*)pUser;\n\n\t// this is kinda slow, but whatever\n\tfor(int i = 0; i < g_KeyCount; i++)\n\t\tgs_aKeys[i].m_KeyId = 0;\n\n\tfor(int KeyId = 0; KeyId < KEY_LAST; KeyId++)\n\t{\n\t\tconst char *pBind = pSelf->m_pClient->m_pBinds->Get(KeyId);\n\t\tif(!pBind[0])\n\t\t\tcontinue;\n\n\t\tfor(int i = 0; i < g_KeyCount; i++)\n\t\t\tif(str_comp(pBind, gs_aKeys[i].m_pCommand) == 0)\n\t\t\t{\n\t\t\t\tgs_aKeys[i].m_KeyId = KeyId;\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n\n\tint NumOptions = 2;\n\tfloat ButtonHeight = 20.0f;\n\tfloat Spaceing = 2.0f;\n\tfloat BackgroundHeight = (float)NumOptions*ButtonHeight+(float)NumOptions*Spaceing;\n\n\tView.HSplitTop(BackgroundHeight, &View, 0);\n\tpSelf->RenderTools()->DrawUIRect(&View, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f);\n\n\tpSelf->UiDoGetButtons(12, 14, View, ButtonHeight, Spaceing);\n\n\treturn BackgroundHeight;\n}\n\nfloat CMenus::RenderSettingsControlsChat(CUIRect View, void *pUser)\n{\n\tCMenus *pSelf = (CMenus*)pUser;\n\n\t// this is kinda slow, but whatever\n\tfor(int i = 0; i < g_KeyCount; i++)\n\t\tgs_aKeys[i].m_KeyId = 0;\n\n\tfor(int KeyId = 0; KeyId < KEY_LAST; KeyId++)\n\t{\n\t\tconst char *pBind = pSelf->m_pClient->m_pBinds->Get(KeyId);\n\t\tif(!pBind[0])\n\t\t\tcontinue;\n\n\t\tfor(int i = 0; i < g_KeyCount; i++)\n\t\t\tif(str_comp(pBind, gs_aKeys[i].m_pCommand) == 0)\n\t\t\t{\n\t\t\t\tgs_aKeys[i].m_KeyId = KeyId;\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n\n\tint NumOptions = 3;\n\tfloat ButtonHeight = 20.0f;\n\tfloat Spaceing = 2.0f;\n\tfloat BackgroundHeight = (float)NumOptions*ButtonHeight+(float)NumOptions*Spaceing;\n\n\tView.HSplitTop(BackgroundHeight, &View, 0);\n\tpSelf->RenderTools()->DrawUIRect(&View, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f);\n\n\tpSelf->UiDoGetButtons(14, 17, View, ButtonHeight, Spaceing);\n\n\treturn BackgroundHeight;\n}\n\nfloat CMenus::RenderSettingsControlsMisc(CUIRect View, void *pUser)\n{\n\tCMenus *pSelf = (CMenus*)pUser;\n\n\t// this is kinda slow, but whatever\n\tfor(int i = 0; i < g_KeyCount; i++)\n\t\tgs_aKeys[i].m_KeyId = 0;\n\n\tfor(int KeyId = 0; KeyId < KEY_LAST; KeyId++)\n\t{\n\t\tconst char *pBind = pSelf->m_pClient->m_pBinds->Get(KeyId);\n\t\tif(!pBind[0])\n\t\t\tcontinue;\n\n\t\tfor(int i = 0; i < g_KeyCount; i++)\n\t\t\tif(str_comp(pBind, gs_aKeys[i].m_pCommand) == 0)\n\t\t\t{\n\t\t\t\tgs_aKeys[i].m_KeyId = KeyId;\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n\n\tint NumOptions = 9;\n\tfloat ButtonHeight = 20.0f;\n\tfloat Spaceing = 2.0f;\n\tfloat BackgroundHeight = (float)NumOptions*ButtonHeight+(float)NumOptions*Spaceing;\n\n\tView.HSplitTop(BackgroundHeight, &View, 0);\n\tpSelf->RenderTools()->DrawUIRect(&View, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f);\n\n\tpSelf->UiDoGetButtons(17, 26, View, ButtonHeight, Spaceing);\n\n\treturn BackgroundHeight;\n}"
  },
  {
    "path": "src/game/client/components/menus_demo.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n\n#include <base/math.h>\n\n#include <engine/demo.h>\n#include <engine/keys.h>\n#include <engine/graphics.h>\n#include <engine/textrender.h>\n#include <engine/storage.h>\n\n#include <game/client/render.h>\n#include <game/client/gameclient.h>\n\n#include <game/client/ui.h>\n\n#include <game/generated/client_data.h>\n\n#include \"maplayers.h\"\n#include \"menus.h\"\n\nint CMenus::DoButton_DemoPlayer(const void *pID, const char *pText, const CUIRect *pRect)\n{\n\tfloat Seconds = 0.6f; //  0.6 seconds for fade\n\tfloat *pFade = ButtonFade(pID, Seconds);\n\n\tRenderTools()->DrawUIRect(pRect, vec4(1,1,1, 0.5f+(*pFade/Seconds)*0.25f), CUI::CORNER_ALL, 5.0f);\n\tUI()->DoLabel(pRect, pText, 14.0f, 0);\n\treturn UI()->DoButtonLogic(pID, pText, false, pRect);\n}\n\nvoid CMenus::RenderDemoPlayer(CUIRect MainView)\n{\n\tconst IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo();\n\n\tconst float SeekBarHeight = 15.0f;\n\tconst float ButtonbarHeight = 20.0f;\n\tconst float NameBarHeight = 20.0f;\n\tconst float Margins = 5.0f;\n\tfloat TotalHeight;\n\n\tif(m_MenuActive)\n\t\tTotalHeight = SeekBarHeight+ButtonbarHeight+NameBarHeight+Margins*3;\n\telse\n\t\tTotalHeight = SeekBarHeight+Margins*2;\n\n\tMainView.HSplitBottom(TotalHeight, 0, &MainView);\n\tMainView.VSplitLeft(50.0f, 0, &MainView);\n\tMainView.VSplitRight(450.0f, &MainView, 0);\n\n\tRenderTools()->DrawUIRect(&MainView, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_T, 10.0f);\n\n\tMainView.Margin(5.0f, &MainView);\n\n\tCUIRect SeekBar, ButtonBar, NameBar;\n\n\tint CurrentTick = pInfo->m_CurrentTick - pInfo->m_FirstTick;\n\tint TotalTicks = pInfo->m_LastTick - pInfo->m_FirstTick;\n\n\tif(m_MenuActive)\n\t{\n\t\tMainView.HSplitTop(SeekBarHeight, &SeekBar, &ButtonBar);\n\t\tButtonBar.HSplitTop(Margins, 0, &ButtonBar);\n\t\tButtonBar.HSplitBottom(NameBarHeight, &ButtonBar, &NameBar);\n\t\tNameBar.HSplitTop(4.0f, 0, &NameBar);\n\t}\n\telse\n\t\tSeekBar = MainView;\n\n\t// do seekbar\n\t{\n\t\tstatic int s_SeekBarID = 0;\n\t\tvoid *id = &s_SeekBarID;\n\t\tchar aBuffer[128];\n\n\t\t// draw seek bar\n\t\tRenderTools()->DrawUIRect(&SeekBar, vec4(0,0,0,0.5f), CUI::CORNER_ALL, 5.0f);\n\n\t\t// draw filled bar\n\t\tfloat Amount = CurrentTick/(float)TotalTicks;\n\t\tCUIRect FilledBar = SeekBar;\n\t\tFilledBar.w = 10.0f + (FilledBar.w-10.0f)*Amount;\n\t\tRenderTools()->DrawUIRect(&FilledBar, vec4(1,1,1,0.5f), CUI::CORNER_ALL, 5.0f);\n\n\t\t// draw markers\n\t\tfor(int i = 0; i < pInfo->m_NumTimelineMarkers; i++)\n\t\t{\n\t\t\tfloat Ratio = (pInfo->m_aTimelineMarkers[i]-pInfo->m_FirstTick) / (float)TotalTicks;\n\t\t\tGraphics()->TextureClear();\n\t\t\tGraphics()->QuadsBegin();\n\t\t\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\tIGraphics::CQuadItem QuadItem(SeekBar.x + (SeekBar.w-10.0f)*Ratio, SeekBar.y, UI()->PixelSize(), SeekBar.h);\n\t\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t\t\tGraphics()->QuadsEnd();\n\t\t}\n\n\t\t// draw time\n\t\tstr_format(aBuffer, sizeof(aBuffer), \"%d:%02d / %d:%02d\",\n\t\t\tCurrentTick/SERVER_TICK_SPEED/60, (CurrentTick/SERVER_TICK_SPEED)%60,\n\t\t\tTotalTicks/SERVER_TICK_SPEED/60, (TotalTicks/SERVER_TICK_SPEED)%60);\n\t\tUI()->DoLabel(&SeekBar, aBuffer, SeekBar.h*0.70f, 0);\n\n\t\t// do the logic\n\t\tint Inside = UI()->MouseInside(&SeekBar);\n\n\t\tif(UI()->ActiveItem() == id)\n\t\t{\n\t\t\tif(!UI()->MouseButton(0))\n\t\t\t\tUI()->SetActiveItem(0);\n\t\t\telse\n\t\t\t{\n\t\t\t\tstatic float PrevAmount = 0.0f;\n\t\t\t\tfloat Amount = (UI()->MouseX()-SeekBar.x)/(float)SeekBar.w;\n\t\t\t\tif(Amount > 0.0f && Amount < 1.0f && absolute(PrevAmount-Amount) >= 0.01f)\n\t\t\t\t{\n\t\t\t\t\tPrevAmount = Amount;\n\t\t\t\t\tm_pClient->OnReset();\n\t\t\t\t\tm_pClient->m_SuppressEvents = true;\n\t\t\t\t\tDemoPlayer()->SetPos(Amount);\n\t\t\t\t\tm_pClient->m_SuppressEvents = false;\n\t\t\t\t\tm_pClient->m_pMapLayersBackGround->EnvelopeUpdate();\n\t\t\t\t\tm_pClient->m_pMapLayersForeGround->EnvelopeUpdate();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if(UI()->HotItem() == id)\n\t\t{\n\t\t\tif(UI()->MouseButton(0))\n\t\t\t\tUI()->SetActiveItem(id);\n\t\t}\n\n\t\tif(Inside)\n\t\t\tUI()->SetHotItem(id);\n\t}\n\n\tif(CurrentTick == TotalTicks)\n\t{\n\t\tm_pClient->OnReset();\n\t\tDemoPlayer()->Pause();\n\t\tDemoPlayer()->SetPos(0);\n\t}\n\n\tbool IncreaseDemoSpeed = false, DecreaseDemoSpeed = false;\n\n\tif(m_MenuActive)\n\t{\n\t\t// do buttons\n\t\tCUIRect Button;\n\n\t\t// combined play and pause button\n\t\tButtonBar.VSplitLeft(ButtonbarHeight, &Button, &ButtonBar);\n\t\tstatic int s_PlayPauseButton = 0;\n\t\tif(!pInfo->m_Paused)\n\t\t{\n\t\t\tif(DoButton_SpriteID(&s_PlayPauseButton, IMAGE_DEMOBUTTONS, SPRITE_DEMOBUTTON_PAUSE, &Button, CUI::CORNER_ALL))\n\t\t\t\tDemoPlayer()->Pause();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(DoButton_SpriteID(&s_PlayPauseButton, IMAGE_DEMOBUTTONS, SPRITE_DEMOBUTTON_PLAY, &Button, CUI::CORNER_ALL))\n\t\t\t\tDemoPlayer()->Unpause();\n\t\t}\n\n\t\t// stop button\n\n\t\tButtonBar.VSplitLeft(Margins, 0, &ButtonBar);\n\t\tButtonBar.VSplitLeft(ButtonbarHeight, &Button, &ButtonBar);\n\t\tstatic int s_ResetButton = 0;\n\t\tif(DoButton_SpriteID(&s_ResetButton, IMAGE_DEMOBUTTONS, SPRITE_DEMOBUTTON_STOP, &Button, CUI::CORNER_ALL))\n\t\t{\n\t\t\tm_pClient->OnReset();\n\t\t\tDemoPlayer()->Pause();\n\t\t\tDemoPlayer()->SetPos(0);\n\t\t}\n\n\t\t// slowdown\n\t\tButtonBar.VSplitLeft(Margins, 0, &ButtonBar);\n\t\tButtonBar.VSplitLeft(ButtonbarHeight, &Button, &ButtonBar);\n\t\tstatic int s_SlowDownButton = 0;\n\t\tif(DoButton_SpriteID(&s_SlowDownButton, IMAGE_DEMOBUTTONS, SPRITE_DEMOBUTTON_SLOWER, &Button, CUI::CORNER_ALL) || Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN))\n\t\t\tDecreaseDemoSpeed = true;\n\n\t\t// fastforward\n\t\tButtonBar.VSplitLeft(Margins, 0, &ButtonBar);\n\t\tButtonBar.VSplitLeft(ButtonbarHeight, &Button, &ButtonBar);\n\t\tstatic int s_FastForwardButton = 0;\n\t\tif(DoButton_SpriteID(&s_FastForwardButton, IMAGE_DEMOBUTTONS, SPRITE_DEMOBUTTON_FASTER, &Button, CUI::CORNER_ALL))\n\t\t\tIncreaseDemoSpeed = true;\n\n\t\t// speed meter\n\t\tButtonBar.VSplitLeft(Margins*3, 0, &ButtonBar);\n\t\tchar aBuffer[64];\n\t\tif(pInfo->m_Speed >= 1.0f)\n\t\t\tstr_format(aBuffer, sizeof(aBuffer), \"x%.0f\", pInfo->m_Speed);\n\t\telse\n\t\t\tstr_format(aBuffer, sizeof(aBuffer), \"x%.2f\", pInfo->m_Speed);\n\t\tUI()->DoLabel(&ButtonBar, aBuffer, Button.h*0.7f, -1);\n\n\t\t// close button\n\t\tButtonBar.VSplitRight(ButtonbarHeight*3, &ButtonBar, &Button);\n\t\tstatic int s_ExitButton = 0;\n\t\tif(DoButton_DemoPlayer(&s_ExitButton, Localize(\"Close\"), &Button))\n\t\t\tClient()->Disconnect();\n\n\t\t// demo name\n\t\tchar aDemoName[64] = {0};\n\t\tDemoPlayer()->GetDemoName(aDemoName, sizeof(aDemoName));\n\t\tchar aBuf[128];\n\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"Demofile: %s\"), aDemoName);\n\t\tCTextCursor Cursor;\n\t\tTextRender()->SetCursor(&Cursor, NameBar.x, NameBar.y, Button.h*0.5f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\t\tCursor.m_LineWidth = MainView.w;\n\t\tTextRender()->TextEx(&Cursor, aBuf, -1);\n\t}\n\n\tif(IncreaseDemoSpeed || Input()->KeyPresses(KEY_MOUSE_WHEEL_UP))\n\t{\n\t\tif(pInfo->m_Speed < 0.1f) DemoPlayer()->SetSpeed(0.1f);\n\t\telse if(pInfo->m_Speed < 0.25f) DemoPlayer()->SetSpeed(0.25f);\n\t\telse if(pInfo->m_Speed < 0.5f) DemoPlayer()->SetSpeed(0.5f);\n\t\telse if(pInfo->m_Speed < 0.75f) DemoPlayer()->SetSpeed(0.75f);\n\t\telse if(pInfo->m_Speed < 1.0f) DemoPlayer()->SetSpeed(1.0f);\n\t\telse if(pInfo->m_Speed < 2.0f) DemoPlayer()->SetSpeed(2.0f);\n\t\telse if(pInfo->m_Speed < 4.0f) DemoPlayer()->SetSpeed(4.0f);\n\t\telse DemoPlayer()->SetSpeed(8.0f);\n\t}\n\telse if(DecreaseDemoSpeed || Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN))\n\t{\n\t\tif(pInfo->m_Speed > 4.0f) DemoPlayer()->SetSpeed(4.0f);\n\t\telse if(pInfo->m_Speed > 2.0f) DemoPlayer()->SetSpeed(2.0f);\n\t\telse if(pInfo->m_Speed > 1.0f) DemoPlayer()->SetSpeed(1.0f);\n\t\telse if(pInfo->m_Speed > 0.75f) DemoPlayer()->SetSpeed(0.75f);\n\t\telse if(pInfo->m_Speed > 0.5f) DemoPlayer()->SetSpeed(0.5f);\n\t\telse if(pInfo->m_Speed > 0.25f) DemoPlayer()->SetSpeed(0.25f);\n\t\telse if(pInfo->m_Speed > 0.1f) DemoPlayer()->SetSpeed(0.1f);\n\t\telse DemoPlayer()->SetSpeed(0.05f);\n\t}\n}\n\nint CMenus::DemolistFetchCallback(const char *pName, int IsDir, int StorageType, void *pUser)\n{\n\tCMenus *pSelf = (CMenus *)pUser;\n\tint Length = str_length(pName);\n\tif((pName[0] == '.' && (pName[1] == 0 ||\n\t\t(pName[1] == '.' && pName[2] == 0 && !str_comp(pSelf->m_aCurrentDemoFolder, \"demos\")))) ||\n\t\t(!IsDir && (Length < 5 || str_comp(pName+Length-5, \".demo\"))))\n\t\treturn 0;\n\n\tCDemoItem Item;\n\tstr_copy(Item.m_aFilename, pName, sizeof(Item.m_aFilename));\n\tif(IsDir)\n\t{\n\t\tstr_format(Item.m_aName, sizeof(Item.m_aName), \"%s/\", pName);\n\t\tItem.m_Valid = false;\n\t}\n\telse\n\t{\n\t\tstr_copy(Item.m_aName, pName, min(static_cast<int>(sizeof(Item.m_aName)), Length-4));\n\t\tItem.m_InfosLoaded = false;\n\t}\n\tItem.m_IsDir = IsDir != 0;\n\tItem.m_StorageType = StorageType;\n\tpSelf->m_lDemos.add_unsorted(Item);\n\n\treturn 0;\n}\n\nvoid CMenus::DemolistPopulate()\n{\n\tm_lDemos.clear();\n\tif(!str_comp(m_aCurrentDemoFolder, \"demos\"))\n\t\tm_DemolistStorageType = IStorage::TYPE_ALL;\n\tStorage()->ListDirectory(m_DemolistStorageType, m_aCurrentDemoFolder, DemolistFetchCallback, this);\n\tm_lDemos.sort_range();\n}\n\nvoid CMenus::DemolistOnUpdate(bool Reset)\n{\n\tm_DemolistSelectedIndex = Reset ? m_lDemos.size() > 0 ? 0 : -1 :\n\t\t\t\t\t\t\t\t\t\tm_DemolistSelectedIndex >= m_lDemos.size() ? m_lDemos.size()-1 : m_DemolistSelectedIndex;\n\tm_DemolistSelectedIsDir = m_DemolistSelectedIndex < 0 ? false : m_lDemos[m_DemolistSelectedIndex].m_IsDir;\n}\n\nvoid CMenus::RenderDemoList(CUIRect MainView)\n{\n\tCUIRect BottomView;\n\tMainView.HSplitTop(20.0f, 0, &MainView);\n\n\t// back button\n\tRenderBackButton(MainView);\n\n\t// cut view\n\tMainView.HSplitBottom(80.0f, &MainView, &BottomView);\n\tBottomView.HSplitTop(20.f, 0, &BottomView);\n\n\tstatic int s_Inited = 0;\n\tif(!s_Inited)\n\t{\n\t\tDemolistPopulate();\n\t\tDemolistOnUpdate(true);\n\t\ts_Inited = 1;\n\t}\n\n\tchar aFooterLabel[128] = {0};\n\tif(m_DemolistSelectedIndex >= 0)\n\t{\n\t\tCDemoItem *Item = &m_lDemos[m_DemolistSelectedIndex];\n\t\tif(str_comp(Item->m_aFilename, \"..\") == 0)\n\t\t\tstr_copy(aFooterLabel, Localize(\"Parent Folder\"), sizeof(aFooterLabel));\n\t\telse if(m_DemolistSelectedIsDir)\n\t\t\tstr_copy(aFooterLabel, Localize(\"Folder\"), sizeof(aFooterLabel));\n\t\telse\n\t\t{\n\t\t\tif(!Item->m_InfosLoaded)\n\t\t\t{\n\t\t\t\tchar aBuffer[512];\n\t\t\t\tstr_format(aBuffer, sizeof(aBuffer), \"%s/%s\", m_aCurrentDemoFolder, Item->m_aFilename);\n\t\t\t\tItem->m_Valid = DemoPlayer()->GetDemoInfo(Storage(), aBuffer, Item->m_StorageType, &Item->m_Info);\n\t\t\t\tItem->m_InfosLoaded = true;\n\t\t\t}\n\t\t\tif(!Item->m_Valid)\n\t\t\t\tstr_copy(aFooterLabel, Localize(\"Invalid Demo\"), sizeof(aFooterLabel));\n\t\t\telse\n\t\t\t\tstr_copy(aFooterLabel, Localize(\"Demo details\"), sizeof(aFooterLabel));\n\t\t}\n\t}\n\n\tCUIRect ListBox, Button, Label, FileIcon;\n\tMainView.HSplitTop(230.0f, &ListBox, &MainView);\n\n\tstatic int s_DemoListId = 0;\n\tstatic float s_ScrollValue = 0;\n\tUiDoListboxHeader(&ListBox, Localize(\"Recorded\"), 20.0f, 2.0f);\n\tUiDoListboxStart(&s_DemoListId, 20.0f, 0, m_lDemos.size(), 1, m_DemolistSelectedIndex, s_ScrollValue);\n\tfor(sorted_array<CDemoItem>::range r = m_lDemos.all(); !r.empty(); r.pop_front())\n\t{\n\t\tCListboxItem Item = UiDoListboxNextItem((void*)(&r.front()));\n\t\tif(Item.m_Visible)\n\t\t{\n\t\t\tItem.m_Rect.VSplitLeft(Item.m_Rect.h, &FileIcon, &Item.m_Rect);\n\t\t\tItem.m_Rect.VSplitLeft(5.0f, 0, &Item.m_Rect);\n\t\t\tFileIcon.Margin(3.0f, &FileIcon);\n\t\t\tFileIcon.x += 3.0f;\n\t\t\tDoIcon(IMAGE_FILEICONS, r.front().m_IsDir?SPRITE_FILE_FOLDER:SPRITE_FILE_DEMO1, &FileIcon);\n\t\t\tif(!str_comp(m_lDemos[m_DemolistSelectedIndex].m_aName, r.front().m_aName))\n\t\t\t{\n\t\t\t\tTextRender()->TextColor(0.0f, 0.0f, 0.0f, 1.0f);\n\t\t\t\tTextRender()->TextOutlineColor(1.0f, 1.0f, 1.0f, 0.25f);\n\t\t\t\tItem.m_Rect.y += 2.0f;\n\t\t\t\tUI()->DoLabel(&Item.m_Rect, r.front().m_aName, Item.m_Rect.h*ms_FontmodHeight*0.8f, 0);\n\t\t\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\t\tTextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tItem.m_Rect.y += 2.0f;\n\t\t\t\tUI()->DoLabel(&Item.m_Rect, r.front().m_aName, Item.m_Rect.h*ms_FontmodHeight*0.8f, 0);\n\t\t\t}\n\t\t}\n\t}\n\tbool Activated = false;\n\tm_DemolistSelectedIndex = UiDoListboxEnd(&s_ScrollValue, &Activated);\n\tDemolistOnUpdate(false);\n\n\t// render demo info\n\tint NumOptions = (!m_DemolistSelectedIsDir && m_DemolistSelectedIndex >= 0 && m_lDemos[m_DemolistSelectedIndex].m_Valid) ? 8 : 0;\n\tfloat ButtonHeight = 20.0f;\n\tfloat Spacing = 2.0f;\n\tfloat BackgroundHeight = (float)(NumOptions+1)*ButtonHeight+(float)NumOptions*Spacing;\n\n\tMainView.HSplitTop(10.0f, 0, &MainView);\n\tMainView.HSplitTop(BackgroundHeight, &MainView, 0);\n\tRenderTools()->DrawUIRect(&MainView, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\tMainView.HSplitTop(ButtonHeight, &Label, &MainView);\n\tLabel.y += 2.0f;\n\tUI()->DoLabel(&Label, aFooterLabel, ButtonHeight*ms_FontmodHeight*0.8f, 0);\n\tif(!m_DemolistSelectedIsDir && m_DemolistSelectedIndex >= 0 && m_lDemos[m_DemolistSelectedIndex].m_Valid)\n\t{\n\t\tMainView.HSplitTop(Spacing, 0, &MainView);\n\t\tMainView.HSplitTop(ButtonHeight, &Button, &MainView);\n\t\tDoInfoBox(&Button, Localize(\"Created\"), m_lDemos[m_DemolistSelectedIndex].m_Info.m_aTimestamp);\n\n\t\tMainView.HSplitTop(Spacing, 0, &MainView);\n\t\tMainView.HSplitTop(ButtonHeight, &Button, &MainView);\n\t\tDoInfoBox(&Button, Localize(\"Type\"), m_lDemos[m_DemolistSelectedIndex].m_Info.m_aType);\n\n\t\tMainView.HSplitTop(Spacing, 0, &MainView);\n\t\tMainView.HSplitTop(ButtonHeight, &Button, &MainView);\n\t\tint Length = ((m_lDemos[m_DemolistSelectedIndex].m_Info.m_aLength[0]<<24)&0xFF000000) | ((m_lDemos[m_DemolistSelectedIndex].m_Info.m_aLength[1]<<16)&0xFF0000) |\n\t\t\t\t\t((m_lDemos[m_DemolistSelectedIndex].m_Info.m_aLength[2]<<8)&0xFF00) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aLength[3]&0xFF);\n\t\tchar aBuf[64];\n\t\tstr_format(aBuf, sizeof(aBuf), \"%d:%02d\", Length/60, Length%60);\n\t\tDoInfoBox(&Button, Localize(\"Length\"), aBuf);\n\n\t\tMainView.HSplitTop(Spacing, 0, &MainView);\n\t\tMainView.HSplitTop(ButtonHeight, &Button, &MainView);\n\t\tstr_format(aBuf, sizeof(aBuf), \"%d\", m_lDemos[m_DemolistSelectedIndex].m_Info.m_Version);\n\t\tDoInfoBox(&Button, Localize(\"Version\"), aBuf);\n\n\t\tMainView.HSplitTop(Spacing, 0, &MainView);\n\t\tMainView.HSplitTop(ButtonHeight, &Button, &MainView);\n\t\tDoInfoBox(&Button, Localize(\"Netversion\"), m_lDemos[m_DemolistSelectedIndex].m_Info.m_aNetversion);\n\n\t\tMainView.HSplitTop(Spacing, 0, &MainView);\n\t\tMainView.HSplitTop(ButtonHeight, &Button, &MainView);\n\t\tDoInfoBox(&Button, Localize(\"Map\"), m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapName);\n\n\t\tMainView.HSplitTop(Spacing, 0, &MainView);\n\t\tMainView.HSplitTop(ButtonHeight, &Button, &MainView);\n\t\tButton.VSplitLeft(ButtonHeight, 0, &Button);\n\t\tfloat Size = float((m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[0]<<24) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[1]<<16) |\n\t\t\t\t\t(m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[2]<<8) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[3]))/1024.0f;\n\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"%.3f KiB\"), Size);\n\t\tDoInfoBox(&Button, Localize(\"Size\"), aBuf);\n\n\t\tMainView.HSplitTop(Spacing, 0, &MainView);\n\t\tMainView.HSplitTop(ButtonHeight, &Button, &MainView);\n\t\tButton.VSplitLeft(ButtonHeight, 0, &Button);\n\t\tunsigned Crc = (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapCrc[0]<<24) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapCrc[1]<<16) |\n\t\t\t\t\t(m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapCrc[2]<<8) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapCrc[3]);\n\t\tstr_format(aBuf, sizeof(aBuf), \"%08x\", Crc);\n\t\tDoInfoBox(&Button, Localize(\"Crc\"), aBuf);\n\t}\n\n\t// demo buttons\n\tint NumButtons = m_DemolistSelectedIsDir ? 2 : 4;\n\tSpacing = 3.0f;\n\tfloat ButtonWidth = (BottomView.w/6.0f)-(Spacing*5.0)/6.0f;\n\tfloat BackgroundWidth = ButtonWidth*(float)NumButtons+(float)(NumButtons-1)*Spacing;\n\n\tBottomView.VSplitRight(BackgroundWidth, 0, &BottomView);\n\tRenderTools()->DrawUIRect4(&BottomView, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f);\n\n\tBottomView.HSplitTop(25.0f, &BottomView, 0);\n\tBottomView.VSplitLeft(ButtonWidth, &Button, &BottomView);\n\tstatic int s_RefreshButton = 0;\n\tif(DoButton_Menu(&s_RefreshButton, Localize(\"Refresh\"), 0, &Button))\n\t{\n\t\tDemolistPopulate();\n\t\tDemolistOnUpdate(false);\n\t}\n\n\tif(!m_DemolistSelectedIsDir)\n\t{\n\t\tBottomView.VSplitLeft(Spacing, 0, &BottomView);\n\t\tBottomView.VSplitLeft(ButtonWidth, &Button, &BottomView);\n\t\tstatic int s_DeleteButton = 0;\n\t\tif(DoButton_Menu(&s_DeleteButton, Localize(\"Delete\"), 0, &Button) || m_DeletePressed)\n\t\t{\n\t\t\tif(m_DemolistSelectedIndex >= 0)\n\t\t\t{\n\t\t\t\tUI()->SetActiveItem(0);\n\t\t\t\tm_Popup = POPUP_DELETE_DEMO;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tBottomView.VSplitLeft(Spacing, 0, &BottomView);\n\t\tBottomView.VSplitLeft(ButtonWidth, &Button, &BottomView);\n\t\tstatic int s_RenameButton = 0;\n\t\tif(DoButton_Menu(&s_RenameButton, Localize(\"Rename\"), 0, &Button))\n\t\t{\n\t\t\tif(m_DemolistSelectedIndex >= 0)\n\t\t\t{\n\t\t\t\tUI()->SetActiveItem(0);\n\t\t\t\tm_Popup = POPUP_RENAME_DEMO;\n\t\t\t\tstr_copy(m_aCurrentDemoFile, m_lDemos[m_DemolistSelectedIndex].m_aFilename, sizeof(m_aCurrentDemoFile));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tBottomView.VSplitLeft(Spacing, 0, &BottomView);\n\tBottomView.VSplitLeft(ButtonWidth, &Button, &BottomView);\n\tstatic int s_PlayButton = 0;\n\tif(DoButton_Menu(&s_PlayButton, m_DemolistSelectedIsDir?Localize(\"Open\"):Localize(\"Play\", \"DemoBrowser\"), 0, &Button) || Activated)\n\t{\n\t\tif(m_DemolistSelectedIndex >= 0)\n\t\t{\n\t\t\tif(m_DemolistSelectedIsDir)\t// folder\n\t\t\t{\n\t\t\t\tif(str_comp(m_lDemos[m_DemolistSelectedIndex].m_aFilename, \"..\") == 0)\t// parent folder\n\t\t\t\t\tfs_parent_dir(m_aCurrentDemoFolder);\n\t\t\t\telse\t// sub folder\n\t\t\t\t{\n\t\t\t\t\tchar aTemp[256];\n\t\t\t\t\tstr_copy(aTemp, m_aCurrentDemoFolder, sizeof(aTemp));\n\t\t\t\t\tstr_format(m_aCurrentDemoFolder, sizeof(m_aCurrentDemoFolder), \"%s/%s\", aTemp, m_lDemos[m_DemolistSelectedIndex].m_aFilename);\n\t\t\t\t\tm_DemolistStorageType = m_lDemos[m_DemolistSelectedIndex].m_StorageType;\n\t\t\t\t}\n\t\t\t\tDemolistPopulate();\n\t\t\t\tDemolistOnUpdate(true);\n\t\t\t}\n\t\t\telse // file\n\t\t\t{\n\t\t\t\tchar aBuf[512];\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"%s/%s\", m_aCurrentDemoFolder, m_lDemos[m_DemolistSelectedIndex].m_aFilename);\n\t\t\t\tconst char *pError = Client()->DemoPlayer_Play(aBuf, m_lDemos[m_DemolistSelectedIndex].m_StorageType);\n\t\t\t\tif(pError)\n\t\t\t\t\tPopupMessage(Localize(\"Error loading demo\"), pError, Localize(\"Ok\"));\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tUI()->SetActiveItem(0);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "src/game/client/components/menus_ingame.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/math.h>\n\n#include <engine/config.h>\n#include <engine/demo.h>\n#include <engine/friends.h>\n#include <engine/graphics.h>\n#include <engine/serverbrowser.h>\n#include <engine/textrender.h>\n#include <engine/shared/config.h>\n\n#include <game/generated/protocol.h>\n#include <game/generated/client_data.h>\n\n#include <game/client/animstate.h>\n#include <game/client/gameclient.h>\n#include <game/client/render.h>\n#include <game/client/ui.h>\n\n#include \"menus.h\"\n#include \"motd.h\"\n#include \"voting.h\"\n\nvoid CMenus::RenderGame(CUIRect MainView)\n{\n\tif(m_pClient->m_LocalClientID == -1)\n\t\treturn;\n\n\tchar aBuf[128];\n\tconst char *pNotification = 0;\n\tint TeamMod = m_pClient->m_aClients[m_pClient->m_LocalClientID].m_Team != TEAM_SPECTATORS ? -1 : 0;\n\tbool AllowSpec = true;\n\tint TimeLeft = 0;\n\n\tif(TeamMod+m_pClient->m_GameInfo.m_aTeamSize[TEAM_RED]+m_pClient->m_GameInfo.m_aTeamSize[TEAM_BLUE] >= m_pClient->m_ServerSettings.m_PlayerSlots)\n\t{\n\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"Only %d active players are allowed\"), m_pClient->m_ServerSettings.m_PlayerSlots);\n\t\tpNotification = aBuf;\n\t}\n\telse if(m_pClient->m_ServerSettings.m_TeamLock)\n\t\tpNotification = Localize(\"Teams are locked\");\n\telse if(m_pClient->m_TeamCooldownTick+1 >= Client()->GameTick())\n\t{\n\t\tTimeLeft = (m_pClient->m_TeamCooldownTick-Client()->GameTick())/Client()->GameTickSpeed()+1;\n\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"Teams are locked. Time to wait before changing team: %02d:%02d\"), TimeLeft/60, TimeLeft%60);\n\t\tpNotification = aBuf;\n\t\tAllowSpec = false;\n\t}\n\n\tCUIRect Button, BottomView, Left, Middle, Right;\n\n\t// cut view\n\tMainView.HSplitBottom(80.0f, &MainView, &BottomView); // MainView not used for now\n\tBottomView.HSplitTop(20.f, 0, &BottomView);\n\n\tfloat Spacing = 3.0f;\n\tfloat ButtonWidth = (BottomView.w/6.0f)-(Spacing*5.0)/6.0f;\n\n\tBottomView.VSplitLeft(ButtonWidth*3.0f+Spacing*2.0f, &Left, &Middle);\n\tMiddle.VSplitLeft(Spacing, 0, &Middle);\n\tMiddle.VSplitLeft(ButtonWidth, &Middle, &Right);\n\tRight.VSplitRight(ButtonWidth, 0, &Right);\n\tif(!(m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS))\n\t\tLeft.VSplitLeft(ButtonWidth, &Left, 0);\n\n\t// do backgrounds\n\tRenderTools()->DrawUIRect4(&Left, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f);\n\tRenderTools()->DrawUIRect4(&Middle, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f);\n\tRenderTools()->DrawUIRect4(&Right, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f);\n\n\t// do buttons\n\tLeft.HSplitTop(25.0f, &Left, 0);\n\tMiddle.HSplitTop(25.0f, &Middle, 0);\n\tRight.HSplitTop(25.0f, &Right, 0);\n\n\tif(pNotification != 0)\n\t{\n\t\t// print notice\n\t\tCUIRect Bar;\n\t\tMainView.HSplitTop(45.0f, &Bar, &MainView);\n\t\tRenderTools()->DrawUIRect(&Bar, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 10.0f);\n\t\tBar.HMargin(15.0f, &Bar);\n\t\tUI()->DoLabelScaled(&Bar, pNotification, 14.0f, 0);\n\t}\n\n\t// join buttons\n\t{\n\t\t// specator button\n\t\tint Team = m_pClient->m_aClients[m_pClient->m_LocalClientID].m_Team;\n\t\tif(pNotification && Team != TEAM_SPECTATORS)\n\t\t{\n\t\t\tif(TimeLeft)\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"(%d)\", TimeLeft);\n\t\t\telse\n\t\t\t\tstr_copy(aBuf, Localize(\"locked\"), sizeof(aBuf));\n\t\t}\n\t\telse\n\t\t\tstr_copy(aBuf, Localize(Team != TEAM_SPECTATORS ? \"Spectate\" : \"Spactating\"), sizeof(aBuf)); // Localize(\"Spectating\");\n\n\t\tLeft.VSplitLeft(ButtonWidth, &Button, &Left);\n\t\tLeft.VSplitLeft(Spacing, 0, &Left);\n\t\tstatic int s_SpectateButton = 0;\n\t\tif(DoButton_Menu(&s_SpectateButton, aBuf, Team == TEAM_SPECTATORS, &Button) && Team != TEAM_SPECTATORS && AllowSpec && !pNotification)\n\t\t{\n\t\t\tm_pClient->SendSwitchTeam(TEAM_SPECTATORS);\n\t\t\tSetActive(false);\n\t\t}\n\n\t\t// team button\n\t\tif(m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS)\n\t\t{\n\t\t\tif(pNotification && Team != TEAM_RED)\n\t\t\t{\n\t\t\t\tif(TimeLeft)\n\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"(%d)\", TimeLeft);\n\t\t\t\telse\n\t\t\t\t\tstr_copy(aBuf, Localize(\"locked\"), sizeof(aBuf));\n\t\t\t}\n\t\t\telse\n\t\t\t\tstr_copy(aBuf, Localize(Team != TEAM_RED ? \"Join red\" : \"Joined red\"), sizeof(aBuf)); // Localize(\"Join red\");Localize(\"Joined red\");\n\n\t\t\tLeft.VSplitLeft(ButtonWidth, &Button, &Left);\n\t\t\tLeft.VSplitLeft(Spacing, 0, &Left);\n\t\t\tstatic int s_RedButton = 0;\n\t\t\tif(DoButton_Menu(&s_RedButton, aBuf, Team == TEAM_RED, &Button, CUI::CORNER_ALL, 5.0f, 0.0f, vec4(0.975f, 0.17f, 0.17f, 0.75f), false) && Team != TEAM_RED && !pNotification)\n\t\t\t{\n\t\t\t\tm_pClient->SendSwitchTeam(TEAM_RED);\n\t\t\t\tSetActive(false);\n\t\t\t}\n\n\t\t\tif(pNotification && Team != TEAM_BLUE)\n\t\t\t{\n\t\t\t\tif(TimeLeft)\n\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"(%d)\", TimeLeft);\n\t\t\t\telse\n\t\t\t\t\tstr_copy(aBuf, Localize(\"locked\"), sizeof(aBuf));\n\t\t\t}\n\t\t\telse\n\t\t\t\tstr_copy(aBuf, Localize(Team != TEAM_BLUE ? \"Join blue\" : \"Joined blue\"), sizeof(aBuf)); // Localize(\"Join blue\");Localize(\"Joined blue\");\n\n\t\t\tLeft.VSplitLeft(ButtonWidth, &Button, &Left);\n\t\t\tstatic int s_BlueButton = 0;\n\t\t\tif(DoButton_Menu(&s_BlueButton, aBuf, Team == TEAM_BLUE, &Button, CUI::CORNER_ALL, 5.0f, 0.0f, vec4(0.17f, 0.46f, 0.975f, 0.75f), false) && Team != TEAM_BLUE && !pNotification)\n\t\t\t{\n\t\t\t\tm_pClient->SendSwitchTeam(TEAM_BLUE);\n\t\t\t\tSetActive(false);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(pNotification && Team != TEAM_RED)\n\t\t\t{\n\t\t\t\tif(TimeLeft)\n\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"(%d)\", TimeLeft);\n\t\t\t\telse\n\t\t\t\t\tstr_copy(aBuf, Localize(\"locked\"), sizeof(aBuf));\n\t\t\t}\n\t\t\telse\n\t\t\t\tstr_copy(aBuf, Localize(Team != TEAM_RED ? \"Join\" : \"Joined\"), sizeof(aBuf)); //Localize(\"Join\");Localize(\"Joined\");\n\n\t\t\tLeft.VSplitLeft(ButtonWidth, &Button, &Left);\n\t\t\tstatic int s_JoinButton = 0;\n\t\t\tif(DoButton_Menu(&s_JoinButton, aBuf, Team == TEAM_RED, &Button) && Team != TEAM_RED && !pNotification)\n\t\t\t{\n\t\t\t\tm_pClient->SendSwitchTeam(0);\n\t\t\t\tSetActive(false);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Record button\n\tstatic int s_DemoButton = 0;\n\tbool Recording = DemoRecorder()->IsRecording();\n\tif(DoButton_Menu(&s_DemoButton, Localize(Recording ? \"Stop record\" : \"Record\"), Recording, &Middle))\t// Localize(\"Stop record\");Localize(\"Record\");\n\t{\n\t\tif(!Recording)\n\t\t\tClient()->DemoRecorder_Start(\"demo\", true);\n\t\telse\n\t\t\tClient()->DemoRecorder_Stop();\n\t}\n\n\t// disconnect button\n\tstatic int s_DisconnectButton = 0;\n\tif(DoButton_Menu(&s_DisconnectButton, Localize(\"Disconnect\"), 0, &Right))\n\t\tClient()->Disconnect();\n}\n\nvoid CMenus::RenderPlayers(CUIRect MainView)\n{\n\tCUIRect Button, ButtonBar, Options, Player;\n\tRenderTools()->DrawUIRect(&MainView, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 10.0f);\n\n\t// player options\n\tMainView.Margin(10.0f, &Options);\n\tRenderTools()->DrawUIRect(&Options, vec4(1.0f, 1.0f, 1.0f, 0.25f), CUI::CORNER_ALL, 10.0f);\n\tOptions.Margin(10.0f, &Options);\n\tOptions.HSplitTop(50.0f, &Button, &Options);\n\tUI()->DoLabelScaled(&Button, Localize(\"Player options\"), 34.0f, -1);\n\n\t// headline\n\tOptions.HSplitTop(34.0f, &ButtonBar, &Options);\n\tButtonBar.VSplitRight(220.0f, &Player, &ButtonBar);\n\tUI()->DoLabelScaled(&Player, Localize(\"Player\"), 24.0f, -1);\n\n\tButtonBar.HMargin(1.0f, &ButtonBar);\n\tfloat Width = ButtonBar.h*2.0f;\n\tButtonBar.VSplitLeft(Width, &Button, &ButtonBar);\n\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_GUIICONS].m_Id);\n\tGraphics()->QuadsBegin();\n\tRenderTools()->SelectSprite(SPRITE_GUIICON_MUTE);\n\tIGraphics::CQuadItem QuadItem(Button.x, Button.y, Button.w, Button.h);\n\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n\n\tButtonBar.VSplitLeft(20.0f, 0, &ButtonBar);\n\tButtonBar.VSplitLeft(Width, &Button, &ButtonBar);\n\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_GUIICONS].m_Id);\n\tGraphics()->QuadsBegin();\n\tRenderTools()->SelectSprite(SPRITE_GUIICON_FRIEND);\n\tQuadItem = IGraphics::CQuadItem(Button.x, Button.y, Button.w, Button.h);\n\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n\n\t// options\n\tstatic int s_aPlayerIDs[MAX_CLIENTS][2] = {{0}};\n\tint Teams[3] = { TEAM_RED, TEAM_BLUE, TEAM_SPECTATORS };\n\tfor(int Team = 0; Team < 3; ++Team)\n\t{\n\t\tfor(int i = 0, Count = 0; i < MAX_CLIENTS; ++i)\n\t\t{\n\t\t\tif(i == m_pClient->m_LocalClientID || !m_pClient->m_aClients[i].m_Active || m_pClient->m_aClients[i].m_Team != Teams[Team])\n\t\t\t\tcontinue;\n\n\t\t\tOptions.HSplitTop(28.0f, &ButtonBar, &Options);\n\t\t\tif(Count++%2 == 0)\n\t\t\t\tRenderTools()->DrawUIRect(&ButtonBar, vec4(1.0f, 1.0f, 1.0f, 0.25f), CUI::CORNER_ALL, 10.0f);\n\t\t\tButtonBar.VSplitRight(220.0f, &Player, &ButtonBar);\n\n\t\t\t// player info\n\t\t\tPlayer.VSplitLeft(28.0f, &Button, &Player);\n\t\t\tCTeeRenderInfo Info = m_pClient->m_aClients[i].m_RenderInfo;\n\t\t\tInfo.m_Size = Button.h;\n\t\t\tRenderTools()->RenderTee(CAnimState::GetIdle(), &Info, EMOTE_NORMAL, vec2(1.0f, 0.0f), vec2(Button.x+Button.h/2, Button.y+Button.h/2));\n\n\t\t\tPlayer.HSplitTop(1.5f, 0, &Player);\n\t\t\tPlayer.VSplitMid(&Player, &Button);\n\t\t\tCTextCursor Cursor;\n\t\t\tTextRender()->SetCursor(&Cursor, Player.x, Player.y, 14.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\t\t\tCursor.m_LineWidth = Player.w;\n\t\t\tTextRender()->TextEx(&Cursor, m_pClient->m_aClients[i].m_aName, -1);\n\n\t\t\tTextRender()->SetCursor(&Cursor, Button.x,Button.y, 14.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\t\t\tCursor.m_LineWidth = Button.w;\n\t\t\tTextRender()->TextEx(&Cursor, m_pClient->m_aClients[i].m_aClan, -1);\n\n\t\t\t// ignore button\n\t\t\tButtonBar.HMargin(2.0f, &ButtonBar);\n\t\t\tButtonBar.VSplitLeft(Width, &Button, &ButtonBar);\n\t\t\tButton.VSplitLeft((Width-Button.h)/4.0f, 0, &Button);\n\t\t\tButton.VSplitLeft(Button.h, &Button, 0);\n\t\t\tif(g_Config.m_ClShowChatFriends && !m_pClient->m_aClients[i].m_Friend)\n\t\t\t\tDoButton_Toggle(&s_aPlayerIDs[i][0], 1, &Button, false);\n\t\t\telse\n\t\t\t\tif(DoButton_Toggle(&s_aPlayerIDs[i][0], m_pClient->m_aClients[i].m_ChatIgnore, &Button, true))\n\t\t\t\t\tm_pClient->m_aClients[i].m_ChatIgnore ^= 1;\n\n\t\t\t// friend button\n\t\t\tButtonBar.VSplitLeft(20.0f, &Button, &ButtonBar);\n\t\t\tButtonBar.VSplitLeft(Width, &Button, &ButtonBar);\n\t\t\tButton.VSplitLeft((Width-Button.h)/4.0f, 0, &Button);\n\t\t\tButton.VSplitLeft(Button.h, &Button, 0);\n\t\t\tif(DoButton_Toggle(&s_aPlayerIDs[i][1], m_pClient->m_aClients[i].m_Friend, &Button, true))\n\t\t\t{\n\t\t\t\tif(m_pClient->m_aClients[i].m_Friend)\n\t\t\t\t\tm_pClient->Friends()->RemoveFriend(m_pClient->m_aClients[i].m_aName, m_pClient->m_aClients[i].m_aClan);\n\t\t\t\telse\n\t\t\t\t\tm_pClient->Friends()->AddFriend(m_pClient->m_aClients[i].m_aName, m_pClient->m_aClients[i].m_aClan);\n\n\t\t\t\tm_pClient->m_aClients[i].m_Friend ^= 1;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid CMenus::RenderServerInfo(CUIRect MainView)\n{\n\tif(!m_pClient->m_Snap.m_pLocalInfo)\n\t\treturn;\n\n\t// fetch server info\n\tCServerInfo CurrentServerInfo;\n\tClient()->GetServerInfo(&CurrentServerInfo);\n\n\t// render background\n\tRenderTools()->DrawUIRect(&MainView, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 10.0f);\n\n\tCUIRect View, ServerInfo, GameInfo, Motd;\n\n\tfloat x = 0.0f;\n\tfloat y = 0.0f;\n\n\tchar aBuf[1024];\n\n\t// set view to use for all sub-modules\n\tMainView.Margin(10.0f, &View);\n\n\t// serverinfo\n\tView.HSplitTop(View.h/2/UI()->Scale()-5.0f, &ServerInfo, &Motd);\n\tServerInfo.VSplitLeft(View.w/2/UI()->Scale()-5.0f, &ServerInfo, &GameInfo);\n\tRenderTools()->DrawUIRect(&ServerInfo, vec4(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f);\n\n\tServerInfo.Margin(5.0f, &ServerInfo);\n\n\tx = 5.0f;\n\ty = 0.0f;\n\n\tTextRender()->Text(0, ServerInfo.x+x, ServerInfo.y+y, 32, Localize(\"Server info\"), 250);\n\ty += 32.0f+5.0f;\n\n\tmem_zero(aBuf, sizeof(aBuf));\n\tstr_format(\n\t\taBuf,\n\t\tsizeof(aBuf),\n\t\t\"%s\\n\\n\"\n\t\t\"%s: %s\\n\"\n\t\t\"%s: %d\\n\"\n\t\t\"%s: %s\\n\"\n\t\t\"%s: %s\\n\",\n\t\tCurrentServerInfo.m_aName,\n\t\tLocalize(\"Address\"), g_Config.m_UiServerAddress,\n\t\tLocalize(\"Ping\"), m_pClient->m_Snap.m_pLocalInfo->m_Latency,\n\t\tLocalize(\"Version\"), CurrentServerInfo.m_aVersion,\n\t\tLocalize(\"Password\"), CurrentServerInfo.m_Flags&IServerBrowser::FLAG_PASSWORD ? Localize(\"Yes\") : Localize(\"No\")\n\t);\n\n\tTextRender()->Text(0, ServerInfo.x+x, ServerInfo.y+y, 20, aBuf, 250);\n\n\t{\n\t\tCUIRect Button;\n\t\tbool IsFavorite = ServerBrowser()->IsFavorite(CurrentServerInfo.m_NetAddr);\n\t\tServerInfo.HSplitBottom(20.0f, &ServerInfo, &Button);\n\t\tstatic int s_AddFavButton = 0;\n\t\tif(DoButton_CheckBox(&s_AddFavButton, Localize(\"Favorite\"), IsFavorite, &Button))\n\t\t{\n\t\t\tif(IsFavorite)\n\t\t\t\tServerBrowser()->RemoveFavorite(&CurrentServerInfo);\n\t\t\telse\n\t\t\t\tServerBrowser()->AddFavorite(&CurrentServerInfo);\n\t\t}\n\t}\n\n\t// gameinfo\n\tGameInfo.VSplitLeft(10.0f, 0x0, &GameInfo);\n\tRenderTools()->DrawUIRect(&GameInfo, vec4(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f);\n\n\tGameInfo.Margin(5.0f, &GameInfo);\n\n\tx = 5.0f;\n\ty = 0.0f;\n\n\tTextRender()->Text(0, GameInfo.x+x, GameInfo.y+y, 32, Localize(\"Game info\"), 250);\n\ty += 32.0f+5.0f;\n\n\tmem_zero(aBuf, sizeof(aBuf));\n\tstr_format(\n\t\taBuf,\n\t\tsizeof(aBuf),\n\t\t\"\\n\\n\"\n\t\t\"%s: %s\\n\"\n\t\t\"%s: %s\\n\"\n\t\t\"%s: %d\\n\"\n\t\t\"%s: %d\\n\"\n\t\t\"\\n\"\n\t\t\"%s: %d/%d\\n\",\n\t\tLocalize(\"Game type\"), CurrentServerInfo.m_aGameType,\n\t\tLocalize(\"Map\"), CurrentServerInfo.m_aMap,\n\t\tLocalize(\"Score limit\"), m_pClient->m_GameInfo.m_ScoreLimit,\n\t\tLocalize(\"Time limit\"), m_pClient->m_GameInfo.m_TimeLimit,\n\t\tLocalize(\"Players\"), m_pClient->m_GameInfo.m_NumPlayers, CurrentServerInfo.m_MaxClients\n\t);\n\tTextRender()->Text(0, GameInfo.x+x, GameInfo.y+y, 20, aBuf, 250);\n\n\t// motd\n\tMotd.HSplitTop(10.0f, 0, &Motd);\n\tRenderTools()->DrawUIRect(&Motd, vec4(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f);\n\tMotd.Margin(5.0f, &Motd);\n\ty = 0.0f;\n\tx = 5.0f;\n\tTextRender()->Text(0, Motd.x+x, Motd.y+y, 32, Localize(\"MOTD\"), -1);\n\ty += 32.0f+5.0f;\n\tTextRender()->Text(0, Motd.x+x, Motd.y+y, 16, m_pClient->m_pMotd->m_aServerMotd, (int)Motd.w);\n}\n\nvoid CMenus::RenderServerControlServer(CUIRect MainView)\n{\n\tstatic int s_VoteList = 0;\n\tstatic float s_ScrollValue = 0;\n\tCUIRect List = MainView;\n\tUiDoListboxHeader(&List, \"\", 20.0f, 2.0f);\n\tUiDoListboxStart(&s_VoteList, 24.0f, \"\", m_pClient->m_pVoting->m_NumVoteOptions, 1, m_CallvoteSelectedOption, s_ScrollValue);\n\n\tfor(CVoteOptionClient *pOption = m_pClient->m_pVoting->m_pFirst; pOption; pOption = pOption->m_pNext)\n\t{\n\t\tCListboxItem Item = UiDoListboxNextItem(pOption);\n\n\t\tif(Item.m_Visible)\n\t\t\tUI()->DoLabelScaled(&Item.m_Rect, pOption->m_aDescription, 16.0f, -1);\n\t}\n\n\tm_CallvoteSelectedOption = UiDoListboxEnd(&s_ScrollValue, 0);\n}\n\nvoid CMenus::RenderServerControlKick(CUIRect MainView, bool FilterSpectators)\n{\n\tint NumOptions = 0;\n\tint Selected = -1;\n\tstatic int aPlayerIDs[MAX_CLIENTS];\n\tint Teams[3] = { TEAM_RED, TEAM_BLUE, TEAM_SPECTATORS };\n\tfor(int Team = 0; Team < 3; ++Team)\n\t{\n\t\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t\t{\n\t\t\tif(i == m_pClient->m_LocalClientID || !m_pClient->m_aClients[i].m_Active || m_pClient->m_aClients[i].m_Team != Teams[Team] ||\n\t\t\t\t(FilterSpectators && m_pClient->m_aClients[i].m_Team == TEAM_SPECTATORS) || \n\t\t\t\t(!FilterSpectators && m_pClient->m_Snap.m_paPlayerInfos[i] && m_pClient->m_Snap.m_paPlayerInfos[i]->m_PlayerFlags&PLAYERFLAG_ADMIN))\n\t\t\t\tcontinue;\n\t\t\tif(m_CallvoteSelectedPlayer == i)\n\t\t\t\tSelected = NumOptions;\n\t\t\taPlayerIDs[NumOptions++] = i;\n\t\t}\n\t}\n\n\tstatic int s_VoteList = 0;\n\tstatic float s_ScrollValue = 0;\n\tCUIRect List = MainView;\n\tUiDoListboxHeader(&List, \"\", 20.0f, 2.0f);\n\tUiDoListboxStart(&s_VoteList, 24.0f, \"\", NumOptions, 1, Selected, s_ScrollValue);\n\n\tfor(int i = 0; i < NumOptions; i++)\n\t{\n\t\tCListboxItem Item = UiDoListboxNextItem(&aPlayerIDs[i]);\n\n\t\tif(Item.m_Visible)\n\t\t{\n\t\t\tCTeeRenderInfo Info = m_pClient->m_aClients[aPlayerIDs[i]].m_RenderInfo;\n\t\t\tInfo.m_Size = Item.m_Rect.h;\n\t\t\tItem.m_Rect.HSplitTop(5.0f, 0, &Item.m_Rect); // some margin from the top\n\t\t\tRenderTools()->RenderTee(CAnimState::GetIdle(), &Info, EMOTE_NORMAL, vec2(1,0), vec2(Item.m_Rect.x+Item.m_Rect.h/2, Item.m_Rect.y+Item.m_Rect.h/2));\n\t\t\tItem.m_Rect.x +=Info.m_Size;\n\t\t\tUI()->DoLabelScaled(&Item.m_Rect, m_pClient->m_aClients[aPlayerIDs[i]].m_aName, 16.0f, -1);\n\t\t}\n\t}\n\n\tSelected = UiDoListboxEnd(&s_ScrollValue, 0);\n\tm_CallvoteSelectedPlayer = Selected != -1 ? aPlayerIDs[Selected] : -1;\n}\n\nvoid CMenus::HandleCallvote(int Page, bool Force)\n{\n\tif(Page == 0)\n\t\tm_pClient->m_pVoting->CallvoteOption(m_CallvoteSelectedOption, m_aCallvoteReason, Force);\n\telse if(Page == 1)\n\t{\n\t\tif(m_CallvoteSelectedPlayer >= 0 && m_CallvoteSelectedPlayer < MAX_CLIENTS &&\n\t\t\tm_pClient->m_aClients[m_CallvoteSelectedPlayer].m_Active)\n\t\t{\n\t\t\tm_pClient->m_pVoting->CallvoteKick(m_CallvoteSelectedPlayer, m_aCallvoteReason, Force);\n\t\t\tSetActive(false);\n\t\t}\n\t}\n\telse if(Page == 2)\n\t{\n\t\tif(m_CallvoteSelectedPlayer >= 0 && m_CallvoteSelectedPlayer < MAX_CLIENTS &&\n\t\t\tm_pClient->m_aClients[m_CallvoteSelectedPlayer].m_Active)\n\t\t{\n\t\t\tm_pClient->m_pVoting->CallvoteSpectate(m_CallvoteSelectedPlayer, m_aCallvoteReason, Force);\n\t\t\tSetActive(false);\n\t\t}\n\t}\n}\n\nvoid CMenus::RenderServerControl(CUIRect MainView)\n{\n\tif(m_pClient->m_LocalClientID == -1)\n\t\treturn;\n\n\tstatic int s_ControlPage = 0;\n\tconst char *pNotification = 0;\n\tchar aBuf[64];\n\t\n\tif(m_pClient->m_aClients[m_pClient->m_LocalClientID].m_Team == TEAM_SPECTATORS)\n\t\tpNotification = Localize(\"Spectators aren't allowed to start a vote.\");\n\telse if(m_pClient->m_pVoting->IsVoting())\n\t\tpNotification = Localize(\"Wait for current vote to end before calling a new one.\");\n\telse if(m_pClient->m_pVoting->CallvoteBlockTime() != 0)\n\t{\n\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"You must wait %d seconds before making another vote\"), m_pClient->m_pVoting->CallvoteBlockTime());\n\t\tpNotification = aBuf;\n\t}\n\n\tbool Authed = Client()->RconAuthed();\n\tif(pNotification && !Authed)\n\t{\n\t\t// only print notice\n\t\tCUIRect Bar;\n\t\tMainView.HSplitTop(45.0f, &Bar, &MainView);\n\t\tRenderTools()->DrawUIRect(&Bar, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 10.0f);\n\t\tBar.HMargin(15.0f, &Bar);\n\t\tUI()->DoLabelScaled(&Bar, pNotification, 14.0f, 0);\n\t\treturn;\n\t}\n\n\t// tab bar\n\tCUIRect Bottom, Extended, TabBar, Button;\n\tMainView.HSplitTop(20.0f, &Bottom, &MainView);\n\tRenderTools()->DrawUIRect(&Bottom, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_T, 10.0f);\n\tMainView.HSplitTop(20.0f, &TabBar, &MainView);\n\t{\n\t\tTabBar.VSplitLeft(TabBar.w/3, &Button, &TabBar);\n\t\tstatic int s_Button0 = 0;\n\t\tif(DoButton_MenuTab(&s_Button0, Localize(\"Change settings\"), s_ControlPage == 0, &Button, 0))\n\t\t\ts_ControlPage = 0;\n\n\t\tTabBar.VSplitMid(&Button, &TabBar);\n\t\tstatic int s_Button1 = 0;\n\t\tif(DoButton_MenuTab(&s_Button1, Localize(\"Kick player\"), s_ControlPage == 1, &Button, 0))\n\t\t\ts_ControlPage = 1;\n\n\t\tstatic int s_Button2 = 0;\n\t\tif(DoButton_MenuTab(&s_Button2, Localize(\"Move player to spectators\"), s_ControlPage == 2, &TabBar, 0))\n\t\t\ts_ControlPage = 2;\n\t}\n\n\tif(s_ControlPage == 1)\n\t{\n\t\tif(!m_pClient->m_ServerSettings.m_KickVote)\n\t\t\tpNotification = Localize(\"Server does not allow voting to kick players\");\n\t\telse if(m_pClient->m_GameInfo.m_aTeamSize[TEAM_RED]+m_pClient->m_GameInfo.m_aTeamSize[TEAM_BLUE] < m_pClient->m_ServerSettings.m_KickMin)\n\t\t{\n\t\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"Kick voting requires %d players on the server\"), m_pClient->m_ServerSettings.m_KickMin);\n\t\t\tpNotification = aBuf;\n\t\t}\n\t}\n\telse if(s_ControlPage == 2 && !m_pClient->m_ServerSettings.m_SpecVote)\n\t\tpNotification = Localize(\"Server does not allow voting to move players to spectators\");\n\t\n\tif(pNotification && !Authed)\n\t{\n\t\t// only print notice\n\t\tCUIRect Bar;\n\t\tMainView.HSplitTop(45.0f, &Bar, &MainView);\n\t\tRenderTools()->DrawUIRect(&Bar, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 10.0f);\n\t\tBar.HMargin(15.0f, &Bar);\n\t\tUI()->DoLabelScaled(&Bar, pNotification, 14.0f, 0);\n\t\treturn;\n\t}\n\n\t// render background\n\tRenderTools()->DrawUIRect(&MainView, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 10.0f);\n\tMainView.Margin(10.0f, &MainView);\n\tMainView.HSplitBottom(90.0f, &MainView, &Extended);\n\n\t// render page\n\tMainView.HSplitBottom(ms_ButtonHeight + 5*2, &MainView, &Bottom);\n\tBottom.HMargin(5.0f, &Bottom);\n\n\tif(s_ControlPage == 0)\n\t\tRenderServerControlServer(MainView);\n\telse if(s_ControlPage == 1)\n\t\tRenderServerControlKick(MainView, false);\n\telse if(s_ControlPage == 2)\n\t\tRenderServerControlKick(MainView, true);\n\n\t// vote menu\n\t{\n\t\tBottom.VSplitRight(120.0f, &Bottom, &Button);\n\n\t\t// render kick reason\n\t\tCUIRect Reason, ClearButton;\n\t\tBottom.VSplitRight(40.0f, &Bottom, 0);\n\t\tBottom.VSplitRight(160.0f, &Bottom, &Reason);\n\t\tReason.HSplitTop(5.0f, 0, &Reason);\n\t\tReason.VSplitRight(Reason.h, &Reason, &ClearButton);\t\t\n\t\tconst char *pLabel = Localize(\"Reason:\");\n\t\tUI()->DoLabelScaled(&Reason, pLabel, 14.0f, -1);\n\t\tfloat w = TextRender()->TextWidth(0, 14.0f, pLabel, -1);\n\t\tReason.VSplitLeft(w+10.0f, 0, &Reason);\n\t\tstatic float s_Offset = 0.0f;\n\t\tDoEditBox(&m_aCallvoteReason, &Reason, m_aCallvoteReason, sizeof(m_aCallvoteReason), 14.0f, &s_Offset, false, CUI::CORNER_L);\n\t\t\n\t\t// clear button\n\t\t{\n\t\t\tstatic int s_ClearButton = 0;\n\t\t\tfloat *pClearButtonFade = ButtonFade(&s_ClearButton, 0.6f);\n\t\t\tRenderTools()->DrawUIRect(&ClearButton, vec4(1.0f, 1.0f, 1.0f, 0.33f+(*pClearButtonFade/0.6f)*0.165f), CUI::CORNER_R, 3.0f);\n\t\t\tUI()->DoLabel(&ClearButton, \"x\", ClearButton.h*ms_FontmodHeight, 0);\n\t\t\tif(UI()->DoButtonLogic(&s_ClearButton, \"x\", 0, &ClearButton))\n\t\t\t\tm_aCallvoteReason[0] = 0;\n\t\t}\n\n\t\tif(pNotification == 0)\n\t\t{\n\t\t\t// call vote\n\t\t\tstatic int s_CallVoteButton = 0;\n\t\t\tif(DoButton_Menu(&s_CallVoteButton, Localize(\"Call vote\"), 0, &Button))\n\t\t\t\tHandleCallvote(s_ControlPage, false);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// print notice\n\t\t\tUI()->DoLabelScaled(&Bottom, pNotification, 14.0f, -1, Bottom.w);\n\t\t}\t\t\n\n\t\t// extended features (only available when authed in rcon)\n\t\tif(Authed)\n\t\t{\n\t\t\t// background\n\t\t\tExtended.Margin(10.0f, &Extended);\n\t\t\tExtended.HSplitTop(20.0f, &Bottom, &Extended);\n\t\t\tExtended.HSplitTop(5.0f, 0, &Extended);\n\n\t\t\t// force vote\n\t\t\tBottom.VSplitLeft(5.0f, 0, &Bottom);\n\t\t\tBottom.VSplitLeft(120.0f, &Button, &Bottom);\n\t\t\tstatic int s_ForceVoteButton = 0;\n\t\t\tif(DoButton_Menu(&s_ForceVoteButton, Localize(\"Force vote\"), 0, &Button))\n\t\t\t\tHandleCallvote(s_ControlPage, true);\n\n\t\t\tif(s_ControlPage == 0)\n\t\t\t{\n\t\t\t\t// remove vote\n\t\t\t\tBottom.VSplitRight(10.0f, &Bottom, 0);\n\t\t\t\tBottom.VSplitRight(120.0f, 0, &Button);\n\t\t\t\tstatic int s_RemoveVoteButton = 0;\n\t\t\t\tif(DoButton_Menu(&s_RemoveVoteButton, Localize(\"Remove\"), 0, &Button))\n\t\t\t\t\tm_pClient->m_pVoting->RemovevoteOption(m_CallvoteSelectedOption);\n\n\n\t\t\t\t// add vote\n\t\t\t\tExtended.HSplitTop(20.0f, &Bottom, &Extended);\n\t\t\t\tBottom.VSplitLeft(5.0f, 0, &Bottom);\n\t\t\t\tBottom.VSplitLeft(250.0f, &Button, &Bottom);\n\t\t\t\tUI()->DoLabelScaled(&Button, Localize(\"Vote description:\"), 14.0f, -1);\n\n\t\t\t\tBottom.VSplitLeft(20.0f, 0, &Button);\n\t\t\t\tUI()->DoLabelScaled(&Button, Localize(\"Vote command:\"), 14.0f, -1);\n\n\t\t\t\tstatic char s_aVoteDescription[64] = {0};\n\t\t\t\tstatic char s_aVoteCommand[512] = {0};\n\t\t\t\tExtended.HSplitTop(20.0f, &Bottom, &Extended);\n\t\t\t\tBottom.VSplitRight(10.0f, &Bottom, 0);\n\t\t\t\tBottom.VSplitRight(120.0f, &Bottom, &Button);\n\t\t\t\tstatic int s_AddVoteButton = 0;\n\t\t\t\tif(DoButton_Menu(&s_AddVoteButton, Localize(\"Add\"), 0, &Button))\n\t\t\t\t\tif(s_aVoteDescription[0] != 0 && s_aVoteCommand[0] != 0)\n\t\t\t\t\t\tm_pClient->m_pVoting->AddvoteOption(s_aVoteDescription, s_aVoteCommand);\n\n\t\t\t\tBottom.VSplitLeft(5.0f, 0, &Bottom);\n\t\t\t\tBottom.VSplitLeft(250.0f, &Button, &Bottom);\n\t\t\t\tstatic float s_OffsetDesc = 0.0f;\n\t\t\t\tDoEditBox(&s_aVoteDescription, &Button, s_aVoteDescription, sizeof(s_aVoteDescription), 14.0f, &s_OffsetDesc, false, CUI::CORNER_ALL);\n\n\t\t\t\tBottom.VMargin(20.0f, &Button);\n\t\t\t\tstatic float s_OffsetCmd = 0.0f;\n\t\t\t\tDoEditBox(&s_aVoteCommand, &Button, s_aVoteCommand, sizeof(s_aVoteCommand), 14.0f, &s_OffsetCmd, false, CUI::CORNER_ALL);\n\t\t\t}\n\t\t}\n\t}\n}\n\n"
  },
  {
    "path": "src/game/client/components/menus_popups.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n\n#include <base/tl/array.h>\n\n#include <engine/shared/config.h>\n\n#include <engine/console.h>\n#include <engine/graphics.h>\n#include <engine/input.h>\n#include <engine/keys.h>\n#include <engine/storage.h>\n#include <engine/serverbrowser.h>\n\n#include \"countryflags.h\"\n#include \"menus.h\"\n\n\n// popup menu handling\nstatic struct\n{\n\tCUIRect m_Rect;\n\tvoid *m_pId;\n\tint (*m_pfnFunc)(CMenus *pMenu, CUIRect Rect);\n\tint m_IsMenu;\n\tvoid *m_pExtra;\n} s_Popups[8];\n\nstatic int g_NumPopups = 0;\n\nvoid CMenus::InvokePopupMenu(void *pID, int Flags, float x, float y, float Width, float Height, int (*pfnFunc)(CMenus *pMenu, CUIRect Rect), void *pExtra)\n{\n\tif(x + Width > UI()->Screen()->w)\n\t\tx -= Width;\n\tif(y + Height > UI()->Screen()->h)\n\t\ty -= Height;\n\ts_Popups[g_NumPopups].m_pId = pID;\n\ts_Popups[g_NumPopups].m_IsMenu = Flags;\n\ts_Popups[g_NumPopups].m_Rect.x = x;\n\ts_Popups[g_NumPopups].m_Rect.y = y;\n\ts_Popups[g_NumPopups].m_Rect.w = Width;\n\ts_Popups[g_NumPopups].m_Rect.h = Height;\n\ts_Popups[g_NumPopups].m_pfnFunc = pfnFunc;\n\ts_Popups[g_NumPopups].m_pExtra = pExtra;\n\tg_NumPopups++;\n}\n\nvoid CMenus::DoPopupMenu()\n{\n\tfor(int i = 0; i < g_NumPopups; i++)\n\t{\n\t\tbool Inside = UI()->MouseInside(&s_Popups[i].m_Rect);\n\t\tUI()->SetHotItem(&s_Popups[i].m_pId);\n\n\t\tif(UI()->ActiveItem() == &s_Popups[i].m_pId)\n\t\t{\n\t\t\tif(!UI()->MouseButton(0))\n\t\t\t{\n\t\t\t\tif(!Inside)\n\t\t\t\t\tg_NumPopups--;\n\t\t\t\tUI()->SetActiveItem(0);\n\t\t\t}\n\t\t}\n\t\telse if(UI()->HotItem() == &s_Popups[i].m_pId)\n\t\t{\n\t\t\tif(UI()->MouseButton(0))\n\t\t\t\tUI()->SetActiveItem(&s_Popups[i].m_pId);\n\t\t}\n\n\t\tint Corners = CUI::CORNER_ALL;\n\t\tif(s_Popups[i].m_IsMenu)\n\t\t\tCorners = CUI::CORNER_R|CUI::CORNER_B;\n\n\t\tCUIRect r = s_Popups[i].m_Rect;\n\t\tRenderTools()->DrawUIRect(&r, vec4(0.5f,0.5f,0.5f,0.75f), Corners, 3.0f);\n\t\tr.Margin(1.0f, &r);\n\t\tRenderTools()->DrawUIRect(&r, vec4(0,0,0,0.75f), Corners, 3.0f);\n\t\tr.Margin(4.0f, &r);\n\n\t\tif(s_Popups[i].m_pfnFunc(this, r))\n\t\t\tg_NumPopups--;\n\n\t\tif(Input()->KeyDown(KEY_ESCAPE))\n\t\t\tg_NumPopups--;\n\t}\n}\n\nint CMenus::PopupFilter(CMenus *pMenus, CUIRect View)\n{\n\tCUIRect ServerFilter = View, FilterHeader;\n\tconst float FontSize = 12.0f;\n\n\t// slected filter\n\tCBrowserFilter *pFilter = &pMenus->m_lFilters[pMenus->m_SelectedFilter];\n\tint SortHash = 0;\n\tint Ping = 0;\n\tint Country = 0;\n\tchar aGametype[32];\n\tchar aServerAddress[16];\n\tpFilter->GetFilter(&SortHash, &Ping, &Country, aGametype, aServerAddress);\n\n\t// server filter\n\tServerFilter.HSplitTop(ms_ListheaderHeight, &FilterHeader, &ServerFilter);\n\tpMenus->RenderTools()->DrawUIRect(&FilterHeader, vec4(1,1,1,0.25f), CUI::CORNER_T, 4.0f);\n\tpMenus->RenderTools()->DrawUIRect(&ServerFilter, vec4(0,0,0,0.15f), CUI::CORNER_B, 4.0f);\n\tpMenus->UI()->DoLabelScaled(&FilterHeader, Localize(\"Server filter\"), FontSize+2.0f, 0);\n\tCUIRect Button;\n\n\tServerFilter.VSplitLeft(5.0f, 0, &ServerFilter);\n\tServerFilter.Margin(3.0f, &ServerFilter);\n\tServerFilter.VMargin(5.0f, &ServerFilter);\n\n\tServerFilter.HSplitTop(20.0f, &Button, &ServerFilter);\n\tstatic int s_BrFilterEmpty = 0;\n\tif(pMenus->DoButton_CheckBox(&s_BrFilterEmpty, Localize(\"Has people playing\"), SortHash&IServerBrowser::FILTER_EMPTY, &Button))\n\t\tpFilter->SetFilter(SortHash^IServerBrowser::FILTER_EMPTY, Ping, Country, aGametype, aServerAddress);\n\n\tServerFilter.HSplitTop(20.0f, &Button, &ServerFilter);\n\tstatic int s_BrFilterSpectators = 0;\n\tif(pMenus->DoButton_CheckBox(&s_BrFilterSpectators, Localize(\"Count players only\"), SortHash&IServerBrowser::FILTER_SPECTATORS, &Button))\n\t\tpFilter->SetFilter(SortHash^IServerBrowser::FILTER_SPECTATORS, Ping, Country, aGametype, aServerAddress);\n\n\tServerFilter.HSplitTop(20.0f, &Button, &ServerFilter);\n\tstatic int s_BrFilterFull = 0;\n\tif(pMenus->DoButton_CheckBox(&s_BrFilterFull, Localize(\"Server not full\"), SortHash&IServerBrowser::FILTER_FULL, &Button))\n\t\tpFilter->SetFilter(SortHash^IServerBrowser::FILTER_FULL, Ping, Country, aGametype, aServerAddress);\n\n\tServerFilter.HSplitTop(20.0f, &Button, &ServerFilter);\n\tstatic int s_BrFilterFriends = 0;\n\tif(pMenus->DoButton_CheckBox(&s_BrFilterFriends, Localize(\"Show friends only\"), SortHash&IServerBrowser::FILTER_FRIENDS, &Button))\n\t\tpFilter->SetFilter(SortHash^IServerBrowser::FILTER_FRIENDS, Ping, Country, aGametype, aServerAddress);\n\n\tServerFilter.HSplitTop(20.0f, &Button, &ServerFilter);\n\tstatic int s_BrFilterPw = 0;\n\tif(pMenus->DoButton_CheckBox(&s_BrFilterPw, Localize(\"No password\"), SortHash&IServerBrowser::FILTER_PW, &Button))\n\t\tpFilter->SetFilter(SortHash^IServerBrowser::FILTER_PW, Ping, Country, aGametype, aServerAddress);\n\n\tServerFilter.HSplitTop(20.0f, &Button, &ServerFilter);\n\tstatic int s_BrFilterCompatversion = 0;\n\tif(pMenus->DoButton_CheckBox(&s_BrFilterCompatversion, Localize(\"Compatible version\"), SortHash&IServerBrowser::FILTER_COMPAT_VERSION, &Button))\n\t\tpFilter->SetFilter(SortHash^IServerBrowser::FILTER_COMPAT_VERSION, Ping, Country, aGametype, aServerAddress);\n\n\tServerFilter.HSplitTop(20.0f, &Button, &ServerFilter);\n\tstatic int s_BrFilterPure = 0;\n\tif(pMenus->DoButton_CheckBox(&s_BrFilterPure, Localize(\"Standard gametype\"), SortHash&IServerBrowser::FILTER_PURE, &Button))\n\t\tpFilter->SetFilter(SortHash^IServerBrowser::FILTER_PURE, Ping, Country, aGametype, aServerAddress);\n\n\tServerFilter.HSplitTop(20.0f, &Button, &ServerFilter);\n\tstatic int s_BrFilterPureMap = 0;\n\tif(pMenus->DoButton_CheckBox(&s_BrFilterPureMap, Localize(\"Standard map\"), SortHash&IServerBrowser::FILTER_PURE_MAP, &Button))\n\t\tpFilter->SetFilter(SortHash^IServerBrowser::FILTER_PURE_MAP, Ping, Country, aGametype, aServerAddress);\n\n\tServerFilter.HSplitTop(20.0f, &Button, &ServerFilter);\n\tstatic int s_BrFilterGametypeStrict = 0;\n\tif(pMenus->DoButton_CheckBox(&s_BrFilterGametypeStrict, Localize(\"Strict gametype filter\"), SortHash&IServerBrowser::FILTER_GAMETYPE_STRICT, &Button))\n\t\tpFilter->SetFilter(SortHash^IServerBrowser::FILTER_GAMETYPE_STRICT, Ping, Country, aGametype, aServerAddress);\n\n\tServerFilter.HSplitTop(5.0f, 0, &ServerFilter);\n\n\tServerFilter.HSplitTop(19.0f, &Button, &ServerFilter);\n\tpMenus->UI()->DoLabelScaled(&Button, Localize(\"Game types:\"), FontSize, -1);\n\tButton.VSplitRight(60.0f, 0, &Button);\n\tServerFilter.HSplitTop(3.0f, 0, &ServerFilter);\n\tstatic float Offset = 0.0f;\n\tstatic int s_BrFilterGametype = 0;\n\tif(pMenus->DoEditBox(&s_BrFilterGametype, &Button, aGametype, sizeof(aGametype), FontSize, &Offset))\n\t\tpFilter->SetFilter(SortHash, Ping, Country, aGametype, aServerAddress);\n\n\t{\n\t\tServerFilter.HSplitTop(19.0f, &Button, &ServerFilter);\n\t\tCUIRect EditBox;\n\t\tButton.VSplitRight(60.0f, &Button, &EditBox);\n\n\t\tpMenus->UI()->DoLabelScaled(&Button, Localize(\"Maximum ping:\"), FontSize, -1);\n\n\t\tchar aBuf[5];\n\t\tstr_format(aBuf, sizeof(aBuf), \"%d\", Ping);\n\t\tstatic float Offset = 0.0f;\n\t\tstatic int s_BrFilterPing = 0;\n\t\tpMenus->DoEditBox(&s_BrFilterPing, &EditBox, aBuf, sizeof(aBuf), FontSize, &Offset);\n\t\tint NewPing = clamp(str_toint(aBuf), 0, 999);\n\t\tif(NewPing != Ping)\n\t\t\tpFilter->SetFilter(SortHash, NewPing, Country, aGametype, aServerAddress);\n\t}\n\n\t// server address\n\tServerFilter.HSplitTop(3.0f, 0, &ServerFilter);\n\tServerFilter.HSplitTop(19.0f, &Button, &ServerFilter);\n\tpMenus->UI()->DoLabelScaled(&Button, Localize(\"Server address:\"), FontSize, -1);\n\tButton.VSplitRight(60.0f, 0, &Button);\n\tstatic float OffsetAddr = 0.0f;\n\tstatic int s_BrFilterServerAddress = 0;\n\tif(pMenus->DoEditBox(&s_BrFilterServerAddress, &Button, aServerAddress, sizeof(aServerAddress), FontSize, &OffsetAddr))\n\t\tpFilter->SetFilter(SortHash, Ping, Country, aGametype, aServerAddress);\n\n\t// player country\n\t{\n\t\tCUIRect Rect;\n\t\tServerFilter.HSplitTop(3.0f, 0, &ServerFilter);\n\t\tServerFilter.HSplitTop(26.0f, &Button, &ServerFilter);\n\t\tButton.VSplitRight(60.0f, &Button, &Rect);\n\t\tButton.HMargin(3.0f, &Button);\n\t\tstatic int s_BrFilterCountry = 0;\n\t\tif(pMenus->DoButton_CheckBox(&s_BrFilterCountry, Localize(\"Player country:\"), SortHash&IServerBrowser::FILTER_COUNTRY, &Button))\n\t\t\tpFilter->SetFilter(SortHash^IServerBrowser::FILTER_COUNTRY, Ping, Country, aGametype, aServerAddress);\n\n\t\tfloat OldWidth = Rect.w;\n\t\tRect.w = Rect.h*2;\n\t\tRect.x += (OldWidth-Rect.w)/2.0f;\n\t\tvec4 Color(1.0f, 1.0f, 1.0f, SortHash^IServerBrowser::FILTER_COUNTRY?1.0f: 0.5f);\n\t\tpMenus->m_pClient->m_pCountryFlags->Render(Country, &Color, Rect.x, Rect.y, Rect.w, Rect.h);\n\n\t\tstatic int s_BrFilterCountryIndex = 0;\n\t\tif(SortHash^IServerBrowser::FILTER_COUNTRY && pMenus->UI()->DoButtonLogic(&s_BrFilterCountryIndex, \"\", 0, &Rect))\n\t\t\tpMenus->m_Popup = POPUP_COUNTRY;\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "src/game/client/components/menus_settings.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n\n#include <base/math.h>\n\n#include <engine/engine.h>\n#include <engine/graphics.h>\n#include <engine/storage.h>\n#include <engine/textrender.h>\n#include <engine/external/json-parser/json.h>\n#include <engine/shared/config.h>\n\n#include <game/generated/protocol.h>\n#include <game/generated/client_data.h>\n\n#include <game/client/components/sounds.h>\n#include <game/client/ui.h>\n#include <game/client/render.h>\n#include <game/client/gameclient.h>\n#include <game/client/animstate.h>\n\n#include \"binds.h\"\n#include \"countryflags.h\"\n#include \"menus.h\"\n\nCMenusKeyBinder CMenus::m_Binder;\n\nCMenusKeyBinder::CMenusKeyBinder()\n{\n\tm_TakeKey = false;\n\tm_GotKey = false;\n}\n\nbool CMenusKeyBinder::OnInput(IInput::CEvent Event)\n{\n\tif(m_TakeKey)\n\t{\n\t\tif(Event.m_Flags&IInput::FLAG_PRESS)\n\t\t{\n\t\t\tm_Key = Event;\n\t\t\tm_GotKey = true;\n\t\t\tm_TakeKey = false;\n\t\t}\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nint CMenus::DoButton_Customize(const void *pID, IGraphics::CTextureHandle Texture, int SpriteID, const CUIRect *pRect, float ImageRatio)\n{\n\tfloat Seconds = 0.6f; //  0.6 seconds for fade\n\tfloat *pFade = ButtonFade(pID, Seconds);\n\n\tRenderTools()->DrawUIRect(pRect, vec4(1.0f, 1.0f, 1.0f, 0.5f+(*pFade/Seconds)*0.25f), CUI::CORNER_ALL, 10.0f);\n\tGraphics()->TextureSet(Texture);\n\tGraphics()->QuadsBegin();\n\tRenderTools()->SelectSprite(SpriteID);\n\tfloat Height = pRect->w/ImageRatio;\n\tIGraphics::CQuadItem QuadItem(pRect->x, pRect->y+(pRect->h-Height)/2, pRect->w, Height);\n\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n\n\treturn UI()->DoButtonLogic(pID, \"\", 0, pRect);\n}\n\nvoid CMenus::SaveSkinfile()\n{\n\tchar aBuf[512];\n\tstr_format(aBuf, sizeof(aBuf), \"skins/%s.json\", m_aSaveSkinName);\n\tIOHANDLE File = Storage()->OpenFile(aBuf, IOFLAG_WRITE, IStorage::TYPE_SAVE);\n\tif(!File)\n\t\treturn;\n\n\t// file start\n\tconst char *p = \"{\\\"skin\\\": {\";\n\tio_write(File, p, str_length(p));\n\tint Count = 0;\n\n\tfor(int PartIndex = 0; PartIndex < CSkins::NUM_SKINPARTS; PartIndex++)\n\t{\n\t\tif(!CSkins::ms_apSkinVariables[PartIndex][0])\n\t\t\tcontinue;\n\t\t\n\t\t// part start\n\t\tif(Count == 0)\n\t\t{\n\t\t\tp = \"\\n\";\n\t\t\tio_write(File, p, str_length(p));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tp = \",\\n\"; \n\t\t\tio_write(File, p, str_length(p));\n\t\t}\n\t\tstr_format(aBuf, sizeof(aBuf), \"\\t\\\"%s\\\": {\\n\", CSkins::ms_apSkinPartNames[PartIndex]);\n\t\tio_write(File, aBuf, str_length(aBuf));\n\n\t\t// part content\n\t\tstr_format(aBuf, sizeof(aBuf), \"\\t\\t\\\"filename\\\": \\\"%s\\\",\\n\", CSkins::ms_apSkinVariables[PartIndex]);\n\t\tio_write(File, aBuf, str_length(aBuf));\n\n\t\tstr_format(aBuf, sizeof(aBuf), \"\\t\\t\\\"custom_colors\\\": \\\"%s\\\"\", *CSkins::ms_apUCCVariables[PartIndex]?\"true\":\"false\");\n\t\tio_write(File, aBuf, str_length(aBuf));\n\n\t\tif(*CSkins::ms_apUCCVariables[PartIndex])\n\t\t{\n\t\t\tfor(int c = 0; c < CSkins::NUM_COLOR_COMPONENTS-1; c++)\n\t\t\t{\n\t\t\t\tint Val = (*CSkins::ms_apColorVariables[PartIndex] >> (2-c)*8) & 0xff;\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \",\\n\\t\\t\\\"%s\\\": %d\", CSkins::ms_apColorComponents[c], Val);\n\t\t\t\tio_write(File, aBuf, str_length(aBuf));\n\t\t\t}\n\t\t\tif(PartIndex == CSkins::SKINPART_TATTOO)\n\t\t\t{\n\t\t\t\tint Val = (*CSkins::ms_apColorVariables[PartIndex] >> 24) & 0xff;\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \",\\n\\t\\t\\\"%s\\\": %d\", CSkins::ms_apColorComponents[3], Val);\n\t\t\t\tio_write(File, aBuf, str_length(aBuf));\n\t\t\t}\n\t\t}\n\n\t\t// part end\n\t\tp = \"\\n\\t}\";\n\t\tio_write(File, p, str_length(p));\n\n\t\t++Count;\n\t}\n\n\t// file end\n\tp = \"}\\n}\\n\";\n\tio_write(File, p, str_length(p));\n\n\tio_close(File);\n\n\t// add new skin to the skin list\n\tm_pClient->m_pSkins->AddSkin(m_aSaveSkinName);\n}\n\nvoid CMenus::RenderHSLPicker(CUIRect MainView)\n{\n\tCUIRect Label, Button, Picker;\n\n\t// background\n\tfloat Spacing = 2.0f;\n\tRenderTools()->DrawUIRect(&MainView, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\t// color header\n\tfloat HeaderHeight = 20.0f;\n\tMainView.HSplitTop(HeaderHeight, &Label, &MainView);\n\tLabel.y += 2.0f;\n\tUI()->DoLabel(&Label, Localize(\"Color\"), HeaderHeight*ms_FontmodHeight*0.8f, 0);\n\tMainView.HSplitTop(Spacing, 0, &MainView);\n\n\t// use custom color checkbox\n\tfloat ButtonHeight = 20.0f;\n\tMainView.HSplitTop(ButtonHeight, &Button, &MainView);\n\tstatic int s_CustomColors = 0;\n\tif(DoButton_CheckBox(&s_CustomColors, Localize(\"Custom colors\"), *CSkins::ms_apUCCVariables[m_TeePartSelected], &Button))\n\t\t*CSkins::ms_apUCCVariables[m_TeePartSelected] ^= 1;\n\n\tif(!(*CSkins::ms_apUCCVariables[m_TeePartSelected]))\n\t\treturn;\n\n\tMainView.HSplitTop(Spacing, 0, &MainView);\n\n\tbool Modified = false;\n\tbool UseAlpha = m_TeePartSelected == CSkins::SKINPART_TATTOO;\n\tint Color = *CSkins::ms_apColorVariables[m_TeePartSelected];\n\n\tint Hue, Sat, Lgt, Alp;\n\tHue = (Color>>16)&0xff;\n\tSat = (Color>>8)&0xff;\n\tLgt = Color&0xff;\n\tif(UseAlpha)\n\t\tAlp = (Color>>24)&0xff;\n\n\tMainView.HSplitTop(144.0f, &Picker, &MainView);\n\tRenderTools()->DrawUIRect(&Picker, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\tfloat Dark = CSkins::DARKEST_COLOR_LGT/255.0f;\n\tIGraphics::CColorVertex ColorArray[4];\n\n\t// Hue/Lgt picker :\n\t{\n\t\tPicker.VMargin((Picker.w-128)/2.0f, &Picker);\n\t\tPicker.HMargin((Picker.h-128.0f)/2.0f, &Picker);\n\n\t\t// picker\n\t\tGraphics()->TextureClear();\n\t\tGraphics()->QuadsBegin();\n\n\t\t// base: grey - hue\n\t\tvec3 c = HslToRgb(vec3(Hue/255.0f, 0.0f, 0.5f));\n\t\tColorArray[0] = IGraphics::CColorVertex(0, c.r, c.g, c.b, 1.0f);\n\t\tc = HslToRgb(vec3(Hue/255.0f, 1.0f, 0.5f));\n\t\tColorArray[1] = IGraphics::CColorVertex(1, c.r, c.g, c.b, 1.0f);\n\t\tc = HslToRgb(vec3(Hue/255.0f, 1.0f, 0.5f));\n\t\tColorArray[2] = IGraphics::CColorVertex(2, c.r, c.g, c.b, 1.0f);\n\t\tc = HslToRgb(vec3(Hue/255.0f, 0.0f, 0.5f));\n\t\tColorArray[3] = IGraphics::CColorVertex(3, c.r, c.g, c.b, 1.0f);\n\t\tGraphics()->SetColorVertex(ColorArray, 4);\n\t\tIGraphics::CQuadItem QuadItem(Picker.x, Picker.y, Picker.w, Picker.h);\n\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\n\t\t// white blending\n\t\tColorArray[0] = IGraphics::CColorVertex(0, 1.0f, 1.0f, 1.0f, 0.0f);\n\t\tColorArray[1] = IGraphics::CColorVertex(1, 1.0f, 1.0f, 1.0f, 0.0f);\n\t\tColorArray[2] = IGraphics::CColorVertex(2, 1.0f, 1.0f, 1.0f, 1.0f);\n\t\tColorArray[3] = IGraphics::CColorVertex(3, 1.0f, 1.0f, 1.0f, 1.0f);\n\t\tGraphics()->SetColorVertex(ColorArray, 4);\n\t\tIGraphics::CQuadItem WhiteGradient(Picker.x, Picker.y + Picker.h*(1-2*Dark)/((1-Dark)*2), Picker.w, Picker.h/((1-Dark)*2));\n\t\tGraphics()->QuadsDrawTL(&WhiteGradient, 1);\n\n\t\t// black blending\n\t\tColorArray[0] = IGraphics::CColorVertex(0, 0.0f, 0.0f, 0.0f, 1.0f-2*Dark);\n\t\tColorArray[1] = IGraphics::CColorVertex(1, 0.0f, 0.0f, 0.0f, 1.0f-2*Dark);\n\t\tColorArray[2] = IGraphics::CColorVertex(2, 0.0f, 0.0f, 0.0f, 0.0f);\n\t\tColorArray[3] = IGraphics::CColorVertex(3, 0.0f, 0.0f, 0.0f, 0.0f);\n\t\tGraphics()->SetColorVertex(ColorArray, 4);\n\t\tIGraphics::CQuadItem BlackGradient(Picker.x, Picker.y, Picker.w, Picker.h*(1-2*Dark)/((1-Dark)*2));\n\t\tGraphics()->QuadsDrawTL(&BlackGradient, 1);\n\n\t\tGraphics()->QuadsEnd();\n\n\t\t// marker\n\t\tvec2 Marker = vec2(Sat/2.0f*UI()->Scale(), Lgt/2.0f*UI()->Scale());\n\t\tGraphics()->TextureClear();\n\t\tGraphics()->QuadsBegin();\n\t\tGraphics()->SetColor(0.0f, 0.0f, 0.0f, 1.0f);\n\t\tIGraphics::CQuadItem aMarker[2];\n\t\taMarker[0] = IGraphics::CQuadItem(Picker.x+Marker.x, Picker.y+Marker.y - 5.0f*UI()->PixelSize(), UI()->PixelSize(), 11.0f*UI()->PixelSize());\n\t\taMarker[1] = IGraphics::CQuadItem(Picker.x+Marker.x - 5.0f*UI()->PixelSize(), Picker.y+Marker.y, 11.0f*UI()->PixelSize(), UI()->PixelSize());\n\t\tGraphics()->QuadsDrawTL(aMarker, 2);\n\t\tGraphics()->QuadsEnd();\n\n\t\t// logic\n\t\tfloat X, Y;\n\t\tstatic int s_HLPicker;\n\t\tif(UI()->DoPickerLogic(&s_HLPicker, &Picker, &X, &Y))\n\t\t{\n\t\t\tSat = (int)(255.0f*X/Picker.w);\n\t\t\tLgt = (int)(255.0f*Y/Picker.h);\n\t\t\tModified = true;\n\t\t}\n\t}\n\n\tMainView.HSplitTop(Spacing, 0, &MainView);\n\n\t// H/S/L/A sliders :\n\t{\n\t\tint NumBars = UseAlpha ? 4 : 3;\n\t\tconst char *const apNames[4] = {Localize(\"Hue:\"), Localize(\"Sat:\"), Localize(\"Lgt:\"), Localize(\"Alp:\")};\n\t\tint *const apVars[4] = {&Hue, &Sat, &Lgt, &Alp};\n\t\tstatic int s_aButtons[12];\n\t\tfloat SliderHeight = 16.0f;\n\t\tstatic const float s_aColorIndices[7][3] = {{1.0f, 0.0f, 0.0f}, {1.0f, 1.0f, 0.0f}, {0.0f, 1.0f, 0.0f},\n\t\t\t\t\t\t\t\t\t\t\t\t\t{0.0f, 1.0f, 1.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f, 1.0f}, {1.0f, 0.0f, 0.0f}};\n\n\t\tfor(int i = 0; i < NumBars; i++)\n\t\t{\n\t\t\tCUIRect Bar;\n\n\t\t\tMainView.HSplitTop(SliderHeight, &Label, &MainView);\n\t\t\tMainView.HSplitTop(Spacing, 0, &MainView);\n\n\t\t\t// label\n\t\t\tRenderTools()->DrawUIRect(&Label, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\t\t\tLabel.VSplitLeft((Label.w-160.0f)/2.0f, &Label, &Button);\n\t\t\tLabel.y += 2.0f;\n\t\t\tUI()->DoLabelScaled(&Label, apNames[i], SliderHeight*ms_FontmodHeight*0.8f, 0);\n\n\t\t\t// button <\n\t\t\tButton.VSplitLeft(Button.h, &Button, &Bar);\n\t\t\tif(DoButton_Menu(&s_aButtons[i*3], \"<\", 0, &Button, CUI::CORNER_TL|CUI::CORNER_BL))\n\t\t\t{\n\t\t\t\t*apVars[i] = max(0, *apVars[i]-1);\n\t\t\t\tModified = true;\n\t\t\t}\n\n\t\t\t// bar\n\t\t\tBar.VSplitLeft(128.0f, &Bar, &Button);\n\t\t\tint NumQuads = 1;\n\t\t\tif( i == 0)\n\t\t\t\tNumQuads = 6;\n\t\t\telse if ( i == 2)\n\t\t\t\tNumQuads = 2;\n\t\t\telse\n\t\t\t\tNumQuads = 1;\n\n\t\t\tfloat Length = Bar.w/NumQuads;\n\t\t\tfloat Offset = Length;\n\t\t\tvec4 ColorL, ColorR;\n\n\t\t\tGraphics()->TextureClear();\n\t\t\tGraphics()->QuadsBegin();\n\t\t\tfor(int j = 0; j < NumQuads; ++j)\n\t\t\t{\n\t\t\t\tswitch(i)\n\t\t\t\t{\n\t\t\t\tcase 0: // Hue\n\t\t\t\t\t{\n\t\t\t\t\t\tColorL = vec4(s_aColorIndices[j][0], s_aColorIndices[j][1], s_aColorIndices[j][2], 1.0f);\n\t\t\t\t\t\tColorR = vec4(s_aColorIndices[j+1][0], s_aColorIndices[j+1][1], s_aColorIndices[j+1][2], 1.0f);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1: // Sat\n\t\t\t\t\t{\n\t\t\t\t\t\tvec3 c = HslToRgb(vec3(Hue/255.0f, 0.0f, Dark+Lgt/255.0f*(1.0f-Dark)));\n\t\t\t\t\t\tColorL = vec4(c.r, c.g, c.b, 1.0f);\n\t\t\t\t\t\tc = HslToRgb(vec3(Hue/255.0f, 1.0f, Dark+Lgt/255.0f*(1.0f-Dark)));\n\t\t\t\t\t\tColorR = vec4(c.r, c.g, c.b, 1.0f);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2: // Lgt\n\t\t\t\t\t{\n\t\t\t\t\t\tif(j == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Dark - 0.5f\n\t\t\t\t\t\t\tvec3 c = HslToRgb(vec3(Hue/255.0f, Sat/255.0f, Dark));\n\t\t\t\t\t\t\tColorL = vec4(c.r, c.g, c.b, 1.0f);\n\t\t\t\t\t\t\tc = HslToRgb(vec3(Hue/255.0f, Sat/255.0f, 0.5f));\n\t\t\t\t\t\t\tColorR = vec4(c.r, c.g, c.b, 1.0f);\n\t\t\t\t\t\t\tLength = Offset = Bar.w - Bar.w/((1-Dark)*2);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// 0.5f - 0.0f\n\t\t\t\t\t\t\tvec3 c = HslToRgb(vec3(Hue/255.0f, Sat/255.0f, 0.5f));\n\t\t\t\t\t\t\tColorL = vec4(c.r, c.g, c.b, 1.0f);\n\t\t\t\t\t\t\tc = HslToRgb(vec3(Hue/255.0f, Sat/255.0f, 1.0f));\n\t\t\t\t\t\t\tColorR = vec4(c.r, c.g, c.b, 1.0f);\n\t\t\t\t\t\t\tLength = Bar.w/((1-Dark)*2);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: // Alpha\n\t\t\t\t\t{\n\t\t\t\t\t\tvec3 c = HslToRgb(vec3(Hue/255.0f, Sat/255.0f, Dark+Lgt/255.0f*(1.0f-Dark)));\n\t\t\t\t\t\tColorL = vec4(c.r, c.g, c.b, 0.0f);\n\t\t\t\t\t\tColorR = vec4(c.r, c.g, c.b, 1.0f);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tColorArray[0] = IGraphics::CColorVertex(0, ColorL.r, ColorL.g, ColorL.b, ColorL.a);\n\t\t\t\tColorArray[1] = IGraphics::CColorVertex(1, ColorR.r, ColorR.g, ColorR.b, ColorR.a);\n\t\t\t\tColorArray[2] = IGraphics::CColorVertex(2, ColorR.r, ColorR.g, ColorR.b, ColorR.a);\n\t\t\t\tColorArray[3] = IGraphics::CColorVertex(3, ColorL.r, ColorL.g, ColorL.b, ColorL.a);\n\t\t\t\tGraphics()->SetColorVertex(ColorArray, 4);\n\t\t\t\tIGraphics::CQuadItem QuadItem(Bar.x+Offset*j, Bar.y, Length, Bar.h);\n\t\t\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t\t\t}\n\n\t\t\t// bar marker\n\t\t\tGraphics()->SetColor(0.0f, 0.0f, 0.0f, 1.0f);\n\t\t\tIGraphics::CQuadItem QuadItem(Bar.x + min(127.0f, *apVars[i]/2.0f)*UI()->Scale(), Bar.y, UI()->PixelSize(), Bar.h);\n\t\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t\t\tGraphics()->QuadsEnd();\n\n\t\t\t// button >\n\t\t\tButton.VSplitLeft(Button.h, &Button, &Label);\n\t\t\tif(DoButton_Menu(&s_aButtons[i*3+1], \">\", 0, &Button, CUI::CORNER_TR|CUI::CORNER_BR))\n\t\t\t{\n\t\t\t\t*apVars[i] = min(255, *apVars[i]+1);\n\t\t\t\tModified = true;\n\t\t\t}\n\n\t\t\t// value label\n\t\t\tchar aBuf[16];\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"%d\", *apVars[i]);\n\t\t\tLabel.y += 2.0f;\n\t\t\tUI()->DoLabelScaled(&Label, aBuf, SliderHeight*ms_FontmodHeight*0.8f, 0);\n\n\t\t\t// logic\n\t\t\tfloat X;\n\t\t\tif(UI()->DoPickerLogic(&s_aButtons[i*3+2], &Bar, &X, 0))\n\t\t\t{\n\t\t\t\t*apVars[i] = X*255.0f/Bar.w;\n\t\t\t\tModified = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tif(Modified)\n\t{\n\t\tint NewVal = (Hue << 16) + (Sat << 8) + Lgt;\n\t\tfor(int p = 0; p < CSkins::NUM_SKINPARTS; p++)\n\t\t{\n\t\t\tif(m_TeePartSelected == p)\n\t\t\t\t*CSkins::ms_apColorVariables[p] = NewVal;\n\t\t}\n\t\tif(UseAlpha)\n\t\t\tg_Config.m_PlayerColorTattoo = (Alp << 24) + NewVal;\n\t}\n}\n\nvoid CMenus::RenderSkinSelection(CUIRect MainView)\n{\n\tstatic sorted_array<const CSkins::CSkin *> s_paSkinList;\n\tstatic float s_ScrollValue = 0.0f;\n\tif(m_RefreshSkinSelector)\n\t{\n\t\ts_paSkinList.clear();\n\t\tfor(int i = 0; i < m_pClient->m_pSkins->Num(); ++i)\n\t\t{\n\t\t\tconst CSkins::CSkin *s = m_pClient->m_pSkins->Get(i);\n\t\t\t// no special skins\n\t\t\tif((s->m_Flags&CSkins::SKINFLAG_SPECIAL) == 0)\n\t\t\t\ts_paSkinList.add(s);\n\t\t}\n\t\tm_RefreshSkinSelector = false;\n\t}\n\n\tm_pSelectedSkin = 0;\n\tint OldSelected = -1;\n\tUiDoListboxHeader(&MainView, Localize(\"Skins\"), 20.0f, 2.0f);\n\tUiDoListboxStart(&m_RefreshSkinSelector, 50.0f, 0, s_paSkinList.size(), 10, OldSelected, s_ScrollValue);\n\n\tfor(int i = 0; i < s_paSkinList.size(); ++i)\n\t{\n\t\tconst CSkins::CSkin *s = s_paSkinList[i];\n\t\tif(s == 0)\n\t\t\tcontinue;\n\t\tif(!str_comp(s->m_aName, g_Config.m_PlayerSkin))\n\t\t{\n\t\t\tm_pSelectedSkin = s;\n\t\t\tOldSelected = i;\n\t\t}\n\n\t\tCListboxItem Item = UiDoListboxNextItem(&s_paSkinList[i], OldSelected == i);\n\t\tif(Item.m_Visible)\n\t\t{\n\t\t\tCTeeRenderInfo Info;\n\t\t\tfor(int p = 0; p < CSkins::NUM_SKINPARTS; p++)\n\t\t\t{\n\t\t\t\tif(s->m_aUseCustomColors[p])\n\t\t\t\t{\n\t\t\t\t\tInfo.m_aTextures[p] = s->m_apParts[p]->m_ColorTexture;\n\t\t\t\t\tInfo.m_aColors[p] = m_pClient->m_pSkins->GetColorV4(s->m_aPartColors[p], p==CSkins::SKINPART_TATTOO);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tInfo.m_aTextures[p] = s->m_apParts[p]->m_OrgTexture;\n\t\t\t\t\tInfo.m_aColors[p] = vec4(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tInfo.m_Size = 50.0f;\n\t\t\tItem.m_Rect.HSplitTop(5.0f, 0, &Item.m_Rect); // some margin from the top\n\t\t\tRenderTools()->RenderTee(CAnimState::GetIdle(), &Info, 0, vec2(1.0f, 0.0f), vec2(Item.m_Rect.x+Item.m_Rect.w/2, Item.m_Rect.y+Item.m_Rect.h/2));\n\t\t}\n\t}\n\n\tconst int NewSelected = UiDoListboxEnd(&s_ScrollValue, 0);\n\tif(NewSelected != -1)\n\t{\n\t\tif(NewSelected != OldSelected)\n\t\t{\n\t\t\tm_pSelectedSkin = s_paSkinList[NewSelected];\n\t\t\tmem_copy(g_Config.m_PlayerSkin, m_pSelectedSkin->m_aName, sizeof(g_Config.m_PlayerSkin));\n\t\t\tfor(int p = 0; p < CSkins::NUM_SKINPARTS; p++)\n\t\t\t{\n\t\t\t\tmem_copy(CSkins::ms_apSkinVariables[p], m_pSelectedSkin->m_apParts[p]->m_aName, 24);\n\t\t\t\t*CSkins::ms_apUCCVariables[p] = m_pSelectedSkin->m_aUseCustomColors[p];\n\t\t\t\t*CSkins::ms_apColorVariables[p] = m_pSelectedSkin->m_aPartColors[p];\n\t\t\t}\n\t\t}\n\t}\n\tOldSelected = NewSelected;\n}\n\nvoid CMenus::RenderSkinPartSelection(CUIRect MainView)\n{\n\tstatic bool s_InitSkinPartList = true;\n\tstatic sorted_array<const CSkins::CSkinPart *> s_paList[6];\n\tstatic float s_ScrollValue = 0.0f;\n\tif(s_InitSkinPartList)\n\t{\n\t\tfor(int p = 0; p < CSkins::NUM_SKINPARTS; p++)\n\t\t{\n\t\t\ts_paList[p].clear();\n\t\t\tfor(int i = 0; i < m_pClient->m_pSkins->NumSkinPart(p); ++i)\n\t\t\t{\n\t\t\t\tconst CSkins::CSkinPart *s = m_pClient->m_pSkins->GetSkinPart(p, i);\n\t\t\t\t// no special skins\n\t\t\t\tif((s->m_Flags&CSkins::SKINFLAG_SPECIAL) == 0)\n\t\t\t\t\ts_paList[p].add(s);\n\t\t\t}\n\t\t}\n\t\ts_InitSkinPartList = false;\n\t}\n\n\tstatic int OldSelected = -1;\n\tUiDoListboxHeader(&MainView, CSkins::ms_apSkinPartNames[m_TeePartSelected], 20.0f, 2.0f);\n\tUiDoListboxStart(&s_InitSkinPartList, 50.0f, 0, s_paList[m_TeePartSelected].size(), 5, OldSelected, s_ScrollValue);\n\n\tfor(int i = 0; i < s_paList[m_TeePartSelected].size(); ++i)\n\t{\n\t\tconst CSkins::CSkinPart *s = s_paList[m_TeePartSelected][i];\n\t\tif(s == 0)\n\t\t\tcontinue;\n\t\tif(!str_comp(s->m_aName, CSkins::ms_apSkinVariables[m_TeePartSelected]))\n\t\t\tOldSelected = i;\n\n\t\tCListboxItem Item = UiDoListboxNextItem(&s_paList[m_TeePartSelected][i], OldSelected == i);\n\t\tif(Item.m_Visible)\n\t\t{\n\t\t\tCTeeRenderInfo Info;\n\t\t\tfor(int j = 0; j < CSkins::NUM_SKINPARTS; j++)\n\t\t\t{\n\t\t\t\tint SkinPart = m_pClient->m_pSkins->FindSkinPart(j, CSkins::ms_apSkinVariables[j], false);\n\t\t\t\tconst CSkins::CSkinPart *pSkinPart = m_pClient->m_pSkins->GetSkinPart(j, SkinPart);\n\t\t\t\tif(*CSkins::ms_apUCCVariables[j])\n\t\t\t\t{\n\t\t\t\t\tif(m_TeePartSelected == j)\n\t\t\t\t\t\tInfo.m_aTextures[j] = s->m_ColorTexture;\n\t\t\t\t\telse\n\t\t\t\t\t\tInfo.m_aTextures[j] = pSkinPart->m_ColorTexture;\n\t\t\t\t\tInfo.m_aColors[j] = m_pClient->m_pSkins->GetColorV4(*CSkins::ms_apColorVariables[j], j==CSkins::SKINPART_TATTOO);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif(m_TeePartSelected == j)\n\t\t\t\t\t\tInfo.m_aTextures[j] = s->m_OrgTexture;\n\t\t\t\t\telse\n\t\t\t\t\t\tInfo.m_aTextures[j] = pSkinPart->m_OrgTexture;\n\t\t\t\t\tInfo.m_aColors[j] = vec4(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\t\t}\n\t\t\t}\n\t\t\tInfo.m_Size = 50.0f;\n\t\t\tItem.m_Rect.HSplitTop(5.0f, 0, &Item.m_Rect); // some margin from the top\n\t\t\tRenderTools()->RenderTee(CAnimState::GetIdle(), &Info, 0, vec2(1.0f, 0.0f), vec2(Item.m_Rect.x+Item.m_Rect.w/2, Item.m_Rect.y+Item.m_Rect.h/2));\n\t\t}\n\t}\n\n\tconst int NewSelected = UiDoListboxEnd(&s_ScrollValue, 0);\n\tif(NewSelected != -1)\n\t{\n\t\tif(NewSelected != OldSelected)\n\t\t{\n\t\t\tconst CSkins::CSkinPart *s = s_paList[m_TeePartSelected][NewSelected];\n\t\t\tmem_copy(CSkins::ms_apSkinVariables[m_TeePartSelected], s->m_aName, 24);\n\t\t\tg_Config.m_PlayerSkin[0] = 0;\n\t\t}\n\t}\n\tOldSelected = NewSelected;\n}\n\nclass CLanguage\n{\npublic:\n\tCLanguage() {}\n\tCLanguage(const char *n, const char *f, int Code) : m_Name(n), m_FileName(f), m_CountryCode(Code) {}\n\n\tstring m_Name;\n\tstring m_FileName;\n\tint m_CountryCode;\n\n\tbool operator<(const CLanguage &Other) { return m_Name < Other.m_Name; }\n};\n\nvoid LoadLanguageIndexfile(IStorage *pStorage, IConsole *pConsole, sorted_array<CLanguage> *pLanguages)\n{\n\t// read file data into buffer\n\tconst char *pFilename = \"languages/index.json\";\n\tIOHANDLE File = pStorage->OpenFile(pFilename, IOFLAG_READ, IStorage::TYPE_ALL);\n\tif(!File)\n\t{\n\t\tpConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"localization\", \"couldn't open index file\");\n\t\treturn;\n\t}\n\tint FileSize = (int)io_length(File);\n\tchar *pFileData = (char *)mem_alloc(FileSize+1, 1);\n\tio_read(File, pFileData, FileSize);\n\tpFileData[FileSize] = 0;\n\tio_close(File);\n\n\t// parse json data\n\tjson_settings JsonSettings;\n\tmem_zero(&JsonSettings, sizeof(JsonSettings));\n\tchar aError[256];\n\tjson_value *pJsonData = json_parse_ex(&JsonSettings, pFileData, aError);\n\tif(pJsonData == 0)\n\t{\n\t\tpConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, pFilename, aError);\n\t\tmem_free(pFileData);\n\t\treturn;\n\t}\n\n\t// extract data\n\tconst json_value &rStart = (*pJsonData)[\"language indices\"];\n\tif(rStart.type == json_array)\n\t{\n\t\tfor(unsigned i = 0; i < rStart.u.array.length; ++i)\n\t\t{\n\t\t\tchar aFileName[128];\n\t\t\tstr_format(aFileName, sizeof(aFileName), \"languages/%s.json\", (const char *)rStart[i][\"file\"]);\n\t\t\tpLanguages->add(CLanguage((const char *)rStart[i][\"name\"], aFileName, (long)rStart[i][\"code\"]));\n\t\t}\n\t}\n\n\t// clean up\n\tjson_value_free(pJsonData);\n\tmem_free(pFileData);\n}\n\nvoid CMenus::RenderLanguageSelection(CUIRect MainView, bool Header)\n{\n\tstatic int s_LanguageList = 0;\n\tstatic int s_SelectedLanguage = 0;\n\tstatic sorted_array<CLanguage> s_Languages;\n\tstatic float s_ScrollValue = 0;\n\n\tif(s_Languages.size() == 0)\n\t{\n\t\ts_Languages.add(CLanguage(\"English\", \"\", 826));\n\t\tLoadLanguageIndexfile(Storage(), Console(), &s_Languages);\n\t\tfor(int i = 0; i < s_Languages.size(); i++)\n\t\t\tif(str_comp(s_Languages[i].m_FileName, g_Config.m_ClLanguagefile) == 0)\n\t\t\t{\n\t\t\t\ts_SelectedLanguage = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n\n\tint OldSelected = s_SelectedLanguage;\n\n\tif(Header)\n\t\tUiDoListboxHeader(&MainView, Localize(\"Language\"), 20.0f, 2.0f);\n\tUiDoListboxStart(&s_LanguageList, 20.0f, 0, s_Languages.size(), 1, s_SelectedLanguage, s_ScrollValue, Header?0:&MainView, Header?true:false);\n\n\tfor(sorted_array<CLanguage>::range r = s_Languages.all(); !r.empty(); r.pop_front())\n\t{\n\t\tCListboxItem Item = UiDoListboxNextItem(&r.front());\n\n\t\tif(Item.m_Visible)\n\t\t{\n\t\t\tCUIRect Rect;\n\t\t\tItem.m_Rect.VSplitLeft(Item.m_Rect.h*2.0f, &Rect, &Item.m_Rect);\n\t\t\tRect.VMargin(6.0f, &Rect);\n\t\t\tRect.HMargin(3.0f, &Rect);\n\t\t\tvec4 Color(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\tm_pClient->m_pCountryFlags->Render(r.front().m_CountryCode, &Color, Rect.x, Rect.y, Rect.w, Rect.h);\n\t\t\tItem.m_Rect.y += 2.0f;\n\t\t\tif(!str_comp(s_Languages[s_SelectedLanguage].m_Name, r.front().m_Name))\n\t\t\t{\n\t\t\t\tTextRender()->TextColor(0.0f, 0.0f, 0.0f, 1.0f);\n\t\t\t\tTextRender()->TextOutlineColor(1.0f, 1.0f, 1.0f, 0.25f);\n\t\t\t\tUI()->DoLabelScaled(&Item.m_Rect, r.front().m_Name, Item.m_Rect.h*ms_FontmodHeight*0.8f, -1);\n\t\t\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\t\tTextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f);\n\t\t\t}\n\t\t\telse\n \t\t\t\tUI()->DoLabelScaled(&Item.m_Rect, r.front().m_Name, Item.m_Rect.h*ms_FontmodHeight*0.8f, -1);\n\t\t}\n\t}\n\n\ts_SelectedLanguage = UiDoListboxEnd(&s_ScrollValue, 0);\n\n\tif(OldSelected != s_SelectedLanguage)\n\t{\n\t\tstr_copy(g_Config.m_ClLanguagefile, s_Languages[s_SelectedLanguage].m_FileName, sizeof(g_Config.m_ClLanguagefile));\n\t\tg_Localization.Load(s_Languages[s_SelectedLanguage].m_FileName, Storage(), Console());\n\t}\n}\n\nvoid CMenus::RenderSettingsGeneral(CUIRect MainView)\n{\n\tCUIRect Label, Button, Game, Client, BottomView;\n\n\t// cut view\n\tMainView.HSplitBottom(80.0f, &MainView, &BottomView);\n\tBottomView.HSplitTop(20.f, 0, &BottomView);\n\n\t// render game menu backgrounds\n\tint NumOptions = g_Config.m_ClNameplates ? 8 : 5;\n\tfloat ButtonHeight = 20.0f;\n\tfloat Spacing = 2.0f;\n\tfloat BackgroundHeight = (float)(NumOptions+1)*ButtonHeight+(float)NumOptions*Spacing;\n\n\tMainView.HSplitTop(20.0f, 0, &MainView);\n\tMainView.HSplitTop(BackgroundHeight, &Game, &MainView);\n\tRenderTools()->DrawUIRect(&Game, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\t// render client menu background\n\tNumOptions = 2;\n\tif(g_Config.m_ClAutoDemoRecord) NumOptions += 1;\n\tif(g_Config.m_ClAutoScreenshot) NumOptions += 1;\n\tBackgroundHeight = (float)(NumOptions+1)*ButtonHeight+(float)NumOptions*Spacing;\n\n\tMainView.HSplitTop(10.0f, 0, &MainView);\n\tMainView.HSplitTop(BackgroundHeight, &Client, &MainView);\n\tRenderTools()->DrawUIRect(&Client, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\t// render game menu\n\tGame.HSplitTop(ButtonHeight, &Label, &Game);\n\tLabel.y += 2.0f;\n\tUI()->DoLabel(&Label, Localize(\"Game\"), ButtonHeight*ms_FontmodHeight*0.8f, 0);\n\n\tGame.HSplitTop(Spacing, 0, &Game);\n\tGame.HSplitTop(ButtonHeight, &Button, &Game);\n\tstatic int s_DynamicCameraButton = 0;\n\tif(DoButton_CheckBox(&s_DynamicCameraButton, Localize(\"Dynamic Camera\"), g_Config.m_ClMouseDeadzone != 0, &Button))\n\t{\n\t\tif(g_Config.m_ClMouseDeadzone)\n\t\t{\n\t\t\tg_Config.m_ClMouseFollowfactor = 0;\n\t\t\tg_Config.m_ClMouseMaxDistance = 400;\n\t\t\tg_Config.m_ClMouseDeadzone = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tg_Config.m_ClMouseFollowfactor = 60;\n\t\t\tg_Config.m_ClMouseMaxDistance = 1000;\n\t\t\tg_Config.m_ClMouseDeadzone = 300;\n\t\t}\n\t}\n\n\tGame.HSplitTop(Spacing, 0, &Game);\n\tGame.HSplitTop(ButtonHeight, &Button, &Game);\n\tstatic int s_AutoswitchWeapons = 0;\n\tif(DoButton_CheckBox(&s_AutoswitchWeapons, Localize(\"Switch weapon on pickup\"), g_Config.m_ClAutoswitchWeapons, &Button))\n\t\tg_Config.m_ClAutoswitchWeapons ^= 1;\n\n\tGame.HSplitTop(Spacing, 0, &Game);\n\tGame.HSplitTop(ButtonHeight, &Button, &Game);\n\tstatic int s_Showhud = 0;\n\tif(DoButton_CheckBox(&s_Showhud, Localize(\"Show ingame HUD\"), g_Config.m_ClShowhud, &Button))\n\t\tg_Config.m_ClShowhud ^= 1;\n\n\tGame.HSplitTop(Spacing, 0, &Game);\n\tGame.HSplitTop(ButtonHeight, &Button, &Game);\n\tstatic int s_Friendchat = 0;\n\tif(DoButton_CheckBox(&s_Friendchat, Localize(\"Show only chat messages from friends\"), g_Config.m_ClShowChatFriends, &Button))\n\t\tg_Config.m_ClShowChatFriends ^= 1;\n\n\tGame.HSplitTop(Spacing, 0, &Game);\n\tGame.HSplitTop(ButtonHeight, &Button, &Game);\n\tstatic int s_Nameplates = 0;\n\tif(DoButton_CheckBox(&s_Nameplates, Localize(\"Show name plates\"), g_Config.m_ClNameplates, &Button))\n\t\tg_Config.m_ClNameplates ^= 1;\n\n\tif(g_Config.m_ClNameplates)\n\t{\n\t\tGame.HSplitTop(Spacing, 0, &Game);\n\t\tGame.HSplitTop(ButtonHeight, &Button, &Game);\n\t\tButton.VSplitLeft(ButtonHeight, 0, &Button);\n\t\tstatic int s_NameplatesAlways = 0;\n\t\tif(DoButton_CheckBox(&s_NameplatesAlways, Localize(\"Always show name plates\"), g_Config.m_ClNameplatesAlways, &Button))\n\t\t\tg_Config.m_ClNameplatesAlways ^= 1;\n\n\t\tGame.HSplitTop(Spacing, 0, &Game);\n\t\tGame.HSplitTop(ButtonHeight, &Button, &Game);\n\t\tButton.VSplitLeft(ButtonHeight, 0, &Button);\n\t\tDoScrollbarOption(&g_Config.m_ClNameplatesSize, &g_Config.m_ClNameplatesSize, &Button, Localize(\"Size\"), 100.0f, 0, 100);\n\n\t\tGame.HSplitTop(Spacing, 0, &Game);\n\t\tGame.HSplitTop(ButtonHeight, &Button, &Game);\n\t\tButton.VSplitLeft(ButtonHeight, 0, &Button);\n\t\tstatic int s_NameplatesTeamcolors = 0;\n\t\tif(DoButton_CheckBox(&s_NameplatesTeamcolors, Localize(\"Use team colors for name plates\"), g_Config.m_ClNameplatesTeamcolors, &Button))\n\t\t\tg_Config.m_ClNameplatesTeamcolors ^= 1;\n\t}\n\n\t// render client menu\n\tClient.HSplitTop(ButtonHeight, &Label, &Client);\n\tLabel.y += 2.0f;\n\tUI()->DoLabel(&Label, Localize(\"Client\"), ButtonHeight*ms_FontmodHeight*0.8f, 0);\n\n\tClient.HSplitTop(Spacing, 0, &Client);\n\tClient.HSplitTop(ButtonHeight, &Button, &Client);\n\tstatic int s_AutoDemoRecord = 0;\n\tif(DoButton_CheckBox(&s_AutoDemoRecord, Localize(\"Automatically record demos\"), g_Config.m_ClAutoDemoRecord, &Button))\n\t\tg_Config.m_ClAutoDemoRecord ^= 1;\n\n\tif(g_Config.m_ClAutoDemoRecord)\n\t{\n\t\tClient.HSplitTop(Spacing, 0, &Client);\n\t\tClient.HSplitTop(ButtonHeight, &Button, &Client);\n\t\tButton.VSplitLeft(ButtonHeight, 0, &Button);\n\t\tDoScrollbarOption(&g_Config.m_ClAutoDemoMax, &g_Config.m_ClAutoDemoMax, &Button, Localize(\"Max\"), 100.0f, 0, 1000, true);\n\t}\n\n\tClient.HSplitTop(Spacing, 0, &Client);\n\tClient.HSplitTop(ButtonHeight, &Button, &Client);\n\tstatic int s_AutoScreenshot = 0;\n\tif(DoButton_CheckBox(&s_AutoScreenshot, Localize(\"Automatically take game over screenshot\"), g_Config.m_ClAutoScreenshot, &Button))\n\t\tg_Config.m_ClAutoScreenshot ^= 1;\n\n\tif(g_Config.m_ClAutoScreenshot)\n\t{\n\t\tClient.HSplitTop(Spacing, 0, &Client);\n\t\tClient.HSplitTop(ButtonHeight, &Button, &Client);\n\t\tButton.VSplitLeft(ButtonHeight, 0, &Button);\n\t\tDoScrollbarOption(&g_Config.m_ClAutoScreenshotMax, &g_Config.m_ClAutoScreenshotMax, &Button, Localize(\"Max\"), 100.0f, 0, 1000, true);\n\t}\n\n\tMainView.HSplitTop(10.0f, 0, &MainView);\n\n\t// render language selection\n\tRenderLanguageSelection(MainView);\n\n\t// reset button\n\tSpacing = 3.0f;\n\tfloat ButtonWidth = (BottomView.w/6.0f)-(Spacing*5.0)/6.0f;\n\n\tBottomView.VSplitRight(ButtonWidth, 0, &BottomView);\n\tRenderTools()->DrawUIRect4(&BottomView, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f);\n\n\tBottomView.HSplitTop(25.0f, &BottomView, 0);\n\tButton = BottomView;\n\tstatic int s_ResetButton=0;\n\tif(DoButton_Menu(&s_ResetButton, Localize(\"Reset\"), 0, &Button))\n\t{\n\t\tg_Config.m_ClMouseFollowfactor = 60;\n\t\tg_Config.m_ClMouseMaxDistance = 1000;\n\t\tg_Config.m_ClMouseDeadzone = 300;\n\t\tg_Config.m_ClAutoswitchWeapons = 1;\n\t\tg_Config.m_ClShowhud = 1;\n\t\tg_Config.m_ClShowChatFriends = 0;\n\t\tg_Config.m_ClNameplates = 1;\n\t\tg_Config.m_ClNameplatesAlways = 1;\n\t\tg_Config.m_ClNameplatesSize = 50;\n\t\tg_Config.m_ClNameplatesTeamcolors = 1;\n\t\tg_Config.m_ClAutoDemoRecord = 0;\n\t\tg_Config.m_ClAutoDemoMax = 10;\n\t\tg_Config.m_ClAutoScreenshot = 0;\n\t\tg_Config.m_ClAutoScreenshotMax = 10;\n\t}\n}\n\nvoid CMenus::RenderSettingsPlayer(CUIRect MainView)\n{\n\tCUIRect Button, Left, Right, TopView, Label;\n\n\t// render game menu backgrounds\n\tfloat ButtonHeight = 20.0f;\n\tfloat Spacing = 2.0f;\n\tfloat BackgroundHeight = 2.0f*ButtonHeight+Spacing;\n\n\tMainView.HSplitTop(20.0f, 0, &MainView);\n\tMainView.HSplitBottom(80.0f, &MainView, 0); // now we have the total rect for the settings\n\tMainView.HSplitTop(BackgroundHeight, &TopView, &MainView);\n\tRenderTools()->DrawUIRect(&TopView, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\t// render game menu\n\tTopView.HSplitTop(ButtonHeight, &Label, &TopView);\n\tLabel.y += 2.0f;\n\tUI()->DoLabel(&Label, Localize(\"Personal\"), ButtonHeight*ms_FontmodHeight*0.8f, 0);\n\n\t// split menu\n\tTopView.HSplitTop(Spacing, 0, &TopView);\n\tTopView.VSplitMid(&Left, &Right);\n\tLeft.VSplitRight(1.5f, &Left, 0);\n\tRight.VSplitLeft(1.5f, 0, &Right);\n\n\t// left menu\n\tLeft.HSplitTop(ButtonHeight, &Button, &Left);\n\tstatic float s_OffsetName = 0.0f;\n\tDoEditBoxOption(g_Config.m_PlayerName, g_Config.m_PlayerName, sizeof(g_Config.m_PlayerName), &Button, Localize(\"Name\"),  100.0f, &s_OffsetName);\n\n\t// right menu\n\tRight.HSplitTop(ButtonHeight, &Button, &Right);\n\tstatic float s_OffsetClan = 0.0f;\n\tDoEditBoxOption(g_Config.m_PlayerClan, g_Config.m_PlayerClan, sizeof(g_Config.m_PlayerClan), &Button, Localize(\"Clan\"),  100.0f, &s_OffsetClan);\n\n\t// country flag selector\n\tMainView.HSplitTop(10.0f, 0, &MainView);\n\tstatic float s_ScrollValue = 0.0f;\n\tint OldSelected = -1;\n\tUiDoListboxHeader(&MainView, Localize(\"Country\"), 20.0f, 2.0f);\n\tUiDoListboxStart(&s_ScrollValue, 40.0f, 0, m_pClient->m_pCountryFlags->Num(), 18, OldSelected, s_ScrollValue);\n\n\tfor(int i = 0; i < m_pClient->m_pCountryFlags->Num(); ++i)\n\t{\n\t\tconst CCountryFlags::CCountryFlag *pEntry = m_pClient->m_pCountryFlags->GetByIndex(i);\n\t\tif(pEntry->m_CountryCode == g_Config.m_PlayerCountry)\n\t\t\tOldSelected = i;\n\n\t\tCListboxItem Item = UiDoListboxNextItem(&pEntry->m_CountryCode, OldSelected == i);\n\t\tif(Item.m_Visible)\n\t\t{\n\t\t\tCUIRect Label;\n\t\t\tItem.m_Rect.Margin(5.0f, &Item.m_Rect);\n\t\t\tItem.m_Rect.HSplitBottom(10.0f, &Item.m_Rect, &Label);\n\t\t\tfloat OldWidth = Item.m_Rect.w;\n\t\t\tItem.m_Rect.w = Item.m_Rect.h*2;\n\t\t\tItem.m_Rect.x += (OldWidth-Item.m_Rect.w)/ 2.0f;\n\t\t\tGraphics()->TextureSet(pEntry->m_Texture);\n\t\t\tGraphics()->QuadsBegin();\n\t\t\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\tIGraphics::CQuadItem QuadItem(Item.m_Rect.x, Item.m_Rect.y, Item.m_Rect.w, Item.m_Rect.h);\n\t\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t\t\tGraphics()->QuadsEnd();\n\t\t\tif(i == OldSelected)\n\t\t\t{\n\t\t\t\tTextRender()->TextColor(0.0f, 0.0f, 0.0f, 1.0f);\n\t\t\t\tTextRender()->TextOutlineColor(1.0f, 1.0f, 1.0f, 0.25f);\n\t\t\t\tUI()->DoLabel(&Label, pEntry->m_aCountryCodeString, 10.0f, 0);\n\t\t\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\t\tTextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f);\n\t\t\t}\n\t\t\telse\n\t\t\t\tUI()->DoLabel(&Label, pEntry->m_aCountryCodeString, 10.0f, 0);\n\t\t}\n\t}\n\n\tconst int NewSelected = UiDoListboxEnd(&s_ScrollValue, 0);\n\tif(OldSelected != NewSelected)\n\t{\n\t\tg_Config.m_PlayerCountry = m_pClient->m_pCountryFlags->GetByIndex(NewSelected)->m_CountryCode;\n\t}\n}\n\nvoid CMenus::RenderSettingsTeeBasic(CUIRect MainView)\n{\n\tRenderSkinSelection(MainView); // yes thats all here ^^\n}\n\nvoid CMenus::RenderSettingsTeeCustom(CUIRect MainView)\n{\n\tCUIRect Label, Patterns, Button, Left, Right;\n\n\t// render skin preview background\n\tfloat SpacingH = 2.0f;\n\tfloat SpacingW = 3.0f;\n\tfloat ButtonHeight = 20.0f;\n\tfloat BoxSize = 297.0f;\n\tfloat BackgroundHeight = (ButtonHeight+SpacingH)*3.0f+BoxSize;\n\n\tMainView.HSplitTop(BackgroundHeight, &MainView, 0);\n\tRenderTools()->DrawUIRect(&MainView, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\tMainView.HSplitTop(ButtonHeight, &Label, &MainView);\n\tLabel.y += 2.0f;\n\tUI()->DoLabel(&Label, Localize(\"Customize\"), ButtonHeight*ms_FontmodHeight*0.8f, 0);\n\n\t// skin part selection\n\tMainView.HSplitTop(SpacingH, 0, &MainView);\n\tMainView.HSplitTop(ButtonHeight, &Patterns, &MainView);\n\tRenderTools()->DrawUIRect(&Patterns, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\tfloat ButtonWidth = (Patterns.w/6.0f)-(SpacingW*5.0)/6.0f;\n\n\tstatic int s_aPatternButtons[6] = {0};\n\tfor(int i = 0; i < CSkins::NUM_SKINPARTS; i++)\n\t{\n\t\tPatterns.VSplitLeft(ButtonWidth, &Button, &Patterns);\n\t\tif(DoButton_MenuTabTop(&s_aPatternButtons[i], CSkins::ms_apSkinPartNames[i], m_TeePartSelected==i, &Button))\n\t\t{\n\t\t\tm_TeePartSelected = i;\n\t\t}\n\t\tPatterns.VSplitLeft(SpacingW, 0, &Patterns);\n\t}\n\n\tMainView.HSplitTop(SpacingH, 0, &MainView);\n\tMainView.VSplitMid(&Left, &Right);\n\tLeft.VSplitRight(SpacingW/2.0f, &Left, 0);\n\tRight.VSplitLeft(SpacingW/2.0f, 0, &Right);\n\n\t// part selection\n\tRenderSkinPartSelection(Left);\n\n\t// HSL picker\n\tRenderHSLPicker(Right);\n}\n\nvoid CMenus::RenderSettingsTee(CUIRect MainView)\n{\n\tstatic bool s_CustomSkinMenu = false;\n\n\tCUIRect Button, Label, BottomView, Preview;\n\n\t// cut view\n\tMainView.HSplitBottom(80.0f, &MainView, &BottomView);\n\tBottomView.HSplitTop(20.f, 0, &BottomView);\n\n\t// render skin preview background\n\tfloat SpacingH = 2.0f;\n\tfloat SpacingW = 3.0f;\n\tfloat ButtonHeight = 20.0f;\n\tfloat SkinHeight = 50.0f;\n\tfloat BackgroundHeight = ButtonHeight+SpacingH+SkinHeight;\n\tif(!s_CustomSkinMenu)\n\t\tBackgroundHeight = (ButtonHeight+SpacingH)*2.0f+SkinHeight;\n\n\tMainView.HSplitTop(20.0f, 0, &MainView);\n\tMainView.HSplitTop(BackgroundHeight, &Preview, &MainView);\n\tRenderTools()->DrawUIRect(&Preview, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\tPreview.HSplitTop(ButtonHeight, &Label, &Preview);\n\tLabel.y += 2.0f;\n\tUI()->DoLabel(&Label, Localize(\"Skin\"), ButtonHeight*ms_FontmodHeight*0.8f, 0);\n\n\t// Preview\n\t{\n\t\tCUIRect Left, Right;\n\t\tPreview.HSplitTop(SpacingH, 0, &Preview);\n\t\tPreview.HSplitTop(SkinHeight, &Left, &Preview);\n\n\t\t// split the menu in 2 parts\n\t\tLeft.VSplitMid(&Left, &Right);\n\t\tLeft.VSplitRight(SpacingW/2.0f, &Left, 0);\n\t\tRight.VSplitLeft(SpacingW/2.0f, 0, &Right);\n\n\t\t// handle left\n\t\tRenderTools()->DrawUIRect(&Left, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\t\tLeft.VSplitMid(&Label, &Left);\n\t\tLabel.y += 17.0f;\n\t\tUI()->DoLabelScaled(&Label, Localize(\"Normal:\"), ButtonHeight*ms_FontmodHeight*0.8f, 0);\n\n\t\tRenderTools()->DrawUIRect(&Left, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\t\tCTeeRenderInfo OwnSkinInfo;\n\t\tOwnSkinInfo.m_Size = 50.0f;\n\t\tfor(int p = 0; p < CSkins::NUM_SKINPARTS; p++)\n\t\t{\n\t\t\tint SkinPart = m_pClient->m_pSkins->FindSkinPart(p, CSkins::ms_apSkinVariables[p], false);\n\t\t\tconst CSkins::CSkinPart *pSkinPart = m_pClient->m_pSkins->GetSkinPart(p, SkinPart);\n\t\t\tif(*CSkins::ms_apUCCVariables[p])\n\t\t\t{\n\t\t\t\tOwnSkinInfo.m_aTextures[p] = pSkinPart->m_ColorTexture;\n\t\t\t\tOwnSkinInfo.m_aColors[p] = m_pClient->m_pSkins->GetColorV4(*CSkins::ms_apColorVariables[p], p==CSkins::SKINPART_TATTOO);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tOwnSkinInfo.m_aTextures[p] = pSkinPart->m_OrgTexture;\n\t\t\t\tOwnSkinInfo.m_aColors[p] = vec4(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\t}\n\t\t}\n\t\tRenderTools()->RenderTee(CAnimState::GetIdle(), &OwnSkinInfo, 0, vec2(1, 0), vec2(Left.x+Left.w/2.0f, Left.y+Left.h/2.0f+2.0f));\n\n\t\t// handle right (team skins)\n\t\tRenderTools()->DrawUIRect(&Right, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\t\tRight.VSplitLeft(Right.w/3.0f+SpacingW/2.0f, &Label, &Right);\n\t\tLabel.y += 17.0f;\n\t\tUI()->DoLabelScaled(&Label, Localize(\"Team:\"), ButtonHeight*ms_FontmodHeight*0.8f, 0);\n\n\t\tRight.VSplitMid(&Left, &Right);\n\t\tLeft.VSplitRight(SpacingW/2.0f, &Left, 0);\n\t\tRight.VSplitLeft(SpacingW/2.0f, 0, &Right);\n\n\t\tRenderTools()->DrawUIRect(&Left, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\t\tfor(int p = 0; p < CSkins::NUM_SKINPARTS; p++)\n\t\t{\n\t\t\tint TeamColor = m_pClient->m_pSkins->GetTeamColor(*CSkins::ms_apUCCVariables[p], *CSkins::ms_apColorVariables[p], TEAM_RED, p);\n\t\t\tOwnSkinInfo.m_aColors[p] = m_pClient->m_pSkins->GetColorV4(TeamColor, p==CSkins::SKINPART_TATTOO);\n\t\t}\n\t\tRenderTools()->RenderTee(CAnimState::GetIdle(), &OwnSkinInfo, 0, vec2(1, 0), vec2(Left.x+Left.w/2.0f, Left.y+Left.h/2.0f+2.0f));\n\n\t\tRenderTools()->DrawUIRect(&Right, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\t\tfor(int p = 0; p < CSkins::NUM_SKINPARTS; p++)\n\t\t{\n\t\t\tint TeamColor = m_pClient->m_pSkins->GetTeamColor(*CSkins::ms_apUCCVariables[p], *CSkins::ms_apColorVariables[p], TEAM_BLUE, p);\n\t\t\tOwnSkinInfo.m_aColors[p] = m_pClient->m_pSkins->GetColorV4(TeamColor, p==CSkins::SKINPART_TATTOO);\n\t\t}\n\t\tRenderTools()->RenderTee(CAnimState::GetIdle(), &OwnSkinInfo, 0, vec2(1, 0), vec2(Right.x+Right.w/2.0f, Right.y+Right.h/2.0f+2.0f));\n\t}\n\n\tif(!s_CustomSkinMenu)\n\t{\n\t\tPreview.HSplitTop(SpacingH, 0, &Preview);\n\t\tRenderTools()->DrawUIRect(&Preview, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\t\tPreview.y += 2.0f;\n\t\tUI()->DoLabel(&Preview, g_Config.m_PlayerSkin, ButtonHeight*ms_FontmodHeight*0.8f, 0);\n\t}\n\n\tMainView.HSplitTop(10.0f, 0, &MainView);\n\n\tif(s_CustomSkinMenu)\n\t\tRenderSettingsTeeCustom(MainView);\n\telse\n\t\tRenderSettingsTeeBasic(MainView);\n\n\t// bottom button\n\tfloat ButtonWidth = (BottomView.w/6.0f)-(SpacingW*5.0)/6.0f;\n\tfloat BackgroundWidth = s_CustomSkinMenu||(m_pSelectedSkin && (m_pSelectedSkin->m_Flags&CSkins::SKINFLAG_STANDARD) == 0) ? ButtonWidth*2.0f+SpacingW : ButtonWidth;\n\n\tBottomView.VSplitRight(BackgroundWidth, 0, &BottomView);\n\tRenderTools()->DrawUIRect4(&BottomView, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f);\n\n\tBottomView.HSplitTop(25.0f, &BottomView, 0);\n\tif(s_CustomSkinMenu)\n\t{\n\t\tBottomView.VSplitLeft(ButtonWidth, &Button, &BottomView);\n\t\tstatic int s_CustomSkinSaveButton=0;\n\t\tif(DoButton_Menu(&s_CustomSkinSaveButton, Localize(\"Save\"), 0, &Button))\n\t\t\tm_Popup = POPUP_SAVE_SKIN;\n\t\tBottomView.VSplitLeft(SpacingW, 0, &BottomView);\n\t}\n\telse if(m_pSelectedSkin && (m_pSelectedSkin->m_Flags&CSkins::SKINFLAG_STANDARD) == 0)\n\t{\n\t\tBottomView.VSplitLeft(ButtonWidth, &Button, &BottomView);\n\t\tstatic int s_CustomSkinSaveButton=0;\n\t\tif(DoButton_Menu(&s_CustomSkinSaveButton, Localize(\"Delete\"), 0, &Button))\n\t\t\tm_Popup = POPUP_DELETE_SKIN;\n\t\tBottomView.VSplitLeft(SpacingW, 0, &BottomView);\n\t}\n\n\tBottomView.VSplitLeft(ButtonWidth, &Button, &BottomView);\n\tstatic int s_CustomSwitchButton=0;\n\tif(DoButton_Menu(&s_CustomSwitchButton, s_CustomSkinMenu ? Localize(\"Basic\") : Localize(\"Custom\"), 0, &Button))\n\t{\n\t\tif(s_CustomSkinMenu)\n\t\t\ts_CustomSkinMenu = false;\n\t\telse\n\t\t\ts_CustomSkinMenu = true;\n\t}\n}\n\n//typedef void (*pfnAssignFuncCallback)(CConfiguration *pConfig, int Value);\n\nvoid CMenus::RenderSettingsControls(CUIRect MainView)\n{\n\tMainView.HSplitTop(20.0f, 0, &MainView);\n\n\t// cut view\n\tCUIRect BottomView, Button;\n\tMainView.HSplitBottom(80.0f, &MainView, &BottomView);\n\tBottomView.HSplitTop(20.f, 0, &BottomView);\n\n\tfloat HeaderHeight = 20.0f;\n\n\tstatic int s_MovementDropdown = 0;\n\tfloat Split = DoDropdownMenu(&s_MovementDropdown, &MainView, Localize(\"Movement\"), HeaderHeight, RenderSettingsControlsMovement);\n\n\tMainView.HSplitTop(Split+10.0f, 0, &MainView);\n\tstatic int s_WeaponDropdown = 0;\n\tSplit = DoDropdownMenu(&s_WeaponDropdown, &MainView, Localize(\"Weapon\"), HeaderHeight, RenderSettingsControlsWeapon);\n\n\tMainView.HSplitTop(Split+10.0f, 0, &MainView);\n\tstatic int s_VotingDropdown = 0;\n\tSplit = DoDropdownMenu(&s_VotingDropdown, &MainView, Localize(\"Voting\"), HeaderHeight, RenderSettingsControlsVoting);\n\n\tMainView.HSplitTop(Split+10.0f, 0, &MainView);\n\tstatic int s_ChatDropdown = 0;\n\tSplit = DoDropdownMenu(&s_ChatDropdown, &MainView, Localize(\"Chat\"), HeaderHeight, RenderSettingsControlsChat);\n\n\tMainView.HSplitTop(Split+10.0f, 0, &MainView);\n\tstatic int s_MiscDropdown = 0;\n\tSplit = DoDropdownMenu(&s_MiscDropdown, &MainView, Localize(\"Misc\"), HeaderHeight, RenderSettingsControlsMisc);\n\n\t// reset button\n\tfloat Spacing = 3.0f;\n\tfloat ButtonWidth = (BottomView.w/6.0f)-(Spacing*5.0)/6.0f;\n\n\tBottomView.VSplitRight(ButtonWidth, 0, &BottomView);\n\tRenderTools()->DrawUIRect4(&BottomView, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f);\n\n\tBottomView.HSplitTop(25.0f, &BottomView, 0);\n\tButton = BottomView;\n\tstatic int s_ResetButton=0;\n\tif(DoButton_Menu(&s_ResetButton, Localize(\"Reset\"), 0, &Button))\n\t\tm_pClient->m_pBinds->SetDefaults();\n}\n\nvoid CMenus::RenderSettingsGraphics(CUIRect MainView)\n{\n\tchar aBuf[128];\n\tbool CheckSettings = false;\n\n\tstatic int s_GfxScreenWidth = g_Config.m_GfxScreenWidth;\n\tstatic int s_GfxScreenHeight = g_Config.m_GfxScreenHeight;\n\tstatic int s_GfxBorderless = g_Config.m_GfxBorderless;\n\tstatic int s_GfxFullscreen = g_Config.m_GfxFullscreen;\n\tstatic int s_GfxVsync = g_Config.m_GfxVsync;\n\tstatic int s_GfxFsaaSamples = g_Config.m_GfxFsaaSamples;\n\tstatic int s_GfxTextureQuality = g_Config.m_GfxTextureQuality;\n\tstatic int s_GfxTextureCompression = g_Config.m_GfxTextureCompression;\n\n\tCUIRect Label, Button, Screen, Texture, BottomView;\n\n\t// cut view\n\tMainView.HSplitBottom(80.0f, &MainView, &BottomView);\n\tBottomView.HSplitTop(20.f, 0, &BottomView);\n\n\t// render screen menu background\n\tint NumOptions = g_Config.m_GfxFullscreen ? 3 : 4;\n\tfloat ButtonHeight = 20.0f;\n\tfloat Spacing = 2.0f;\n\tfloat BackgroundHeight = (float)(NumOptions+1)*ButtonHeight+(float)NumOptions*Spacing;\n\n\tMainView.HSplitTop(20.0f, 0, &MainView);\n\tMainView.HSplitTop(BackgroundHeight, &Screen, &MainView);\n\tRenderTools()->DrawUIRect(&Screen, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\t// render textures menu background\n\tNumOptions = 3;\n\tBackgroundHeight = (float)(NumOptions+1)*ButtonHeight+(float)NumOptions*Spacing;\n\n\tMainView.HSplitTop(10.0f, 0, &MainView);\n\tMainView.HSplitTop(BackgroundHeight, &Texture, &MainView);\n\tRenderTools()->DrawUIRect(&Texture, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\t// render screen menu\n\tScreen.HSplitTop(ButtonHeight, &Label, &Screen);\n\tLabel.y += 2.0f;\n\tUI()->DoLabel(&Label, Localize(\"Screen\"), ButtonHeight*ms_FontmodHeight*0.8f, 0);\n\n\tScreen.HSplitTop(Spacing, 0, &Screen);\n\tScreen.HSplitTop(ButtonHeight, &Button, &Screen);\n\tstatic int s_ButtonGfxFullscreen = 0;\n\tif(DoButton_CheckBox(&s_ButtonGfxFullscreen, Localize(\"Fullscreen\"), g_Config.m_GfxFullscreen, &Button))\n\t{\n\t\tg_Config.m_GfxFullscreen ^= 1;\n\t\tif(g_Config.m_GfxFullscreen && g_Config.m_GfxBorderless)\n\t\t\tg_Config.m_GfxBorderless = 0;\n\t\tCheckSettings = true;\n\t}\n\n\tif(!g_Config.m_GfxFullscreen)\n\t{\n\t\tScreen.HSplitTop(Spacing, 0, &Screen);\n\t\tScreen.HSplitTop(ButtonHeight, &Button, &Screen);\n\t\tButton.VSplitLeft(ButtonHeight, 0, &Button);\n\t\tstatic int s_ButtonGfxBorderless = 0;\n\t\tif(DoButton_CheckBox(&s_ButtonGfxBorderless, Localize(\"Borderless window\"), g_Config.m_GfxBorderless, &Button))\n\t\t{\n\t\t\tg_Config.m_GfxBorderless ^= 1;\n\t\t\tif(g_Config.m_GfxBorderless && g_Config.m_GfxFullscreen)\n\t\t\t\tg_Config.m_GfxFullscreen = 0;\n\t\t\tCheckSettings = true;\n\t\t}\n\t}\n\n\tScreen.HSplitTop(Spacing, 0, &Screen);\n\tScreen.HSplitTop(ButtonHeight, &Button, &Screen);\n\tstatic int s_ButtonGfxVsync = 0;\n\tif(DoButton_CheckBox(&s_ButtonGfxVsync, Localize(\"V-Sync\"), g_Config.m_GfxVsync, &Button))\n\t{\n\t\tg_Config.m_GfxVsync ^= 1;\n\t\tCheckSettings = true;\n\t}\n\n\t// FSAA button\n\t{\n\t\tScreen.HSplitTop(Spacing, 0, &Screen);\n\t\tScreen.HSplitTop(ButtonHeight, &Button, &Screen);\n\t\tRenderTools()->DrawUIRect(&Button, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\t\tCUIRect Text;\n\t\tButton.VSplitLeft(ButtonHeight+5.0f, 0, &Button);\n\t\tButton.VSplitLeft(100.0f, &Text, &Button);\n\n\t\tchar aBuf[32];\n\t\tstr_format(aBuf, sizeof(aBuf), \"%s:\", Localize(\"Anti Aliasing\"));\n\t\tText.y += 2.0f;\n\t\tUI()->DoLabel(&Text, aBuf, Text.h*ms_FontmodHeight*0.8f, -1);\n\n\t\tButton.VSplitLeft(70.0f, &Button, 0);\n\t\tstr_format(aBuf, sizeof(aBuf), \"%dx\", g_Config.m_GfxFsaaSamples);\n\t\tstatic int s_ButtonGfxFsaaSamples = 0;\n\t\tif(DoButton_Menu(&s_ButtonGfxFsaaSamples, aBuf, 0, &Button))\n\t\t{\n\t\t\tif(!g_Config.m_GfxFsaaSamples)\n\t\t\t\tg_Config.m_GfxFsaaSamples = 2;\n\t\t\telse if(g_Config.m_GfxFsaaSamples == 16)\n\t\t\t\tg_Config.m_GfxFsaaSamples = 0;\n\t\t\telse\n\t\t\t\tg_Config.m_GfxFsaaSamples *= 2;\n\t\t\tCheckSettings = true;\n\t\t}\n\t}\n\n\t// render texture menu\n\tTexture.HSplitTop(ButtonHeight, &Label, &Texture);\n\tLabel.y += 2.0f;\n\tUI()->DoLabel(&Label, Localize(\"Texture\"), ButtonHeight*ms_FontmodHeight*0.8f, 0);\n\n\tTexture.HSplitTop(Spacing, 0, &Texture);\n\tTexture.HSplitTop(ButtonHeight, &Button, &Texture);\n\tstatic int s_ButtonGfxTextureQuality = 0;\n\tif(DoButton_CheckBox(&s_ButtonGfxTextureQuality, Localize(\"Quality Textures\"), g_Config.m_GfxTextureQuality, &Button))\n\t{\n\t\tg_Config.m_GfxTextureQuality ^= 1;\n\t\tCheckSettings = true;\n\t}\n\n\tTexture.HSplitTop(Spacing, 0, &Texture);\n\tTexture.HSplitTop(ButtonHeight, &Button, &Texture);\n\tstatic int s_ButtonGfxTextureCompression = 0;\n\tif(DoButton_CheckBox(&s_ButtonGfxTextureCompression, Localize(\"Texture Compression\"), g_Config.m_GfxTextureCompression, &Button))\n\t{\n\t\tg_Config.m_GfxTextureCompression ^= 1;\n\t\tCheckSettings = true;\n\t}\n\n\tTexture.HSplitTop(Spacing, 0, &Texture);\n\tTexture.HSplitTop(ButtonHeight, &Button, &Texture);\n\tstatic int s_ButtonGfxHighDetail = 0;\n\tif(DoButton_CheckBox(&s_ButtonGfxHighDetail, Localize(\"High Detail\"), g_Config.m_GfxHighDetail, &Button))\n\t\tg_Config.m_GfxHighDetail ^= 1;\n\n\t// render screen modes\n\tMainView.HSplitTop(10.0f, 0, &MainView);\n\n\t// display mode list\n\t{\n\t\t// custom list header\n\t\tNumOptions = 2;\n\n\t\tCUIRect Header, Button;\n\t\tMainView.HSplitTop(ButtonHeight*(float)(NumOptions+1)+Spacing*(float)(NumOptions+1), &Header, 0);\n\t\tRenderTools()->DrawUIRect(&Header, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_T, 5.0f);\n\n\t\t// draw header\n\t\tMainView.HSplitTop(ButtonHeight, &Header, &MainView);\n\t\tHeader.y += 2.0f;\n\t\tUI()->DoLabel(&Header, Localize(\"Resolutions\"), Header.h*ms_FontmodHeight*0.8f, 0);\n\n\t\t// supported modes button\n\t\tMainView.HSplitTop(Spacing, 0, &MainView);\n\t\tMainView.HSplitTop(ButtonHeight, &Button, &MainView);\n\t\tstatic int s_GfxDisplayAllModes = 0;\n\t\tif(DoButton_CheckBox(&s_GfxDisplayAllModes, Localize(\"Show only supported\"), g_Config.m_GfxDisplayAllModes^1, &Button))\n\t\t{\n\t\t\tg_Config.m_GfxDisplayAllModes ^= 1;\n\t\t\tm_NumModes = Graphics()->GetVideoModes(m_aModes, MAX_RESOLUTIONS);\n\t\t\tUpdateVideoFormats();\n\n\t\t\tbool Found = false;\n\t\t\tfor(int i = 0; i < m_NumVideoFormats; i++)\n\t\t\t{\n\t\t\t\tint G = gcd(g_Config.m_GfxScreenWidth, g_Config.m_GfxScreenHeight);\n\t\t\t\tif(m_aVideoFormats[i].m_WidthValue == g_Config.m_GfxScreenWidth/G && m_aVideoFormats[i].m_HeightValue == g_Config.m_GfxScreenHeight/G)\n\t\t\t\t{\n\t\t\t\t\tm_CurrentVideoFormat = i;\n\t\t\t\t\tFound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif(!Found)\n\t\t\t\tm_CurrentVideoFormat = 0;\n\n\t\t\tUpdatedFilteredVideoModes();\n\t\t}\n\n\t\t// format changer\n\t\t{\n\t\t\tMainView.HSplitTop(Spacing, 0, &MainView);\n\t\t\tMainView.HSplitTop(ButtonHeight, &Button, &MainView);\n\t\t\tRenderTools()->DrawUIRect(&Button, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\t\t\tCUIRect Text, Value, Unit;\n\t\t\tButton.VSplitLeft(Button.w/3.0f, &Text, &Button);\n\t\t\tButton.VSplitMid(&Value, &Unit);\n\n\t\t\tchar aBuf[32];\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"%s:\", Localize(\"Format\"));\n\t\t\tText.y += 2.0f;\n\t\t\tUI()->DoLabel(&Text, aBuf, Text.h*ms_FontmodHeight*0.8f, 0);\n\n\t\t\tUnit.y += 2.0f;\n\t\t\tif((float)m_aVideoFormats[m_CurrentVideoFormat].m_WidthValue/(float)m_aVideoFormats[m_CurrentVideoFormat].m_HeightValue >= 1.55f)\n\t\t\t\tUI()->DoLabel(&Unit, Localize(\"Wide\"), Unit.h*ms_FontmodHeight*0.8f, 0);\n\t\t\telse\n\t\t\t\tUI()->DoLabel(&Unit, Localize(\"Letterbox\"), Unit.h*ms_FontmodHeight*0.8f, 0);\n\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"%d:%d\", m_aVideoFormats[m_CurrentVideoFormat].m_WidthValue, m_aVideoFormats[m_CurrentVideoFormat].m_HeightValue);\n\t\t\tstatic int s_VideoFormatButton = 0;\n\t\t\tif(DoButton_Menu(&s_VideoFormatButton, aBuf, 0, &Value))\n\t\t\t{\n\t\t\t\tm_CurrentVideoFormat++;\n\t\t\t\tif(m_CurrentVideoFormat == m_NumVideoFormats)\n\t\t\t\t\tm_CurrentVideoFormat = 0;\n\n\t\t\t\tUpdatedFilteredVideoModes();\n\t\t\t}\n\t\t}\n\n\t\tMainView.HSplitTop(Spacing, 0, &MainView);\n\n\t\tstatic float s_ScrollValue = 0;\n\t\tstatic int s_DisplayModeList = 0;\n\t\tint OldSelected = -1;\n\t\tint G = gcd(s_GfxScreenWidth, s_GfxScreenHeight);\n\t\tstr_format(aBuf, sizeof(aBuf), \"%s: %dx%d (%d:%d)\", Localize(\"Current\"), s_GfxScreenWidth, s_GfxScreenHeight, s_GfxScreenWidth/G, s_GfxScreenHeight/G);\n\t\tUiDoListboxStart(&s_DisplayModeList, 20.0f, aBuf, m_lFilteredVideoModes.size(), 1, OldSelected, s_ScrollValue, &MainView);\n\n\t\tfor(int i = 0; i < m_lFilteredVideoModes.size(); ++i)\n\t\t{\n\t\t\tif(g_Config.m_GfxScreenWidth == m_lFilteredVideoModes[i].m_Width &&\n\t\t\t\tg_Config.m_GfxScreenHeight == m_lFilteredVideoModes[i].m_Height)\n\t\t\t{\n\t\t\t\tOldSelected = i;\n\t\t\t}\n\n\t\t\tCListboxItem Item = UiDoListboxNextItem(&m_lFilteredVideoModes[i], OldSelected == i);\n\t\t\tif(Item.m_Visible)\n\t\t\t{\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \" %dx%d\", m_lFilteredVideoModes[i].m_Width, m_lFilteredVideoModes[i].m_Height);\n\t\t\t\tif(i == OldSelected)\n\t\t\t\t{\n\t\t\t\t\tTextRender()->TextColor(0.0f, 0.0f, 0.0f, 1.0f);\n\t\t\t\t\tTextRender()->TextOutlineColor(1.0f, 1.0f, 1.0f, 0.25f);\n\t\t\t\t\tItem.m_Rect.y += 2.0f;\n\t\t\t\t\tUI()->DoLabelScaled(&Item.m_Rect, aBuf, Item.m_Rect.h*ms_FontmodHeight*0.8f, 0);\n\t\t\t\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\t\t\tTextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tItem.m_Rect.y += 2.0f;\n\t\t\t\t\tUI()->DoLabelScaled(&Item.m_Rect, aBuf, Item.m_Rect.h*ms_FontmodHeight*0.8f, 0);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst int NewSelected = UiDoListboxEnd(&s_ScrollValue, 0);\n\t\tif(OldSelected != NewSelected)\n\t\t{\n\t\t\tg_Config.m_GfxScreenWidth = m_lFilteredVideoModes[NewSelected].m_Width;\n\t\t\tg_Config.m_GfxScreenHeight = m_lFilteredVideoModes[NewSelected].m_Height;\n\t\t\tCheckSettings = true;\n\t\t}\n\t}\n\n\t// reset button\n\tSpacing = 3.0f;\n\tfloat ButtonWidth = (BottomView.w/6.0f)-(Spacing*5.0)/6.0f;\n\n\tBottomView.VSplitRight(ButtonWidth, 0, &BottomView);\n\tRenderTools()->DrawUIRect4(&BottomView, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f);\n\n\tBottomView.HSplitTop(25.0f, &BottomView, 0);\n\tButton = BottomView;\n\tstatic int s_ResetButton=0;\n\tif(DoButton_Menu(&s_ResetButton, Localize(\"Reset\"), 0, &Button))\n\t{\n\t\tg_Config.m_GfxScreenWidth = Graphics()->GetDesktopScreenWidth();\n\t\tg_Config.m_GfxScreenHeight = Graphics()->GetDesktopScreenHeight();\n\t\tg_Config.m_GfxBorderless = 0;\n\t\tg_Config.m_GfxFullscreen = 1;\n\t\tg_Config.m_GfxVsync = 1;\n\t\tg_Config.m_GfxFsaaSamples = 0;\n\t\tg_Config.m_GfxTextureQuality = 1;\n\t\tg_Config.m_GfxTextureCompression = 0;\n\t\tg_Config.m_GfxHighDetail = 1;\n\n\t\tif(g_Config.m_GfxDisplayAllModes)\n\t\t{\n\t\t\tg_Config.m_GfxDisplayAllModes = 0;\n\t\t\tm_NumModes = Graphics()->GetVideoModes(m_aModes, MAX_RESOLUTIONS);\n\t\t\tUpdateVideoFormats();\n\n\t\t\tbool Found = false;\n\t\t\tfor(int i = 0; i < m_NumVideoFormats; i++)\n\t\t\t{\n\t\t\t\tint G = gcd(g_Config.m_GfxScreenWidth, g_Config.m_GfxScreenHeight);\n\t\t\t\tif(m_aVideoFormats[i].m_WidthValue == g_Config.m_GfxScreenWidth/G && m_aVideoFormats[i].m_HeightValue == g_Config.m_GfxScreenHeight/G)\n\t\t\t\t{\n\t\t\t\t\tm_CurrentVideoFormat = i;\n\t\t\t\t\tFound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif(!Found)\n\t\t\t\tm_CurrentVideoFormat = 0;\n\n\t\t\tUpdatedFilteredVideoModes();\n\t\t}\n\n\t\tCheckSettings = true;\n\t}\n\n\t// check if the new settings require a restart\n\tif(CheckSettings)\n\t{\n\t\tif(s_GfxScreenWidth == g_Config.m_GfxScreenWidth &&\n\t\t\ts_GfxScreenHeight == g_Config.m_GfxScreenHeight &&\n\t\t\ts_GfxBorderless == g_Config.m_GfxBorderless &&\n\t\t\ts_GfxFullscreen == g_Config.m_GfxFullscreen &&\n\t\t\ts_GfxVsync == g_Config.m_GfxVsync &&\n\t\t\ts_GfxFsaaSamples == g_Config.m_GfxFsaaSamples &&\n\t\t\ts_GfxTextureQuality == g_Config.m_GfxTextureQuality &&\n\t\t\ts_GfxTextureCompression == g_Config.m_GfxTextureCompression)\n\t\t\tm_NeedRestartGraphics = false;\n\t\telse\n\t\t\tm_NeedRestartGraphics = true;\n\t}\n}\n\nvoid CMenus::RenderSettingsSound(CUIRect MainView)\n{\n\tCUIRect Label, Button, Sound, Detail, BottomView;\n\n\t// render sound menu background\n\tint NumOptions = g_Config.m_SndEnable ? 3 : 1;\n\tfloat ButtonHeight = 20.0f;\n\tfloat Spacing = 2.0f;\n\tfloat BackgroundHeight = (float)(NumOptions+1)*ButtonHeight+(float)NumOptions*Spacing;\n\n\tMainView.HSplitTop(20.0f, 0, &MainView);\n\tMainView.HSplitTop(BackgroundHeight, &Sound, &MainView);\n\tRenderTools()->DrawUIRect(&Sound, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\t// render detail menu background\n\tif(g_Config.m_SndEnable)\n\t{\n\t\tBackgroundHeight = 2.0f*ButtonHeight+Spacing;\n\n\t\tMainView.HSplitTop(10.0f, 0, &MainView);\n\t\tMainView.HSplitTop(BackgroundHeight, &Detail, &MainView);\n\t\tRenderTools()->DrawUIRect(&Detail, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\t}\n\n\tstatic int s_SndEnable = g_Config.m_SndEnable;\n\tstatic int s_SndRate = g_Config.m_SndRate;\n\n\t// render sound menu\n\tSound.HSplitTop(ButtonHeight, &Label, &Sound);\n\tLabel.y += 2.0f;\n\tUI()->DoLabel(&Label, Localize(\"Sound\"), ButtonHeight*ms_FontmodHeight*0.8f, 0);\n\n\tSound.HSplitTop(Spacing, 0, &Sound);\n\tSound.HSplitTop(ButtonHeight, &Button, &Sound);\n\tstatic int s_ButtonSndEnable = 0;\n\tif(DoButton_CheckBox(&s_ButtonSndEnable, Localize(\"Use sounds\"), g_Config.m_SndEnable, &Button))\n\t{\n\t\tg_Config.m_SndEnable ^= 1;\n\t\tif(g_Config.m_SndEnable)\n\t\t{\n\t\t\tif(g_Config.m_SndMusic)\n\t\t\t\tm_pClient->m_pSounds->Play(CSounds::CHN_MUSIC, SOUND_MENU, 1.0f);\n\t\t}\n\t\telse\n\t\t\tm_pClient->m_pSounds->Stop(SOUND_MENU);\n\t\tm_NeedRestartSound = g_Config.m_SndEnable && (!s_SndEnable || s_SndRate != g_Config.m_SndRate);\n\t}\n\n\tif(g_Config.m_SndEnable)\n\t{\n\t\tSound.HSplitTop(Spacing, 0, &Sound);\n\t\tSound.HSplitTop(ButtonHeight, &Button, &Sound);\n\t\tButton.VSplitLeft(ButtonHeight, 0, &Button);\n\t\tstatic int s_ButtonSndMusic = 0;\n\t\tif(DoButton_CheckBox(&s_ButtonSndMusic, Localize(\"Play background music\"), g_Config.m_SndMusic, &Button))\n\t\t{\n\t\t\tg_Config.m_SndMusic ^= 1;\n\t\t\tif(Client()->State() == IClient::STATE_OFFLINE)\n\t\t\t{\n\t\t\t\tif(g_Config.m_SndMusic)\n\t\t\t\t\tm_pClient->m_pSounds->Play(CSounds::CHN_MUSIC, SOUND_MENU, 1.0f);\n\t\t\t\telse\n\t\t\t\t\tm_pClient->m_pSounds->Stop(SOUND_MENU);\n\t\t\t}\n\t\t}\n\n\t\tSound.HSplitTop(Spacing, 0, &Sound);\n\t\tSound.HSplitTop(ButtonHeight, &Button, &Sound);\n\t\tButton.VSplitLeft(ButtonHeight, 0, &Button);\n\t\tstatic int s_ButtonSndNonactiveMute = 0;\n\t\tif(DoButton_CheckBox(&s_ButtonSndNonactiveMute, Localize(\"Mute when not active\"), g_Config.m_SndNonactiveMute, &Button))\n\t\t\tg_Config.m_SndNonactiveMute ^= 1;\n\n\t\t// render detail menu\n\t\tDetail.HSplitTop(ButtonHeight, &Label, &Detail);\n\t\tLabel.y += 2.0f;\n\t\tUI()->DoLabel(&Label, Localize(\"Detail\"), ButtonHeight*ms_FontmodHeight*0.8f, 0);\n\n\t\t// split menu\n\t\tCUIRect Left, Right;\n\t\tDetail.HSplitTop(Spacing, 0, &Detail);\n\t\tDetail.VSplitMid(&Left, &Right);\n\t\tLeft.VSplitRight(1.5f, &Left, 0);\n\t\tRight.VSplitLeft(1.5f, 0, &Right);\n\n\t\t// sample rate thingy\n\t\t{\n\t\t\tLeft.HSplitTop(ButtonHeight, &Button, &Left);\n\n\t\t\tRenderTools()->DrawUIRect(&Button, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\t\t\tCUIRect Text, Value, Unit;\n\t\t\tButton.VSplitLeft(Button.w/3.0f, &Text, &Button);\n\t\t\tButton.VSplitMid(&Value, &Unit);\n\n\t\t\tchar aBuf[32];\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"%s:\", Localize(\"Sample rate\"));\n\t\t\tText.y += 2.0f;\n\t\t\tUI()->DoLabel(&Text, aBuf, Text.h*ms_FontmodHeight*0.8f, 0);\n\n\t\t\tUnit.y += 2.0f;\n\t\t\tUI()->DoLabel(&Unit, \"kHz\", Unit.h*ms_FontmodHeight*0.8f, 0);\n\n\t\t\tif(g_Config.m_SndRate != 48000 && g_Config.m_SndRate != 44100)\n\t\t\t\tg_Config.m_SndRate = 48000;\n\t\t\tif(g_Config.m_SndRate == 48000)\n\t\t\t\tstr_copy(aBuf, \"48.0\", sizeof(aBuf));\n\t\t\telse\n\t\t\t\tstr_copy(aBuf, \"44.1\", sizeof(aBuf));\n\t\t\tstatic int s_SampleRateButton = 0;\n\t\t\tif(DoButton_Menu(&s_SampleRateButton, aBuf, 0, &Value))\n\t\t\t{\n\t\t\t\tif(g_Config.m_SndRate == 48000)\n\t\t\t\t\tg_Config.m_SndRate = 44100;\n\t\t\t\telse\n\t\t\t\t\tg_Config.m_SndRate = 48000;\n\t\t\t}\n\n\t\t\tm_NeedRestartSound = !s_SndEnable || s_SndRate != g_Config.m_SndRate;\n\t\t}\n\n\t\tRight.HSplitTop(ButtonHeight, &Button, &Right);\n\t\tDoScrollbarOption(&g_Config.m_SndVolume, &g_Config.m_SndVolume, &Button, Localize(\"Volume\"), 110.0f, 0, 100);\n\t}\n\n\t// reset button\n\tMainView.HSplitBottom(60.0f, 0, &BottomView);\n\n\tSpacing = 3.0f;\n\tfloat ButtonWidth = (BottomView.w/6.0f)-(Spacing*5.0)/6.0f;\n\n\tBottomView.VSplitRight(ButtonWidth, 0, &BottomView);\n\tRenderTools()->DrawUIRect4(&BottomView, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f);\n\n\tBottomView.HSplitTop(25.0f, &BottomView, 0);\n\tButton = BottomView;\n\tstatic int s_ResetButton=0;\n\tif(DoButton_Menu(&s_ResetButton, Localize(\"Reset\"), 0, &Button))\n\t{\n\t\tg_Config.m_SndEnable = 1;\n\t\tif(!g_Config.m_SndMusic)\n\t\t{\n\t\t\tg_Config.m_SndMusic = 1;\n\t\t\tm_pClient->m_pSounds->Play(CSounds::CHN_MUSIC, SOUND_MENU, 1.0f);\n\t\t}\n\t\tg_Config.m_SndNonactiveMute = 0;\n\t\tg_Config.m_SndRate = 48000;\n\t\tg_Config.m_SndVolume = 100;\n\t}\n}\n\nvoid CMenus::RenderSettings(CUIRect MainView)\n{\n\t// handle which page should be rendered\n\tif(g_Config.m_UiSettingsPage == SETTINGS_GENERAL)\n\t\tRenderSettingsGeneral(MainView);\n\telse if(g_Config.m_UiSettingsPage == SETTINGS_PLAYER)\n\t\tRenderSettingsPlayer(MainView);\n\telse if(g_Config.m_UiSettingsPage == SETTINGS_TEE)\n\t\tRenderSettingsTee(MainView);\n\telse if(g_Config.m_UiSettingsPage == SETTINGS_CONTROLS)\n\t\tRenderSettingsControls(MainView);\n\telse if(g_Config.m_UiSettingsPage == SETTINGS_GRAPHICS)\n\t\tRenderSettingsGraphics(MainView);\n\telse if(g_Config.m_UiSettingsPage == SETTINGS_SOUND)\n\t\tRenderSettingsSound(MainView);\n\n\tMainView.HSplitBottom(60.0f, 0, &MainView);\n\n\t// reset warning\n\tif(m_NeedRestartGraphics || m_NeedRestartSound)\n\t{\n\t\t// background\n\t\tCUIRect RestartWarning;\n\t\tMainView.HSplitTop(25.0f, &RestartWarning, 0);\n\t\tRestartWarning.VMargin(140.0f, &RestartWarning);\n\t\tRenderTools()->DrawUIRect(&RestartWarning, vec4(1.0f, 1.0f, 1.0f, 0.25f), CUI::CORNER_ALL, 5.0f);\n\n\t\t// text\n\t\tTextRender()->TextColor(0.973f, 0.863f, 0.207, 1.0f);\n\t\tRestartWarning.y += 2.0f;\n\t\tUI()->DoLabel(&RestartWarning, Localize(\"You must restart the game for all settings to take effect.\"), RestartWarning.h*ms_FontmodHeight*0.75f, 0);\n\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t}\n\n\tRenderBackButton(MainView);\n}\n"
  },
  {
    "path": "src/game/client/components/menus_start.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/graphics.h>\n#include <engine/textrender.h>\n\n#include <engine/shared/config.h>\n\n#include <game/version.h>\n#include <game/client/render.h>\n#include <game/client/ui.h>\n\n#include <game/generated/client_data.h>\n\n#include \"menus.h\"\n\nvoid CMenus::RenderStartMenu(CUIRect MainView)\n{\n\tCUIRect TopMenu, BottomMenu;\n\tMainView.VMargin(MainView.w/2-190.0f, &TopMenu);\n\tTopMenu.HSplitTop(365.0f, &TopMenu, &BottomMenu);\n\t//TopMenu.HSplitBottom(145.0f, &TopMenu, 0);\n\tRenderTools()->DrawUIRect4(&TopMenu, vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 10.0f);\n\n\tTopMenu.HSplitTop(145.0f, 0, &TopMenu);\n\n\tCUIRect Button;\n\n\tTopMenu.HSplitBottom(40.0f, &TopMenu, &Button);\n\tstatic int s_SettingsButton = 0;\n\tif(g_Config.m_ClShowStartMenuImages)\n\t{\n\t\tif(DoButton_MenuImage(&s_SettingsButton, Localize(\"Settings\"), 0, &Button, \"settings\", 10.0f, 0.5f))\n\t\t{\n\t\t\tm_MenuPage = PAGE_SETTINGS;\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(DoButton_Menu(&s_SettingsButton, Localize(\"Settings\"), 0, &Button, CUI::CORNER_ALL, 10.0f, 0.5f))\n\t\t{\n\t\t\tm_MenuPage = PAGE_SETTINGS;\n\t\t}\n\t}\n\n\t/*TopMenu.HSplitBottom(5.0f, &TopMenu, 0); // little space\n\tTopMenu.HSplitBottom(40.0f, &TopMenu, &Bottom);\n\tstatic int s_LocalServerButton = 0;\n\tif(g_Config.m_ClShowStartMenuImages)\n\t{\n\t\tif(DoButton_MenuImage(&s_LocalServerButton, Localize(\"Local server\"), 0, &Button, \"local_server\", 10.0f, 0.5f))\n\t\t{\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(DoButton_Menu(&s_LocalServerButton, Localize(\"Local server\"), 0, &Button, CUI::CORNER_ALL, 10.0f, 0.5f))\n\t\t{\n\t\t}\n\t}*/\n\n\tTopMenu.HSplitBottom(5.0f, &TopMenu, 0); // little space\n\tTopMenu.HSplitBottom(40.0f, &TopMenu, &Button);\n\tstatic int s_DemoButton = 0;\n\tif(g_Config.m_ClShowStartMenuImages)\n\t{\n\t\tif(DoButton_MenuImage(&s_DemoButton, Localize(\"Demos\"), 0, &Button, \"demos\", 10.0f, 0.5f))\n\t\t{\n\t\t\tm_MenuPage = PAGE_DEMOS;\n\t\t\tDemolistPopulate();\n\t\t\tDemolistOnUpdate(false);\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(DoButton_Menu(&s_DemoButton, Localize(\"Demos\"), 0, &Button, CUI::CORNER_ALL, 10.0f, 0.5f))\n\t\t{\n\t\t\tm_MenuPage = PAGE_DEMOS;\n\t\t\tDemolistPopulate();\n\t\t\tDemolistOnUpdate(false);\n\t\t}\n\t}\n\n\tTopMenu.HSplitBottom(5.0f, &TopMenu, 0); // little space\n\tTopMenu.HSplitBottom(40.0f, &TopMenu, &Button);\n\tstatic int s_MapEditorButton = 0;\n\tif(g_Config.m_ClShowStartMenuImages)\n\t{\n\t\tif(DoButton_MenuImage(&s_MapEditorButton, Localize(\"Editor\"), 0, &Button, \"editor\", 10.0f, 0.5f))\n\t\t{\n\t\t\tg_Config.m_ClEditor = 1;\n\t\t\tInput()->MouseModeRelative();\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(DoButton_Menu(&s_MapEditorButton, Localize(\"Editor\"), 0, &Button, CUI::CORNER_ALL, 10.0f, 0.5f))\n\t\t{\n\t\t\tg_Config.m_ClEditor = 1;\n\t\t\tInput()->MouseModeRelative();\n\t\t}\n\t}\n\n\tTopMenu.HSplitBottom(5.0f, &TopMenu, 0); // little space\n\tTopMenu.HSplitBottom(40.0f, &TopMenu, &Button);\n\tstatic int s_PlayButton = 0;\n\tif(g_Config.m_ClShowStartMenuImages)\n\t{\n\t\tif(DoButton_MenuImage(&s_PlayButton, Localize(\"Play\"), 0, &Button, \"play_game\", 10.0f, 0.5f))\n\t\t\tm_MenuPage = g_Config.m_UiBrowserPage;\n\t}\n\telse\n\t{\n\t\tif(DoButton_Menu(&s_PlayButton, Localize(\"Play\"), 0, &Button, CUI::CORNER_ALL, 10.0f, 0.5f))\n\t\t\tm_MenuPage = g_Config.m_UiBrowserPage;\n\t}\n\n\tBottomMenu.HSplitTop(90.0f, 0, &BottomMenu);\n\tRenderTools()->DrawUIRect4(&BottomMenu, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 10.0f);\n\n\tBottomMenu.HSplitTop(40.0f, &Button, &TopMenu);\n\tstatic int s_QuitButton = 0;\n\tif(DoButton_Menu(&s_QuitButton, Localize(\"Quit\"), 0, &Button, CUI::CORNER_ALL, 10.0f, 0.5f))\n\t\tm_Popup = POPUP_QUIT;\n\n\t// render version\n\tCUIRect Version;\n\tMainView.HSplitBottom(50.0f, 0, &Version);\n\tVersion.VMargin(50.0f, &Version);\n\tchar aBuf[64];\n\tif(str_comp(Client()->LatestVersion(), \"0\") != 0)\n\t{\n\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"Teeworlds %s is out! Download it at www.teeworlds.com!\"), Client()->LatestVersion());\n\t\tTextRender()->TextColor(1.0f, 0.4f, 0.4f, 1.0f);\n\t\tUI()->DoLabelScaled(&Version, aBuf, 14.0f, 0);\n\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t}\n\tUI()->DoLabelScaled(&Version, GAME_VERSION, 14.0f, 1);\t\n}\n\nvoid CMenus::RenderLogo(CUIRect MainView)\n{\n\t// render cursor\n\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_BANNER].m_Id);\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(1,1,1,1);\n\tIGraphics::CQuadItem QuadItem(MainView.w/2-140, 60, 280, 70);\n\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n}\n"
  },
  {
    "path": "src/game/client/components/motd.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/shared/config.h>\n#include <engine/graphics.h>\n#include <engine/textrender.h>\n#include <engine/keys.h>\n\n#include <game/generated/protocol.h>\n#include <game/generated/client_data.h>\n#include <game/client/gameclient.h>\n\n#include \"motd.h\"\n\nvoid CMotd::Clear()\n{\n\tm_ServerMotdTime = 0;\n}\n\nbool CMotd::IsActive()\n{\n\treturn time_get() < m_ServerMotdTime;\n}\n\nvoid CMotd::OnStateChange(int NewState, int OldState)\n{\n\tif(OldState == IClient::STATE_ONLINE || OldState == IClient::STATE_OFFLINE)\n\t\tClear();\n}\n\nvoid CMotd::OnRender()\n{\n\tif(!IsActive())\n\t\treturn;\n\n\tfloat Width = 400*3.0f*Graphics()->ScreenAspect();\n\tfloat Height = 400*3.0f;\n\n\tGraphics()->MapScreen(0, 0, Width, Height);\n\n\tfloat h = 800.0f;\n\tfloat w = 650.0f;\n\tfloat x = Width/2 - w/2;\n\tfloat y = 150.0f;\n\n\tGraphics()->BlendNormal();\n\tGraphics()->TextureClear();\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(0,0,0,0.5f);\n\tRenderTools()->DrawRoundRect(x, y, w, h, 40.0f);\n\tGraphics()->QuadsEnd();\n\n\tTextRender()->Text(0, x+40.0f, y+40.0f, 32.0f, m_aServerMotd, (int)(w-80.0f));\n}\n\nvoid CMotd::OnMessage(int MsgType, void *pRawMsg)\n{\n\tif(Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t\treturn;\n\n\tif(MsgType == NETMSGTYPE_SV_MOTD)\n\t{\n\t\tCNetMsg_Sv_Motd *pMsg = (CNetMsg_Sv_Motd *)pRawMsg;\n\n\t\t// process escaping\n\t\tstr_copy(m_aServerMotd, pMsg->m_pMessage, sizeof(m_aServerMotd));\n\t\tfor(int i = 0; m_aServerMotd[i]; i++)\n\t\t{\n\t\t\tif(m_aServerMotd[i] == '\\\\')\n\t\t\t{\n\t\t\t\tif(m_aServerMotd[i+1] == 'n')\n\t\t\t\t{\n\t\t\t\t\tm_aServerMotd[i] = ' ';\n\t\t\t\t\tm_aServerMotd[i+1] = '\\n';\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif(m_aServerMotd[0] && g_Config.m_ClMotdTime)\n\t\t\tm_ServerMotdTime = time_get()+time_freq()*g_Config.m_ClMotdTime;\n\t\telse\n\t\t\tm_ServerMotdTime = 0;\n\t}\n}\n\nbool CMotd::OnInput(IInput::CEvent Event)\n{\n\tif(IsActive() && Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_ESCAPE)\n\t{\n\t\tClear();\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n"
  },
  {
    "path": "src/game/client/components/motd.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_MOTD_H\n#define GAME_CLIENT_COMPONENTS_MOTD_H\n#include <game/client/component.h>\n\nclass CMotd : public CComponent\n{\n\t// motd\n\tint64 m_ServerMotdTime;\npublic:\n\tchar m_aServerMotd[900];\n\n\tvoid Clear();\n\tbool IsActive();\n\n\tvirtual void OnRender();\n\tvirtual void OnStateChange(int NewState, int OldState);\n\tvirtual void OnMessage(int MsgType, void *pRawMsg);\n\tvirtual bool OnInput(IInput::CEvent Event);\n};\n\n#endif\n"
  },
  {
    "path": "src/game/client/components/nameplates.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/textrender.h>\n#include <engine/shared/config.h>\n#include <game/generated/protocol.h>\n#include <game/generated/client_data.h>\n\n#include <game/client/gameclient.h>\n#include <game/client/animstate.h>\n#include \"nameplates.h\"\n#include \"controls.h\"\n\nvoid CNamePlates::RenderNameplate(\n\tconst CNetObj_Character *pPrevChar,\n\tconst CNetObj_Character *pPlayerChar,\n\tconst CNetObj_PlayerInfo *pPlayerInfo,\n\tint ClientID\n\t)\n{\n\tfloat IntraTick = Client()->IntraGameTick();\n\n\tvec2 Position = mix(vec2(pPrevChar->m_X, pPrevChar->m_Y), vec2(pPlayerChar->m_X, pPlayerChar->m_Y), IntraTick);\n\n\n\tfloat FontSize = 18.0f + 20.0f * g_Config.m_ClNameplatesSize / 100.0f;\n\t// render name plate\n\tif(m_pClient->m_LocalClientID != ClientID)\n\t{\n\t\tfloat a = 1;\n\t\tif(g_Config.m_ClNameplatesAlways == 0)\n\t\t\ta = clamp(1-powf(distance(m_pClient->m_pControls->m_TargetPos, Position)/200.0f,16.0f), 0.0f, 1.0f);\n\n\t\tconst char *pName = m_pClient->m_aClients[ClientID].m_aName;\n\t\tfloat tw = TextRender()->TextWidth(0, FontSize, pName, -1);\n\n\t\tTextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.5f*a);\n\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, a);\n\t\tif(g_Config.m_ClNameplatesTeamcolors && m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS)\n\t\t{\n\t\t\tif(m_pClient->m_aClients[ClientID].m_Team == TEAM_RED)\n\t\t\t\tTextRender()->TextColor(1.0f, 0.5f, 0.5f, a);\n\t\t\telse if(m_pClient->m_aClients[ClientID].m_Team == TEAM_BLUE)\n\t\t\t\tTextRender()->TextColor(0.7f, 0.7f, 1.0f, a);\n\t\t}\n\n\t\tTextRender()->Text(0, Position.x-tw/2.0f, Position.y-FontSize-38.0f, FontSize, pName, -1);\n\n\t\tif(g_Config.m_Debug) // render client id when in debug aswell\n\t\t{\n\t\t\tchar aBuf[128];\n\t\t\tstr_format(aBuf, sizeof(aBuf),\"%d\", ClientID);\n\t\t\tTextRender()->Text(0, Position.x, Position.y-90, 28.0f, aBuf, -1);\n\t\t}\n\n\t\tTextRender()->TextColor(1,1,1,1);\n\t\tTextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f);\n\t}\n}\n\nvoid CNamePlates::OnRender()\n{\n\tif (!g_Config.m_ClNameplates)\n\t\treturn;\n\n\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t{\n\t\t// only render active characters\n\t\tif(!m_pClient->m_Snap.m_aCharacters[i].m_Active)\n\t\t\tcontinue;\n\n\t\tconst void *pInfo = Client()->SnapFindItem(IClient::SNAP_CURRENT, NETOBJTYPE_PLAYERINFO, i);\n\n\t\tif(pInfo)\n\t\t{\n\t\t\tRenderNameplate(\n\t\t\t\t&m_pClient->m_Snap.m_aCharacters[i].m_Prev,\n\t\t\t\t&m_pClient->m_Snap.m_aCharacters[i].m_Cur,\n\t\t\t\t(const CNetObj_PlayerInfo *)pInfo,\n\t\t\t\ti);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "src/game/client/components/nameplates.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_NAMEPLATES_H\n#define GAME_CLIENT_COMPONENTS_NAMEPLATES_H\n#include <game/client/component.h>\n\nclass CNamePlates : public CComponent\n{\n\tvoid RenderNameplate(\n\t\tconst CNetObj_Character *pPrevChar,\n\t\tconst CNetObj_Character *pPlayerChar,\n\t\tconst CNetObj_PlayerInfo *pPlayerInfo,\n\t\tint ClientID\n\t);\n\npublic:\n\tvirtual void OnRender();\n};\n\n#endif\n"
  },
  {
    "path": "src/game/client/components/particles.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/math.h>\n#include <engine/graphics.h>\n#include <engine/demo.h>\n\n#include <game/generated/client_data.h>\n#include <game/client/render.h>\n#include <game/gamecore.h>\n#include \"particles.h\"\n\nCParticles::CParticles()\n{\n\tOnReset();\n\tm_RenderTrail.m_pParts = this;\n\tm_RenderExplosions.m_pParts = this;\n\tm_RenderGeneral.m_pParts = this;\n}\n\n\nvoid CParticles::OnReset()\n{\n\t// reset particles\n\tfor(int i = 0; i < MAX_PARTICLES; i++)\n\t{\n\t\tm_aParticles[i].m_PrevPart = i-1;\n\t\tm_aParticles[i].m_NextPart = i+1;\n\t}\n\n\tm_aParticles[0].m_PrevPart = 0;\n\tm_aParticles[MAX_PARTICLES-1].m_NextPart = -1;\n\tm_FirstFree = 0;\n\n\tfor(int i = 0; i < NUM_GROUPS; i++)\n\t\tm_aFirstPart[i] = -1;\n}\n\nvoid CParticles::Add(int Group, CParticle *pPart)\n{\n\tif(Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tconst IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo();\n\t\tif(pInfo->m_Paused)\n\t\t\treturn;\n\t}\n\telse\n\t{\n\t\tif(m_pClient->m_Snap.m_pGameData && m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED)\n\t\t\treturn;\n\t}\n\n\tif (m_FirstFree == -1)\n\t\treturn;\n\n\t// remove from the free list\n\tint Id = m_FirstFree;\n\tm_FirstFree = m_aParticles[Id].m_NextPart;\n\tif(m_FirstFree != -1)\n\t\tm_aParticles[m_FirstFree].m_PrevPart = -1;\n\n\t// copy data\n\tm_aParticles[Id] = *pPart;\n\n\t// insert to the group list\n\tm_aParticles[Id].m_PrevPart = -1;\n\tm_aParticles[Id].m_NextPart = m_aFirstPart[Group];\n\tif(m_aFirstPart[Group] != -1)\n\t\tm_aParticles[m_aFirstPart[Group]].m_PrevPart = Id;\n\tm_aFirstPart[Group] = Id;\n\n\t// set some parameters\n\tm_aParticles[Id].m_Life = 0;\n}\n\nvoid CParticles::Update(float TimePassed)\n{\n\tstatic float FrictionFraction = 0;\n\tFrictionFraction += TimePassed;\n\n\tif(FrictionFraction > 2.0f) // safty messure\n\t\tFrictionFraction = 0;\n\n\tint FrictionCount = 0;\n\twhile(FrictionFraction > 0.05f)\n\t{\n\t\tFrictionCount++;\n\t\tFrictionFraction -= 0.05f;\n\t}\n\n\tfor(int g = 0; g < NUM_GROUPS; g++)\n\t{\n\t\tint i = m_aFirstPart[g];\n\t\twhile(i != -1)\n\t\t{\n\t\t\tint Next = m_aParticles[i].m_NextPart;\n\t\t\t//m_aParticles[i].vel += flow_get(m_aParticles[i].pos)*time_passed * m_aParticles[i].flow_affected;\n\t\t\tm_aParticles[i].m_Vel.y += m_aParticles[i].m_Gravity*TimePassed;\n\n\t\t\tfor(int f = 0; f < FrictionCount; f++) // apply friction\n\t\t\t\tm_aParticles[i].m_Vel *= m_aParticles[i].m_Friction;\n\n\t\t\t// move the point\n\t\t\tvec2 Vel = m_aParticles[i].m_Vel*TimePassed;\n\t\t\tCollision()->MovePoint(&m_aParticles[i].m_Pos, &Vel, 0.1f+0.9f*frandom(), NULL);\n\t\t\tm_aParticles[i].m_Vel = Vel* (1.0f/TimePassed);\n\n\t\t\tm_aParticles[i].m_Life += TimePassed;\n\t\t\tm_aParticles[i].m_Rot += TimePassed * m_aParticles[i].m_Rotspeed;\n\n\t\t\t// check particle death\n\t\t\tif(m_aParticles[i].m_Life > m_aParticles[i].m_LifeSpan)\n\t\t\t{\n\t\t\t\t// remove it from the group list\n\t\t\t\tif(m_aParticles[i].m_PrevPart != -1)\n\t\t\t\t\tm_aParticles[m_aParticles[i].m_PrevPart].m_NextPart = m_aParticles[i].m_NextPart;\n\t\t\t\telse\n\t\t\t\t\tm_aFirstPart[g] = m_aParticles[i].m_NextPart;\n\n\t\t\t\tif(m_aParticles[i].m_NextPart != -1)\n\t\t\t\t\tm_aParticles[m_aParticles[i].m_NextPart].m_PrevPart = m_aParticles[i].m_PrevPart;\n\n\t\t\t\t// insert to the free list\n\t\t\t\tif(m_FirstFree != -1)\n\t\t\t\t\tm_aParticles[m_FirstFree].m_PrevPart = i;\n\t\t\t\tm_aParticles[i].m_PrevPart = -1;\n\t\t\t\tm_aParticles[i].m_NextPart = m_FirstFree;\n\t\t\t\tm_FirstFree = i;\n\t\t\t}\n\n\t\t\ti = Next;\n\t\t}\n\t}\n}\n\nvoid CParticles::OnRender()\n{\n\tif(Client()->State() < IClient::STATE_ONLINE)\n\t\treturn;\n\n\tstatic int64 LastTime = 0;\n\tint64 t = time_get();\n\n\tif(Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tconst IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo();\n\t\tif(!pInfo->m_Paused)\n\t\t\tUpdate((float)((t-LastTime)/(double)time_freq())*pInfo->m_Speed);\n\t}\n\telse\n\t{\n\t\tif(m_pClient->m_Snap.m_pGameData && !(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED))\n\t\t\tUpdate((float)((t-LastTime)/(double)time_freq()));\n\t}\n\n\tLastTime = t;\n}\n\nvoid CParticles::RenderGroup(int Group)\n{\n\tGraphics()->BlendNormal();\n\t//gfx_blend_additive();\n\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_PARTICLES].m_Id);\n\tGraphics()->QuadsBegin();\n\n\tint i = m_aFirstPart[Group];\n\twhile(i != -1)\n\t{\n\t\tRenderTools()->SelectSprite(m_aParticles[i].m_Spr);\n\t\tfloat a = m_aParticles[i].m_Life / m_aParticles[i].m_LifeSpan;\n\t\tvec2 p = m_aParticles[i].m_Pos;\n\t\tfloat Size = mix(m_aParticles[i].m_StartSize, m_aParticles[i].m_EndSize, a);\n\n\t\tGraphics()->QuadsSetRotation(m_aParticles[i].m_Rot);\n\n\t\tGraphics()->SetColor(\n\t\t\tm_aParticles[i].m_Color.r,\n\t\t\tm_aParticles[i].m_Color.g,\n\t\t\tm_aParticles[i].m_Color.b,\n\t\t\tm_aParticles[i].m_Color.a); // pow(a, 0.75f) *\n\n\t\tIGraphics::CQuadItem QuadItem(p.x, p.y, Size, Size);\n\t\tGraphics()->QuadsDraw(&QuadItem, 1);\n\n\t\ti = m_aParticles[i].m_NextPart;\n\t}\n\tGraphics()->QuadsEnd();\n\tGraphics()->BlendNormal();\n}\n"
  },
  {
    "path": "src/game/client/components/particles.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_PARTICLES_H\n#define GAME_CLIENT_COMPONENTS_PARTICLES_H\n#include <base/vmath.h>\n#include <game/client/component.h>\n\n// particles\nstruct CParticle\n{\n\tvoid SetDefault()\n\t{\n\t\tm_Vel = vec2(0,0);\n\t\tm_LifeSpan = 0;\n\t\tm_StartSize = 32;\n\t\tm_EndSize = 32;\n\t\tm_Rot = 0;\n\t\tm_Rotspeed = 0;\n\t\tm_Gravity = 0;\n\t\tm_Friction = 0;\n\t\tm_FlowAffected = 1.0f;\n\t\tm_Color = vec4(1,1,1,1);\n\t}\n\n\tvec2 m_Pos;\n\tvec2 m_Vel;\n\n\tint m_Spr;\n\n\tfloat m_FlowAffected;\n\n\tfloat m_LifeSpan;\n\n\tfloat m_StartSize;\n\tfloat m_EndSize;\n\n\tfloat m_Rot;\n\tfloat m_Rotspeed;\n\n\tfloat m_Gravity;\n\tfloat m_Friction;\n\n\tvec4 m_Color;\n\n\t// set by the particle system\n\tfloat m_Life;\n\tint m_PrevPart;\n\tint m_NextPart;\n};\n\nclass CParticles : public CComponent\n{\n\tfriend class CGameClient;\npublic:\n\tenum\n\t{\n\t\tGROUP_PROJECTILE_TRAIL=0,\n\t\tGROUP_EXPLOSIONS,\n\t\tGROUP_GENERAL,\n\t\tNUM_GROUPS\n\t};\n\n\tCParticles();\n\n\tvoid Add(int Group, CParticle *pPart);\n\n\tvirtual void OnReset();\n\tvirtual void OnRender();\n\nprivate:\n\n\tenum\n\t{\n\t\tMAX_PARTICLES=1024*8,\n\t};\n\n\tCParticle m_aParticles[MAX_PARTICLES];\n\tint m_FirstFree;\n\tint m_aFirstPart[NUM_GROUPS];\n\n\tvoid RenderGroup(int Group);\n\tvoid Update(float TimePassed);\n\n\ttemplate<int TGROUP>\n\tclass CRenderGroup : public CComponent\n\t{\n\tpublic:\n\t\tCParticles *m_pParts;\n\t\tvirtual void OnRender() { m_pParts->RenderGroup(TGROUP); }\n\t};\n\n\tCRenderGroup<GROUP_PROJECTILE_TRAIL> m_RenderTrail;\n\tCRenderGroup<GROUP_EXPLOSIONS> m_RenderExplosions;\n\tCRenderGroup<GROUP_GENERAL> m_RenderGeneral;\n};\n#endif\n"
  },
  {
    "path": "src/game/client/components/players.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/demo.h>\n#include <engine/engine.h>\n#include <engine/graphics.h>\n#include <engine/shared/config.h>\n#include <game/generated/protocol.h>\n#include <game/generated/client_data.h>\n\n#include <game/gamecore.h> // get_angle\n#include <game/client/animstate.h>\n#include <game/client/gameclient.h>\n#include <game/client/ui.h>\n#include <game/client/render.h>\n\n#include <game/client/components/flow.h>\n#include <game/client/components/skins.h>\n#include <game/client/components/effects.h>\n#include <game/client/components/sounds.h>\n#include <game/client/components/controls.h>\n\n#include \"players.h\"\n\nvoid CPlayers::RenderHand(CTeeRenderInfo *pInfo, vec2 CenterPos, vec2 Dir, float AngleOffset, vec2 PostRotOffset)\n{\n\t// for drawing hand\n\t//const skin *s = skin_get(skin_id);\n\n\tfloat BaseSize = 15.0f;\n\t//dir = normalize(hook_pos-pos);\n\n\tvec2 HandPos = CenterPos + Dir;\n\tfloat Angle = GetAngle(Dir);\n\tif (Dir.x < 0)\n\t\tAngle -= AngleOffset;\n\telse\n\t\tAngle += AngleOffset;\n\n\tvec2 DirX = Dir;\n\tvec2 DirY(-Dir.y,Dir.x);\n\n\tif (Dir.x < 0)\n\t\tDirY = -DirY;\n\n\tHandPos += DirX * PostRotOffset.x;\n\tHandPos += DirY * PostRotOffset.y;\n\n\t//Graphics()->TextureSet(data->m_aImages[IMAGE_CHAR_DEFAULT].id);\n\tGraphics()->TextureSet(pInfo->m_aTextures[CSkins::SKINPART_HANDS]);\n\tGraphics()->QuadsBegin();\n\tvec4 Color = pInfo->m_aColors[CSkins::SKINPART_HANDS];\n\tGraphics()->SetColor(Color.r, Color.g, Color.b, Color.a);\n\n\t// two passes\n\tfor (int i = 0; i < 2; i++)\n\t{\n\t\tbool OutLine = i == 0;\n\n\t\tRenderTools()->SelectSprite(OutLine?SPRITE_TEE_HAND_OUTLINE:SPRITE_TEE_HAND, 0, 0, 0);\n\t\tGraphics()->QuadsSetRotation(Angle);\n\t\tIGraphics::CQuadItem QuadItem(HandPos.x, HandPos.y, 2*BaseSize, 2*BaseSize);\n\t\tGraphics()->QuadsDraw(&QuadItem, 1);\n\t}\n\n\tGraphics()->QuadsSetRotation(0);\n\tGraphics()->QuadsEnd();\n}\n\ninline float NormalizeAngular(float f)\n{\n\treturn fmod(f+pi*2, pi*2);\n}\n\ninline float AngularMixDirection (float Src, float Dst) { return sinf(Dst-Src) >0?1:-1; }\ninline float AngularDistance(float Src, float Dst) { return asinf(sinf(Dst-Src)); }\n\ninline float AngularApproach(float Src, float Dst, float Amount)\n{\n\tfloat d = AngularMixDirection (Src, Dst);\n\tfloat n = Src + Amount*d;\n\tif(AngularMixDirection (n, Dst) != d)\n\t\treturn Dst;\n\treturn n;\n}\n\nvoid CPlayers::RenderHook(\n\tconst CNetObj_Character *pPrevChar,\n\tconst CNetObj_Character *pPlayerChar,\n\tconst CNetObj_PlayerInfo *pPrevInfo,\n\tconst CNetObj_PlayerInfo *pPlayerInfo,\n\tint ClientID\n\t)\n{\n\tCNetObj_Character Prev;\n\tCNetObj_Character Player;\n\tPrev = *pPrevChar;\n\tPlayer = *pPlayerChar;\n\n\tCTeeRenderInfo RenderInfo = m_aRenderInfo[ClientID];\n\n\tfloat IntraTick = Client()->IntraGameTick();\n\n\t// set size\n\tRenderInfo.m_Size = 64.0f;\n\n\n\t// use preditect players if needed\n\tif(m_pClient->m_LocalClientID == ClientID && g_Config.m_ClPredict && Client()->State() != IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tif(!m_pClient->m_Snap.m_pLocalCharacter ||\n\t\t\t(m_pClient->m_Snap.m_pGameData && m_pClient->m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_PAUSED|GAMESTATEFLAG_ROUNDOVER|GAMESTATEFLAG_GAMEOVER)))\n\t\t{\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// apply predicted results\n\t\t\tm_pClient->m_PredictedChar.Write(&Player);\n\t\t\tm_pClient->m_PredictedPrevChar.Write(&Prev);\n\t\t\tIntraTick = Client()->PredIntraGameTick();\n\t\t}\n\t}\n\n\tvec2 Position = mix(vec2(Prev.m_X, Prev.m_Y), vec2(Player.m_X, Player.m_Y), IntraTick);\n\n\t// draw hook\n\tif (Prev.m_HookState>0 && Player.m_HookState>0)\n\t{\n\t\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);\n\t\tGraphics()->QuadsBegin();\n\t\t//Graphics()->QuadsBegin();\n\n\t\tvec2 Pos = Position;\n\t\tvec2 HookPos;\n\n\t\tif(pPlayerChar->m_HookedPlayer != -1)\n\t\t{\n\t\t\tif(m_pClient->m_LocalClientID != -1 && pPlayerChar->m_HookedPlayer == m_pClient->m_LocalClientID)\n\t\t\t{\n\t\t\t\tif(Client()->State() == IClient::STATE_DEMOPLAYBACK) // only use prediction if needed\n\t\t\t\t\tHookPos = vec2(m_pClient->m_LocalCharacterPos.x, m_pClient->m_LocalCharacterPos.y);\n\t\t\t\telse\n\t\t\t\t\tHookPos = mix(vec2(m_pClient->m_PredictedPrevChar.m_Pos.x, m_pClient->m_PredictedPrevChar.m_Pos.y),\n\t\t\t\t\t\tvec2(m_pClient->m_PredictedChar.m_Pos.x, m_pClient->m_PredictedChar.m_Pos.y), Client()->PredIntraGameTick());\n\t\t\t}\n\t\t\telse if(m_pClient->m_LocalClientID == ClientID)\n\t\t\t{\n\t\t\t\tHookPos = mix(vec2(m_pClient->m_Snap.m_aCharacters[pPlayerChar->m_HookedPlayer].m_Prev.m_X,\n\t\t\t\t\tm_pClient->m_Snap.m_aCharacters[pPlayerChar->m_HookedPlayer].m_Prev.m_Y),\n\t\t\t\t\tvec2(m_pClient->m_Snap.m_aCharacters[pPlayerChar->m_HookedPlayer].m_Cur.m_X,\n\t\t\t\t\tm_pClient->m_Snap.m_aCharacters[pPlayerChar->m_HookedPlayer].m_Cur.m_Y),\n\t\t\t\t\tClient()->IntraGameTick());\n\t\t\t}\n\t\t\telse\n\t\t\t\tHookPos = mix(vec2(pPrevChar->m_HookX, pPrevChar->m_HookY), vec2(pPlayerChar->m_HookX, pPlayerChar->m_HookY), Client()->IntraGameTick());\n\t\t}\n\t\telse\n\t\t\tHookPos = mix(vec2(Prev.m_HookX, Prev.m_HookY), vec2(Player.m_HookX, Player.m_HookY), IntraTick);\n\n\t\tfloat d = distance(Pos, HookPos);\n\t\tvec2 Dir = normalize(Pos-HookPos);\n\n\t\tGraphics()->QuadsSetRotation(GetAngle(Dir)+pi);\n\n\t\t// render head\n\t\tRenderTools()->SelectSprite(SPRITE_HOOK_HEAD);\n\t\tIGraphics::CQuadItem QuadItem(HookPos.x, HookPos.y, 24,16);\n\t\tGraphics()->QuadsDraw(&QuadItem, 1);\n\n\t\t// render chain\n\t\tRenderTools()->SelectSprite(SPRITE_HOOK_CHAIN);\n\t\tIGraphics::CQuadItem Array[1024];\n\t\tint i = 0;\n\t\tfor(float f = 24; f < d && i < 1024; f += 24, i++)\n\t\t{\n\t\t\tvec2 p = HookPos + Dir*f;\n\t\t\tArray[i] = IGraphics::CQuadItem(p.x, p.y,24,16);\n\t\t}\n\n\t\tGraphics()->QuadsDraw(Array, i);\n\t\tGraphics()->QuadsSetRotation(0);\n\t\tGraphics()->QuadsEnd();\n\n\t\tRenderHand(&RenderInfo, Position, normalize(HookPos-Pos), -pi/2, vec2(20, 0));\n\t}\n}\n\nvoid CPlayers::RenderPlayer(\n\tconst CNetObj_Character *pPrevChar,\n\tconst CNetObj_Character *pPlayerChar,\n\tconst CNetObj_PlayerInfo *pPrevInfo,\n\tconst CNetObj_PlayerInfo *pPlayerInfo,\n\tint ClientID\n\t)\n{\n\tCNetObj_Character Prev;\n\tCNetObj_Character Player;\n\tPrev = *pPrevChar;\n\tPlayer = *pPlayerChar;\n\n\tCNetObj_PlayerInfo pInfo = *pPlayerInfo;\n\tCTeeRenderInfo RenderInfo = m_aRenderInfo[ClientID];\n\n\t// set size\n\tRenderInfo.m_Size = 64.0f;\n\n\tfloat IntraTick = Client()->IntraGameTick();\n\n\tfloat Angle = mix((float)Prev.m_Angle, (float)Player.m_Angle, IntraTick)/256.0f;\n\n\t//float angle = 0;\n\n\tif(m_pClient->m_LocalClientID == ClientID && Client()->State() != IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\t// just use the direct input if it's local player we are rendering\n\t\tAngle = GetAngle(m_pClient->m_pControls->m_MousePos);\n\t}\n\telse\n\t{\n\t\t/*\n\t\tfloat mixspeed = Client()->FrameTime()*2.5f;\n\t\tif(player.attacktick != prev.attacktick) // shooting boosts the mixing speed\n\t\t\tmixspeed *= 15.0f;\n\n\t\t// move the delta on a constant speed on a x^2 curve\n\t\tfloat current = g_GameClient.m_aClients[info.cid].angle;\n\t\tfloat target = player.angle/256.0f;\n\t\tfloat delta = angular_distance(current, target);\n\t\tfloat sign = delta < 0 ? -1 : 1;\n\t\tfloat new_delta = delta - 2*mixspeed*sqrt(delta*sign)*sign + mixspeed*mixspeed;\n\n\t\t// make sure that it doesn't vibrate when it's still\n\t\tif(fabs(delta) < 2/256.0f)\n\t\t\tangle = target;\n\t\telse\n\t\t\tangle = angular_approach(current, target, fabs(delta-new_delta));\n\n\t\tg_GameClient.m_aClients[info.cid].angle = angle;*/\n\t}\n\n\t// use preditect players if needed\n\tif(m_pClient->m_LocalClientID == ClientID && g_Config.m_ClPredict && Client()->State() != IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tif(!m_pClient->m_Snap.m_pLocalCharacter ||\n\t\t\t(m_pClient->m_Snap.m_pGameData && m_pClient->m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_PAUSED|GAMESTATEFLAG_ROUNDOVER|GAMESTATEFLAG_GAMEOVER)))\n\t\t{\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// apply predicted results\n\t\t\tm_pClient->m_PredictedChar.Write(&Player);\n\t\t\tm_pClient->m_PredictedPrevChar.Write(&Prev);\n\t\t\tIntraTick = Client()->PredIntraGameTick();\n\t\t}\n\t}\n\n\tvec2 Direction = GetDirection((int)(Angle*256.0f));\n\tvec2 Position = mix(vec2(Prev.m_X, Prev.m_Y), vec2(Player.m_X, Player.m_Y), IntraTick);\n\tvec2 Vel = mix(vec2(Prev.m_VelX/256.0f, Prev.m_VelY/256.0f), vec2(Player.m_VelX/256.0f, Player.m_VelY/256.0f), IntraTick);\n\n\tm_pClient->m_pFlow->Add(Position, Vel*100.0f, 10.0f);\n\n\tRenderInfo.m_GotAirJump = Player.m_Jumped&2?0:1;\n\n\tbool Stationary = Player.m_VelX <= 1 && Player.m_VelX >= -1;\n\tbool InAir = !Collision()->CheckPoint(Player.m_X, Player.m_Y+16);\n\tbool WantOtherDir = (Player.m_Direction == -1 && Vel.x > 0) || (Player.m_Direction == 1 && Vel.x < 0);\n\n\t// evaluate animation\n\tfloat WalkTime = fmod(absolute(Position.x), 100.0f)/100.0f;\n\tCAnimState State;\n\tState.Set(&g_pData->m_aAnimations[ANIM_BASE], 0);\n\n\tif(InAir)\n\t\tState.Add(&g_pData->m_aAnimations[ANIM_INAIR], 0, 1.0f); // TODO: some sort of time here\n\telse if(Stationary)\n\t\tState.Add(&g_pData->m_aAnimations[ANIM_IDLE], 0, 1.0f); // TODO: some sort of time here\n\telse if(!WantOtherDir)\n\t\tState.Add(&g_pData->m_aAnimations[ANIM_WALK], WalkTime, 1.0f);\n\n\tstatic float s_LastGameTickTime = Client()->GameTickTime();\n\tif(m_pClient->m_Snap.m_pGameData && !(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED))\n\t\ts_LastGameTickTime = Client()->GameTickTime();\n\tif (Player.m_Weapon == WEAPON_HAMMER)\n\t{\n\t\tfloat ct = (Client()->PrevGameTick()-Player.m_AttackTick)/(float)SERVER_TICK_SPEED + s_LastGameTickTime;\n\t\tState.Add(&g_pData->m_aAnimations[ANIM_HAMMER_SWING], clamp(ct*5.0f,0.0f,1.0f), 1.0f);\n\t}\n\tif (Player.m_Weapon == WEAPON_NINJA)\n\t{\n\t\tfloat ct = (Client()->PrevGameTick()-Player.m_AttackTick)/(float)SERVER_TICK_SPEED + s_LastGameTickTime;\n\t\tState.Add(&g_pData->m_aAnimations[ANIM_NINJA_SWING], clamp(ct*2.0f,0.0f,1.0f), 1.0f);\n\t}\n\n\t// do skidding\n\tif(!InAir && WantOtherDir && length(Vel*50) > 500.0f)\n\t{\n\t\tstatic int64 SkidSoundTime = 0;\n\t\tif(time_get()-SkidSoundTime > time_freq()/10)\n\t\t{\n\t\t\tm_pClient->m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_PLAYER_SKID, 0.25f, Position);\n\t\t\tSkidSoundTime = time_get();\n\t\t}\n\n\t\tm_pClient->m_pEffects->SkidTrail(\n\t\t\tPosition+vec2(-Player.m_Direction*6,12),\n\t\t\tvec2(-Player.m_Direction*100*length(Vel),-50)\n\t\t);\n\t}\n\n\t// draw gun\n\t{\n\t\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);\n\t\tGraphics()->QuadsBegin();\n\t\tGraphics()->QuadsSetRotation(State.GetAttach()->m_Angle*pi*2+Angle);\n\n\t\t// normal weapons\n\t\tint iw = clamp(Player.m_Weapon, 0, NUM_WEAPONS-1);\n\t\tRenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[iw].m_pSpriteBody, Direction.x < 0 ? SPRITE_FLAG_FLIP_Y : 0);\n\n\t\tvec2 Dir = Direction;\n\t\tfloat Recoil = 0.0f;\n\t\tvec2 p;\n\t\tif (Player.m_Weapon == WEAPON_HAMMER)\n\t\t{\n\t\t\t// Static position for hammer\n\t\t\tp = Position + vec2(State.GetAttach()->m_X, State.GetAttach()->m_Y);\n\t\t\tp.y += g_pData->m_Weapons.m_aId[iw].m_Offsety;\n\t\t\t// if attack is under way, bash stuffs\n\t\t\tif(Direction.x < 0)\n\t\t\t{\n\t\t\t\tGraphics()->QuadsSetRotation(-pi/2-State.GetAttach()->m_Angle*pi*2);\n\t\t\t\tp.x -= g_pData->m_Weapons.m_aId[iw].m_Offsetx;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tGraphics()->QuadsSetRotation(-pi/2+State.GetAttach()->m_Angle*pi*2);\n\t\t\t}\n\t\t\tRenderTools()->DrawSprite(p.x, p.y, g_pData->m_Weapons.m_aId[iw].m_VisualSize);\n\t\t}\n\t\telse if (Player.m_Weapon == WEAPON_NINJA)\n\t\t{\n\t\t\tp = Position;\n\t\t\tp.y += g_pData->m_Weapons.m_aId[iw].m_Offsety;\n\n\t\t\tif(Direction.x < 0)\n\t\t\t{\n\t\t\t\tGraphics()->QuadsSetRotation(-pi/2-State.GetAttach()->m_Angle*pi*2);\n\t\t\t\tp.x -= g_pData->m_Weapons.m_aId[iw].m_Offsetx;\n\t\t\t\tm_pClient->m_pEffects->PowerupShine(p+vec2(32,0), vec2(32,12));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tGraphics()->QuadsSetRotation(-pi/2+State.GetAttach()->m_Angle*pi*2);\n\t\t\t\tm_pClient->m_pEffects->PowerupShine(p-vec2(32,0), vec2(32,12));\n\t\t\t}\n\t\t\tRenderTools()->DrawSprite(p.x, p.y, g_pData->m_Weapons.m_aId[iw].m_VisualSize);\n\n\t\t\t// HADOKEN\n\t\t\tif ((Client()->GameTick()-Player.m_AttackTick) <= (SERVER_TICK_SPEED / 6) && g_pData->m_Weapons.m_aId[iw].m_NumSpriteMuzzles)\n\t\t\t{\n\t\t\t\tint IteX = rand() % g_pData->m_Weapons.m_aId[iw].m_NumSpriteMuzzles;\n\t\t\t\tstatic int s_LastIteX = IteX;\n\t\t\t\tif(Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t\t\t\t{\n\t\t\t\t\tconst IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo();\n\t\t\t\t\tif(pInfo->m_Paused)\n\t\t\t\t\t\tIteX = s_LastIteX;\n\t\t\t\t\telse\n\t\t\t\t\t\ts_LastIteX = IteX;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif(m_pClient->m_Snap.m_pGameData && m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED)\n\t\t\t\t\t\tIteX = s_LastIteX;\n\t\t\t\t\telse\n\t\t\t\t\t\ts_LastIteX = IteX;\n\t\t\t\t}\n\t\t\t\tif(g_pData->m_Weapons.m_aId[iw].m_aSpriteMuzzles[IteX])\n\t\t\t\t{\n\t\t\t\t\tvec2 Dir = vec2(pPlayerChar->m_X,pPlayerChar->m_Y) - vec2(pPrevChar->m_X, pPrevChar->m_Y);\n\t\t\t\t\tDir = normalize(Dir);\n\t\t\t\t\tfloat HadOkenAngle = GetAngle(Dir);\n\t\t\t\t\tGraphics()->QuadsSetRotation(HadOkenAngle );\n\t\t\t\t\t//float offsety = -data->weapons[iw].muzzleoffsety;\n\t\t\t\t\tRenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[iw].m_aSpriteMuzzles[IteX], 0);\n\t\t\t\t\tvec2 DirY(-Dir.y,Dir.x);\n\t\t\t\t\tp = Position;\n\t\t\t\t\tfloat OffsetX = g_pData->m_Weapons.m_aId[iw].m_Muzzleoffsetx;\n\t\t\t\t\tp -= Dir * OffsetX;\n\t\t\t\t\tRenderTools()->DrawSprite(p.x, p.y, 160.0f);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// TODO: should be an animation\n\t\t\tRecoil = 0;\n\t\t\tstatic float s_LastIntraTick = IntraTick;\n\t\t\tif(m_pClient->m_Snap.m_pGameData && !(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED))\n\t\t\t\ts_LastIntraTick = IntraTick;\n\n\t\t\tfloat a = (Client()->GameTick()-Player.m_AttackTick+s_LastIntraTick)/5.0f;\n\t\t\tif(a < 1)\n\t\t\t\tRecoil = sinf(a*pi);\n\t\t\tp = Position + Dir * g_pData->m_Weapons.m_aId[iw].m_Offsetx - Dir*Recoil*10.0f;\n\t\t\tp.y += g_pData->m_Weapons.m_aId[iw].m_Offsety;\n\t\t\tRenderTools()->DrawSprite(p.x, p.y, g_pData->m_Weapons.m_aId[iw].m_VisualSize);\n\t\t}\n\n\t\tif (Player.m_Weapon == WEAPON_GUN || Player.m_Weapon == WEAPON_SHOTGUN)\n\t\t{\n\t\t\t// check if we're firing stuff\n\t\t\tif(g_pData->m_Weapons.m_aId[iw].m_NumSpriteMuzzles)//prev.attackticks)\n\t\t\t{\n\t\t\t\tfloat Alpha = 0.0f;\n\t\t\t\tint Phase1Tick = (Client()->GameTick() - Player.m_AttackTick);\n\t\t\t\tif (Phase1Tick < (g_pData->m_Weapons.m_aId[iw].m_Muzzleduration + 3))\n\t\t\t\t{\n\t\t\t\t\tfloat t = ((((float)Phase1Tick) + IntraTick)/(float)g_pData->m_Weapons.m_aId[iw].m_Muzzleduration);\n\t\t\t\t\tAlpha = mix(2.0f, 0.0f, min(1.0f,max(0.0f,t)));\n\t\t\t\t}\n\n\t\t\t\tint IteX = rand() % g_pData->m_Weapons.m_aId[iw].m_NumSpriteMuzzles;\n\t\t\t\tstatic int s_LastIteX = IteX;\n\t\t\t\tif(Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t\t\t\t{\n\t\t\t\t\tconst IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo();\n\t\t\t\t\tif(pInfo->m_Paused)\n\t\t\t\t\t\tIteX = s_LastIteX;\n\t\t\t\t\telse\n\t\t\t\t\t\ts_LastIteX = IteX;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif(m_pClient->m_Snap.m_pGameData && m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED)\n\t\t\t\t\t\tIteX = s_LastIteX;\n\t\t\t\t\telse\n\t\t\t\t\t\ts_LastIteX = IteX;\n\t\t\t\t}\n\t\t\t\tif (Alpha > 0.0f && g_pData->m_Weapons.m_aId[iw].m_aSpriteMuzzles[IteX])\n\t\t\t\t{\n\t\t\t\t\tfloat OffsetY = -g_pData->m_Weapons.m_aId[iw].m_Muzzleoffsety;\n\t\t\t\t\tRenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[iw].m_aSpriteMuzzles[IteX], Direction.x < 0 ? SPRITE_FLAG_FLIP_Y : 0);\n\t\t\t\t\tif(Direction.x < 0)\n\t\t\t\t\t\tOffsetY = -OffsetY;\n\n\t\t\t\t\tvec2 DirY(-Dir.y,Dir.x);\n\t\t\t\t\tvec2 MuzzlePos = p + Dir * g_pData->m_Weapons.m_aId[iw].m_Muzzleoffsetx + DirY * OffsetY;\n\n\t\t\t\t\tRenderTools()->DrawSprite(MuzzlePos.x, MuzzlePos.y, g_pData->m_Weapons.m_aId[iw].m_VisualSize);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tGraphics()->QuadsEnd();\n\n\t\tswitch (Player.m_Weapon)\n\t\t{\n\t\t\tcase WEAPON_GUN: RenderHand(&RenderInfo, p, Direction, -3*pi/4, vec2(-15, 4)); break;\n\t\t\tcase WEAPON_SHOTGUN: RenderHand(&RenderInfo, p, Direction, -pi/2, vec2(-5, 4)); break;\n\t\t\tcase WEAPON_GRENADE: RenderHand(&RenderInfo, p, Direction, -pi/2, vec2(-4, 7)); break;\n\t\t}\n\n\t}\n\n\t// render the \"shadow\" tee\n\tif(m_pClient->m_LocalClientID == ClientID && g_Config.m_Debug)\n\t{\n\t\tvec2 GhostPosition = mix(vec2(pPrevChar->m_X, pPrevChar->m_Y), vec2(pPlayerChar->m_X, pPlayerChar->m_Y), Client()->IntraGameTick());\n\t\tCTeeRenderInfo Ghost = RenderInfo;\n\t\tfor(int p = 0; p < CSkins::NUM_SKINPARTS; p++)\n\t\t\tGhost.m_aColors[p].a *= 0.5f;\n\t\tRenderTools()->RenderTee(&State, &Ghost, Player.m_Emote, Direction, GhostPosition); // render ghost\n\t}\n\n\tRenderTools()->RenderTee(&State, &RenderInfo, Player.m_Emote, Direction, Position);\n\n\tif(pInfo.m_PlayerFlags&PLAYERFLAG_CHATTING)\n\t{\n\t\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_EMOTICONS].m_Id);\n\t\tGraphics()->QuadsBegin();\n\t\tRenderTools()->SelectSprite(SPRITE_DOTDOT);\n\t\tIGraphics::CQuadItem QuadItem(Position.x + 24, Position.y - 40, 64,64);\n\t\tGraphics()->QuadsDraw(&QuadItem, 1);\n\t\tGraphics()->QuadsEnd();\n\t}\n\n\tif (m_pClient->m_aClients[ClientID].m_EmoticonStart != -1 && m_pClient->m_aClients[ClientID].m_EmoticonStart + 2 * Client()->GameTickSpeed() > Client()->GameTick())\n\t{\n\t\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_EMOTICONS].m_Id);\n\t\tGraphics()->QuadsBegin();\n\n\t\tint SinceStart = Client()->GameTick() - m_pClient->m_aClients[ClientID].m_EmoticonStart;\n\t\tint FromEnd = m_pClient->m_aClients[ClientID].m_EmoticonStart + 2 * Client()->GameTickSpeed() - Client()->GameTick();\n\n\t\tfloat a = 1;\n\n\t\tif (FromEnd < Client()->GameTickSpeed() / 5)\n\t\t\ta = FromEnd / (Client()->GameTickSpeed() / 5.0);\n\n\t\tfloat h = 1;\n\t\tif (SinceStart < Client()->GameTickSpeed() / 10)\n\t\t\th = SinceStart / (Client()->GameTickSpeed() / 10.0);\n\n\t\tfloat Wiggle = 0;\n\t\tif (SinceStart < Client()->GameTickSpeed() / 5)\n\t\t\tWiggle = SinceStart / (Client()->GameTickSpeed() / 5.0);\n\n\t\tfloat WiggleAngle = sinf(5*Wiggle);\n\n\t\tGraphics()->QuadsSetRotation(pi/6*WiggleAngle);\n\n\t\tGraphics()->SetColor(1.0f,1.0f,1.0f,a);\n\t\t// client_datas::emoticon is an offset from the first emoticon\n\t\tRenderTools()->SelectSprite(SPRITE_OOP + m_pClient->m_aClients[ClientID].m_Emoticon);\n\t\tIGraphics::CQuadItem QuadItem(Position.x, Position.y - 23 - 32*h, 64, 64*h);\n\t\tGraphics()->QuadsDraw(&QuadItem, 1);\n\t\tGraphics()->QuadsEnd();\n\t}\n}\n\nvoid CPlayers::OnRender()\n{\n\t// update RenderInfo for ninja\n\tbool IsTeamplay = (m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS) != 0;\n\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t{\n\t\tm_aRenderInfo[i] = m_pClient->m_aClients[i].m_RenderInfo;\n\t\tif(m_pClient->m_Snap.m_aCharacters[i].m_Cur.m_Weapon == WEAPON_NINJA)\n\t\t{\n\t\t\t// change the skin for the player to the ninja\n\t\t\tint Skin = m_pClient->m_pSkins->Find(\"x_ninja\", true);\n\t\t\tif(Skin != -1)\n\t\t\t{\n\t\t\t\tconst CSkins::CSkin *pNinja = m_pClient->m_pSkins->Get(Skin);\n\t\t\t\tfor(int p = 0; p < CSkins::NUM_SKINPARTS; p++)\n\t\t\t\t{\n\t\t\t\t\tif(IsTeamplay)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_aRenderInfo[i].m_aTextures[p] = pNinja->m_apParts[p]->m_ColorTexture;\n\t\t\t\t\t\tint ColorVal = m_pClient->m_pSkins->GetTeamColor(true, pNinja->m_aPartColors[p], m_pClient->m_aClients[i].m_Team, p);\n\t\t\t\t\t\tm_aRenderInfo[i].m_aColors[p] = m_pClient->m_pSkins->GetColorV4(ColorVal, p==CSkins::SKINPART_TATTOO);\n\t\t\t\t\t}\n\t\t\t\t\telse if(pNinja->m_aUseCustomColors[p])\n\t\t\t\t\t{\n\t\t\t\t\t\tm_aRenderInfo[i].m_aTextures[p] = pNinja->m_apParts[p]->m_ColorTexture;\n\t\t\t\t\t\tm_aRenderInfo[i].m_aColors[p] = m_pClient->m_pSkins->GetColorV4(pNinja->m_aPartColors[p], p==CSkins::SKINPART_TATTOO);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tm_aRenderInfo[i].m_aTextures[p] = pNinja->m_apParts[p]->m_OrgTexture;\n\t\t\t\t\t\tm_aRenderInfo[i].m_aColors[p] = vec4(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// render other players in two passes, first pass we render the other, second pass we render our self\n\tfor(int p = 0; p < 4; p++)\n\t{\n\t\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t\t{\n\t\t\t// only render active characters\n\t\t\tif(!m_pClient->m_Snap.m_aCharacters[i].m_Active)\n\t\t\t\tcontinue;\n\n\t\t\tconst void *pPrevInfo = Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_PLAYERINFO, i);\n\t\t\tconst void *pInfo = Client()->SnapFindItem(IClient::SNAP_CURRENT, NETOBJTYPE_PLAYERINFO, i);\n\n\t\t\tif(pPrevInfo && pInfo)\n\t\t\t{\n\t\t\t\t//\n\t\t\t\tbool Local = m_pClient->m_LocalClientID == i;\n\t\t\t\tif((p % 2) == 0 && Local) continue;\n\t\t\t\tif((p % 2) == 1 && !Local) continue;\n\n\t\t\t\tCNetObj_Character PrevChar = m_pClient->m_Snap.m_aCharacters[i].m_Prev;\n\t\t\t\tCNetObj_Character CurChar = m_pClient->m_Snap.m_aCharacters[i].m_Cur;\n\n\t\t\t\tif(p<2)\n\t\t\t\t\tRenderHook(\n\t\t\t\t\t\t\t&PrevChar,\n\t\t\t\t\t\t\t&CurChar,\n\t\t\t\t\t\t\t(const CNetObj_PlayerInfo *)pPrevInfo,\n\t\t\t\t\t\t\t(const CNetObj_PlayerInfo *)pInfo,\n\t\t\t\t\t\t\ti\n\t\t\t\t\t\t);\n\t\t\t\telse\n\t\t\t\t\tRenderPlayer(\n\t\t\t\t\t\t\t&PrevChar,\n\t\t\t\t\t\t\t&CurChar,\n\t\t\t\t\t\t\t(const CNetObj_PlayerInfo *)pPrevInfo,\n\t\t\t\t\t\t\t(const CNetObj_PlayerInfo *)pInfo,\n\t\t\t\t\t\t\ti\n\t\t\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "src/game/client/components/players.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_PLAYERS_H\n#define GAME_CLIENT_COMPONENTS_PLAYERS_H\n#include <game/client/component.h>\n\nclass CPlayers : public CComponent\n{\n\tCTeeRenderInfo m_aRenderInfo[MAX_CLIENTS];\n\tvoid RenderHand(class CTeeRenderInfo *pInfo, vec2 CenterPos, vec2 Dir, float AngleOffset, vec2 PostRotOffset);\n\tvoid RenderPlayer(\n\t\tconst CNetObj_Character *pPrevChar,\n\t\tconst CNetObj_Character *pPlayerChar,\n\t\tconst CNetObj_PlayerInfo *pPrevInfo,\n\t\tconst CNetObj_PlayerInfo *pPlayerInfo,\n\t\tint ClientID\n\t);\n\tvoid RenderHook(\n\t\tconst CNetObj_Character *pPrevChar,\n\t\tconst CNetObj_Character *pPlayerChar,\n\t\tconst CNetObj_PlayerInfo *pPrevInfo,\n\t\tconst CNetObj_PlayerInfo *pPlayerInfo,\n\t\tint ClientID\n\t);\n\npublic:\n\tvirtual void OnRender();\n};\n\n#endif\n"
  },
  {
    "path": "src/game/client/components/scoreboard.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/demo.h>\n#include <engine/graphics.h>\n#include <engine/textrender.h>\n#include <engine/shared/config.h>\n\n#include <game/generated/client_data.h>\n#include <game/generated/protocol.h>\n\n#include <game/client/animstate.h>\n#include <game/client/gameclient.h>\n#include <game/client/localization.h>\n#include <game/client/render.h>\n#include <game/client/components/countryflags.h>\n#include <game/client/components/motd.h>\n\n#include \"scoreboard.h\"\n\n\nCScoreboard::CScoreboard()\n{\n\tOnReset();\n}\n\nvoid CScoreboard::ConKeyScoreboard(IConsole::IResult *pResult, void *pUserData)\n{\n\t((CScoreboard *)pUserData)->m_Active = pResult->GetInteger(0) != 0;\n}\n\nvoid CScoreboard::OnReset()\n{\n\tm_Active = false;\n}\n\nvoid CScoreboard::OnRelease()\n{\n\tm_Active = false;\n}\n\nvoid CScoreboard::OnConsoleInit()\n{\n\tConsole()->Register(\"+scoreboard\", \"\", CFGFLAG_CLIENT, ConKeyScoreboard, this, \"Show scoreboard\");\n}\n\nvoid CScoreboard::RenderGoals(float x, float y, float w)\n{\n\tfloat h = 50.0f;\n\n\tGraphics()->BlendNormal();\n\tGraphics()->TextureClear();\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(0,0,0,0.5f);\n\tRenderTools()->DrawRoundRect(x, y, w, h, 10.0f);\n\tGraphics()->QuadsEnd();\n\n\t// render goals\n\ty += 10.0f;\n\tif(m_pClient->m_GameInfo.m_ScoreLimit)\n\t{\n\t\tchar aBuf[64];\n\t\tstr_format(aBuf, sizeof(aBuf), \"%s: %d\", Localize(\"Score limit\"), m_pClient->m_GameInfo.m_ScoreLimit);\n\t\tTextRender()->Text(0, x+10.0f, y, 20.0f, aBuf, -1);\n\t}\n\tif(m_pClient->m_GameInfo.m_TimeLimit)\n\t{\n\t\tchar aBuf[64];\n\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"Time limit: %d min\"), m_pClient->m_GameInfo.m_TimeLimit);\n\t\tTextRender()->Text(0, x+230.0f, y, 20.0f, aBuf, -1);\n\t}\n\tif(m_pClient->m_GameInfo.m_MatchNum && m_pClient->m_GameInfo.m_MatchCurrent)\n\t{\n\t\tchar aBuf[64];\n\t\tstr_format(aBuf, sizeof(aBuf), \"%s %d/%d\", Localize(\"Match\"), m_pClient->m_GameInfo.m_MatchCurrent, m_pClient->m_GameInfo.m_MatchNum);\n\t\tfloat tw = TextRender()->TextWidth(0, 20.0f, aBuf, -1);\n\t\tTextRender()->Text(0, x+w-tw-10.0f, y, 20.0f, aBuf, -1);\n\t}\n}\n\nvoid CScoreboard::RenderSpectators(float x, float y, float w)\n{\n\tfloat h = 140.0f;\n\n\t// background\n\tGraphics()->BlendNormal();\n\tGraphics()->TextureClear();\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(0,0,0,0.5f);\n\tRenderTools()->DrawRoundRect(x, y, w, h, 10.0f);\n\tGraphics()->QuadsEnd();\n\n\t// Headline\n\ty += 10.0f;\n\tTextRender()->Text(0, x+10.0f, y, 28.0f, Localize(\"Spectators\"), w-20.0f);\n\n\t// spectator names\n\ty += 30.0f;\n\tbool Multiple = false;\n\tCTextCursor Cursor;\n\tTextRender()->SetCursor(&Cursor, x+10.0f, y, 22.0f, TEXTFLAG_RENDER);\n\tCursor.m_LineWidth = w-20.0f;\n\tCursor.m_MaxLines = 4;\n\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t{\n\t\tconst CNetObj_PlayerInfo *pInfo = m_pClient->m_Snap.m_paPlayerInfos[i];\n\t\tif(!pInfo || m_pClient->m_aClients[i].m_Team != TEAM_SPECTATORS)\n\t\t\tcontinue;\n\n\t\tif(Multiple)\n\t\t\tTextRender()->TextEx(&Cursor, \", \", -1);\n\t\tif(pInfo->m_PlayerFlags&PLAYERFLAG_WATCHING)\n\t\t\tTextRender()->TextColor(1.0f, 1.0f, 0.0f, 1.0f);\n\t\tTextRender()->TextEx(&Cursor, m_pClient->m_aClients[i].m_aName, -1);\n\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\tMultiple = true;\n\t}\n}\n\nvoid CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const char *pTitle)\n{\n\tif(Team == TEAM_SPECTATORS)\n\t\treturn;\n\n\tfloat h = 760.0f;\n\n\t// background\n\tGraphics()->BlendNormal();\n\tGraphics()->TextureClear();\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(0.0f, 0.0f, 0.0f, 0.5f);\n\tRenderTools()->DrawRoundRect(x, y, w, h, 17.0f);\n\tGraphics()->QuadsEnd();\n\n\t// render title\n\tfloat TitleFontsize = 40.0f;\n\tif(!pTitle)\n\t{\n\t\tif(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)\n\t\t\tpTitle = Localize(\"Game over\");\n\t\telse if(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_ROUNDOVER)\n\t\t\tpTitle = Localize(\"Round over\");\n\t\telse\n\t\t\tpTitle = Localize(\"Score board\");\n\t}\n\tTextRender()->Text(0, x+20.0f, y, TitleFontsize, pTitle, -1);\n\n\tchar aBuf[128] = {0};\n\tif(m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS)\n\t{\n\t\tint Score = Team == TEAM_RED ? m_pClient->m_Snap.m_pGameDataTeam->m_TeamscoreRed : m_pClient->m_Snap.m_pGameDataTeam->m_TeamscoreBlue;\n\t\tstr_format(aBuf, sizeof(aBuf), \"%d\", Score);\n\t}\n\telse\n\t{\n\t\tif(m_pClient->m_Snap.m_SpecInfo.m_Active && m_pClient->m_Snap.m_SpecInfo.m_SpectatorID != SPEC_FREEVIEW &&\n\t\t\tm_pClient->m_Snap.m_paPlayerInfos[m_pClient->m_Snap.m_SpecInfo.m_SpectatorID])\n\t\t{\n\t\t\tint Score = m_pClient->m_Snap.m_paPlayerInfos[m_pClient->m_Snap.m_SpecInfo.m_SpectatorID]->m_Score;\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"%d\", Score);\n\t\t}\n\t\telse if(m_pClient->m_Snap.m_pLocalInfo)\n\t\t{\n\t\t\tint Score = m_pClient->m_Snap.m_pLocalInfo->m_Score;\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"%d\", Score);\n\t\t}\n\t}\n\tfloat tw = TextRender()->TextWidth(0, TitleFontsize, aBuf, -1);\n\tTextRender()->Text(0, x+w-tw-20.0f, y, TitleFontsize, aBuf, -1);\n\n\t// calculate measurements\n\tx += 10.0f;\n\tfloat LineHeight = 60.0f;\n\tfloat TeeSizeMod = 1.0f;\n\tfloat Spacing = 16.0f;\n\tif(m_pClient->m_GameInfo.m_aTeamSize[Team] > 12)\n\t{\n\t\tLineHeight = 40.0f;\n\t\tTeeSizeMod = 0.8f;\n\t\tSpacing = 0.0f;\n\t}\n\telse if(m_pClient->m_GameInfo.m_aTeamSize[Team] > 8)\n\t{\n\t\tLineHeight = 50.0f;\n\t\tTeeSizeMod = 0.9f;\n\t\tSpacing = 8.0f;\n\t}\n\n\tfloat ScoreOffset = x+10.0f, ScoreLength = 60.0f;\n\tfloat TeeOffset = ScoreOffset+ScoreLength, TeeLength = 60*TeeSizeMod;\n\tfloat NameOffset = TeeOffset+TeeLength, NameLength = 300.0f-TeeLength;\n\tfloat PingOffset = x+610.0f, PingLength = 65.0f;\n\tfloat CountryOffset = PingOffset-(LineHeight-Spacing-TeeSizeMod*5.0f)*2.0f, CountryLength = (LineHeight-Spacing-TeeSizeMod*5.0f)*2.0f;\n\tfloat ClanOffset = x+370.0f, ClanLength = 230.0f-CountryLength;\n\n\t// render headlines\n\ty += 50.0f;\n\tfloat HeadlineFontsize = 22.0f;\n\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 0.7f);\n\ttw = TextRender()->TextWidth(0, HeadlineFontsize, Localize(\"Score\"), -1);\n\tTextRender()->Text(0, ScoreOffset+ScoreLength-tw, y, HeadlineFontsize, Localize(\"Score\"), -1);\n\n\tTextRender()->Text(0, NameOffset, y, HeadlineFontsize, Localize(\"Name\"), -1);\n\n\ttw = TextRender()->TextWidth(0, HeadlineFontsize, Localize(\"Clan\"), -1);\n\tTextRender()->Text(0, ClanOffset+ClanLength/2-tw/2, y, HeadlineFontsize, Localize(\"Clan\"), -1);\n\n\ttw = TextRender()->TextWidth(0, HeadlineFontsize, Localize(\"Ping\"), -1);\n\tTextRender()->Text(0, PingOffset+PingLength-tw, y, HeadlineFontsize, Localize(\"Ping\"), -1);\n\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\n\t// render player entries\n\ty += HeadlineFontsize*2.0f;\n\tfloat FontSize = 24.0f;\n\tCTextCursor Cursor;\n\n\tfor(int RenderDead = 0; RenderDead < 2; ++RenderDead)\n\t{\n\t\tfloat ColorAlpha = RenderDead ? 0.5f : 1.0f;\n\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, ColorAlpha);\n\t\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t\t{\n\t\t\t// make sure that we render the correct team\n\t\t\tconst CGameClient::CPlayerInfoItem *pInfo = &m_pClient->m_Snap.m_aInfoByScore[i];\n\t\t\tif(!pInfo->m_pPlayerInfo || m_pClient->m_aClients[pInfo->m_ClientID].m_Team != Team || (!RenderDead && (pInfo->m_pPlayerInfo->m_PlayerFlags&PLAYERFLAG_DEAD)) ||\n\t\t\t\t(RenderDead && !(pInfo->m_pPlayerInfo->m_PlayerFlags&PLAYERFLAG_DEAD)))\n\t\t\t\tcontinue;\n\n\t\t\t// background so it's easy to find the local player or the followed one in spectator mode\n\t\t\tif(m_pClient->m_LocalClientID == pInfo->m_ClientID || (m_pClient->m_Snap.m_SpecInfo.m_Active && pInfo->m_ClientID == m_pClient->m_Snap.m_SpecInfo.m_SpectatorID))\n\t\t\t{\n\t\t\t\tGraphics()->TextureClear();\n\t\t\t\tGraphics()->QuadsBegin();\n\t\t\t\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 0.25f*ColorAlpha);\n\t\t\t\tRenderTools()->DrawRoundRect(x, y, w-20.0f, LineHeight, 15.0f);\n\t\t\t\tGraphics()->QuadsEnd();\n\t\t\t}\n\n\t\t\t// score\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"%d\", clamp(pInfo->m_pPlayerInfo->m_Score, -999, 999));\n\t\t\ttw = TextRender()->TextWidth(0, FontSize, aBuf, -1);\n\t\t\tTextRender()->SetCursor(&Cursor, ScoreOffset+ScoreLength-tw, y+Spacing, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\t\t\tCursor.m_LineWidth = ScoreLength;\n\t\t\tTextRender()->TextEx(&Cursor, aBuf, -1);\n\n\t\t\t// flag\n\t\t\tif(m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_FLAGS && m_pClient->m_Snap.m_pGameDataFlag &&\n\t\t\t\t(m_pClient->m_Snap.m_pGameDataFlag->m_FlagCarrierRed == pInfo->m_ClientID ||\n\t\t\t\tm_pClient->m_Snap.m_pGameDataFlag->m_FlagCarrierBlue == pInfo->m_ClientID))\n\t\t\t{\n\t\t\t\tGraphics()->BlendNormal();\n\t\t\t\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);\n\t\t\t\tGraphics()->QuadsBegin();\n\n\t\t\t\tRenderTools()->SelectSprite(m_pClient->m_aClients[pInfo->m_ClientID].m_Team==TEAM_RED ? SPRITE_FLAG_BLUE : SPRITE_FLAG_RED, SPRITE_FLAG_FLIP_X);\n\n\t\t\t\tfloat Size = LineHeight;\n\t\t\t\tIGraphics::CQuadItem QuadItem(TeeOffset+0.0f, y-5.0f-Spacing/2.0f, Size/2.0f, Size);\n\t\t\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t\t\t\tGraphics()->QuadsEnd();\n\t\t\t}\n\n\t\t\t// avatar\n\t\t\tif(RenderDead)\n\t\t\t{\n\t\t\t\tGraphics()->BlendNormal();\n\t\t\t\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_DEADTEE].m_Id);\n\t\t\t\tGraphics()->QuadsBegin();\n\t\t\t\tIGraphics::CQuadItem QuadItem(TeeOffset, y, 64*TeeSizeMod, 64*TeeSizeMod);\n\t\t\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t\t\t\tGraphics()->QuadsEnd();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tCTeeRenderInfo TeeInfo = m_pClient->m_aClients[pInfo->m_ClientID].m_RenderInfo;\n\t\t\t\tTeeInfo.m_Size *= TeeSizeMod;\n\t\t\t\tRenderTools()->RenderTee(CAnimState::GetIdle(), &TeeInfo, EMOTE_NORMAL, vec2(1.0f, 0.0f), vec2(TeeOffset+TeeLength/2, y+LineHeight/2));\n\t\t\t}\n\n\t\t\t// name\n\t\t\t// todo: improve visual player ready state\n\t\t\tif(!(pInfo->m_pPlayerInfo->m_PlayerFlags&PLAYERFLAG_READY))\n\t\t\t\tTextRender()->TextColor(1.0f, 0.5f, 0.5f, ColorAlpha);\n\t\t\telse if(RenderDead && pInfo->m_pPlayerInfo->m_PlayerFlags&PLAYERFLAG_WATCHING)\n\t\t\t\tTextRender()->TextColor(1.0f, 1.0f, 0.0f, ColorAlpha);\n\t\t\tTextRender()->SetCursor(&Cursor, NameOffset, y+Spacing, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\t\t\tCursor.m_LineWidth = NameLength;\n\t\t\tTextRender()->TextEx(&Cursor, m_pClient->m_aClients[pInfo->m_ClientID].m_aName, -1);\n\t\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, ColorAlpha);\n\n\t\t\t// clan\n\t\t\ttw = TextRender()->TextWidth(0, FontSize, m_pClient->m_aClients[pInfo->m_ClientID].m_aClan, -1);\n\t\t\tTextRender()->SetCursor(&Cursor, ClanOffset+ClanLength/2-tw/2, y+Spacing, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\t\t\tCursor.m_LineWidth = ClanLength;\n\t\t\tTextRender()->TextEx(&Cursor, m_pClient->m_aClients[pInfo->m_ClientID].m_aClan, -1);\n\n\t\t\t// country flag\n\t\t\tvec4 Color(1.0f, 1.0f, 1.0f, 0.5f*ColorAlpha);\n\t\t\tm_pClient->m_pCountryFlags->Render(m_pClient->m_aClients[pInfo->m_ClientID].m_Country, &Color,\n\t\t\t\t\t\t\t\t\t\t\t\tCountryOffset, y+(Spacing+TeeSizeMod*5.0f)/2.0f, CountryLength, LineHeight-Spacing-TeeSizeMod*5.0f);\n\n\t\t\t// ping\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"%d\", clamp(pInfo->m_pPlayerInfo->m_Latency, 0, 1000));\n\t\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 0.7f);\n\t\t\ttw = TextRender()->TextWidth(0, FontSize, aBuf, -1);\n\t\t\tTextRender()->SetCursor(&Cursor, PingOffset+PingLength-tw, y+Spacing, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\t\t\tCursor.m_LineWidth = PingLength;\n\t\t\tTextRender()->TextEx(&Cursor, aBuf, -1);\n\t\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\ty += LineHeight+Spacing;\n\t\t}\n\t}\n\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n}\n\nvoid CScoreboard::RenderRecordingNotification(float x)\n{\n\tif(!m_pClient->DemoRecorder()->IsRecording())\n\t\treturn;\n\n\t//draw the box\n\tGraphics()->BlendNormal();\n\tGraphics()->TextureClear();\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(0.0f, 0.0f, 0.0f, 0.4f);\n\tRenderTools()->DrawRoundRectExt(x, 0.0f, 180.0f, 50.0f, 15.0f, CUI::CORNER_B);\n\tGraphics()->QuadsEnd();\n\n\t//draw the red dot\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(1.0f, 0.0f, 0.0f, 1.0f);\n\tRenderTools()->DrawRoundRect(x+20, 15.0f, 20.0f, 20.0f, 10.0f);\n\tGraphics()->QuadsEnd();\n\n\t//draw the text\n\tchar aBuf[64];\n\tint Seconds = m_pClient->DemoRecorder()->Length();\n\tstr_format(aBuf, sizeof(aBuf), Localize(\"REC %3d:%02d\"), Seconds/60, Seconds%60);\n\tTextRender()->Text(0, x+50.0f, 10.0f, 20.0f, aBuf, -1);\n}\n\nvoid CScoreboard::OnRender()\n{\n\tif(!Active())\n\t\treturn;\n\n\t// if the score board is active, then we should clear the motd message aswell\n\tif(m_pClient->m_pMotd->IsActive())\n\t\tm_pClient->m_pMotd->Clear();\n\n\n\tfloat Width = 400*3.0f*Graphics()->ScreenAspect();\n\tfloat Height = 400*3.0f;\n\n\tGraphics()->MapScreen(0, 0, Width, Height);\n\n\tfloat w = 700.0f;\n\n\tif(m_pClient->m_Snap.m_pGameData)\n\t{\n\t\tif(!(m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS))\n\t\t\tRenderScoreboard(Width/2-w/2, 150.0f, w, 0, 0);\n\t\telse if(m_pClient->m_Snap.m_pGameDataTeam)\n\t\t{\n\t\t\tconst char *pRedClanName = GetClanName(TEAM_RED);\n\t\t\tconst char *pBlueClanName = GetClanName(TEAM_BLUE);\n\n\t\t\tif(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)\n\t\t\t{\n\t\t\t\tchar aText[256];\n\t\t\t\tstr_copy(aText, Localize(\"Draw!\"), sizeof(aText));\n\n\t\t\t\tif(m_pClient->m_Snap.m_pGameDataTeam->m_TeamscoreRed > m_pClient->m_Snap.m_pGameDataTeam->m_TeamscoreBlue)\n\t\t\t\t{\n\t\t\t\t\tif(pRedClanName)\n\t\t\t\t\t\tstr_format(aText, sizeof(aText), Localize(\"%s wins!\"), pRedClanName);\n\t\t\t\t\telse\n\t\t\t\t\t\tstr_copy(aText, Localize(\"Red team wins!\"), sizeof(aText));\n\t\t\t\t}\n\t\t\t\telse if(m_pClient->m_Snap.m_pGameDataTeam->m_TeamscoreBlue > m_pClient->m_Snap.m_pGameDataTeam->m_TeamscoreRed)\n\t\t\t\t{\n\t\t\t\t\tif(pBlueClanName)\n\t\t\t\t\t\tstr_format(aText, sizeof(aText), Localize(\"%s wins!\"), pBlueClanName);\n\t\t\t\t\telse\n\t\t\t\t\t\tstr_copy(aText, Localize(\"Blue team wins!\"), sizeof(aText));\n\t\t\t\t}\n\n\t\t\t\tfloat w = TextRender()->TextWidth(0, 86.0f, aText, -1);\n\t\t\t\tTextRender()->Text(0, Width/2-w/2, 39, 86.0f, aText, -1);\n\t\t\t}\n\t\t\telse if(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_ROUNDOVER)\n\t\t\t{\n\t\t\t\tchar aText[256];\n\t\t\t\tstr_copy(aText, Localize(\"Round over!\"), sizeof(aText));\n\n\t\t\t\tfloat w = TextRender()->TextWidth(0, 86.0f, aText, -1);\n\t\t\t\tTextRender()->Text(0, Width/2-w/2, 39, 86.0f, aText, -1);\n\t\t\t}\n\n\t\t\tRenderScoreboard(Width/2-w-5.0f, 150.0f, w, TEAM_RED, pRedClanName ? pRedClanName : Localize(\"Red team\"));\n\t\t\tRenderScoreboard(Width/2+5.0f, 150.0f, w, TEAM_BLUE, pBlueClanName ? pBlueClanName : Localize(\"Blue team\"));\n\t\t}\n\n\t\tRenderGoals(Width/2-w/2, 150+760+10, w);\n\t\tRenderSpectators(Width/2-w/2, 150+760+10+50+10, w);\n\t}\n\n\tRenderRecordingNotification((Width/7)*4);\n}\n\nbool CScoreboard::Active()\n{\n\t// if we activly wanna look on the scoreboard\n\tif(m_Active)\n\t\treturn true;\n\n\tif(m_pClient->m_LocalClientID != -1 && m_pClient->m_aClients[m_pClient->m_LocalClientID].m_Team != TEAM_SPECTATORS)\n\t{\n\t\t// we are not a spectator, check if we are dead, don't follow a player and the game isn't paused\n\t\tif(!m_pClient->m_Snap.m_pLocalCharacter && !m_pClient->m_Snap.m_SpecInfo.m_Active &&\n\t\t\t!(m_pClient->m_Snap.m_pGameData && m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED))\n\t\t\treturn true;\n\t}\n\n\t// if the game is over\n\tif(m_pClient->m_Snap.m_pGameData && m_pClient->m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_ROUNDOVER|GAMESTATEFLAG_GAMEOVER))\n\t\treturn true;\n\n\treturn false;\n}\n\nconst char *CScoreboard::GetClanName(int Team)\n{\n\tint ClanPlayers = 0;\n\tconst char *pClanName = 0;\n\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t{\n\t\tif(!m_pClient->m_aClients[i].m_Active || m_pClient->m_aClients[i].m_Team != Team)\n\t\t\tcontinue;\n\n\t\tif(!pClanName)\n\t\t{\n\t\t\tpClanName = m_pClient->m_aClients[i].m_aClan;\n\t\t\tClanPlayers++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(str_comp(m_pClient->m_aClients[i].m_aClan, pClanName) == 0)\n\t\t\t\tClanPlayers++;\n\t\t\telse\n\t\t\t\treturn 0;\n\t\t}\n\t}\n\n\tif(ClanPlayers > 1 && pClanName[0])\n\t\treturn pClanName;\n\telse\n\t\treturn 0;\n}\n"
  },
  {
    "path": "src/game/client/components/scoreboard.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_SCOREBOARD_H\n#define GAME_CLIENT_COMPONENTS_SCOREBOARD_H\n#include <game/client/component.h>\n\nclass CScoreboard : public CComponent\n{\n\tvoid RenderGoals(float x, float y, float w);\n\tvoid RenderSpectators(float x, float y, float w);\n\tvoid RenderScoreboard(float x, float y, float w, int Team, const char *pTitle);\n\tvoid RenderRecordingNotification(float x);\n\n\tstatic void ConKeyScoreboard(IConsole::IResult *pResult, void *pUserData);\n\n\tconst char *GetClanName(int Team);\n\n\tbool m_Active;\n\npublic:\n\tCScoreboard();\n\tvirtual void OnReset();\n\tvirtual void OnConsoleInit();\n\tvirtual void OnRender();\n\tvirtual void OnRelease();\n\n\tbool Active();\n};\n\n#endif\n"
  },
  {
    "path": "src/game/client/components/skins.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <math.h>\n\n#include <base/system.h>\n#include <base/math.h>\n\n#include <engine/graphics.h>\n#include <engine/storage.h>\n#include <engine/external/json-parser/json.h>\n#include <engine/shared/config.h>\n\n#include \"skins.h\"\n\n\nconst char * const CSkins::ms_apSkinPartNames[NUM_SKINPARTS] = {\"body\", \"tattoo\", \"decoration\", \"hands\", \"feet\", \"eyes\"};\nconst char * const CSkins::ms_apColorComponents[NUM_COLOR_COMPONENTS] = {\"hue\", \"sat\", \"lgt\", \"alp\"};\n\nchar *const CSkins::ms_apSkinVariables[NUM_SKINPARTS] = {g_Config.m_PlayerSkinBody, g_Config.m_PlayerSkinTattoo, g_Config.m_PlayerSkinDecoration,\n\t\t\t\t\t\t\t\t\t\t\t\t\tg_Config.m_PlayerSkinHands, g_Config.m_PlayerSkinFeet, g_Config.m_PlayerSkinEyes};\nint *const CSkins::ms_apUCCVariables[NUM_SKINPARTS] = {&g_Config.m_PlayerUseCustomColorBody, &g_Config.m_PlayerUseCustomColorTattoo, &g_Config.m_PlayerUseCustomColorDecoration,\n\t\t\t\t\t\t\t\t\t\t\t\t\t&g_Config.m_PlayerUseCustomColorHands, &g_Config.m_PlayerUseCustomColorFeet, &g_Config.m_PlayerUseCustomColorEyes};\nint *const CSkins::ms_apColorVariables[NUM_SKINPARTS] = {&g_Config.m_PlayerColorBody, &g_Config.m_PlayerColorTattoo, &g_Config.m_PlayerColorDecoration,\n\t\t\t\t\t\t\t\t\t\t\t\t\t&g_Config.m_PlayerColorHands, &g_Config.m_PlayerColorFeet, &g_Config.m_PlayerColorEyes};\n\n\nint CSkins::SkinPartScan(const char *pName, int IsDir, int DirType, void *pUser)\n{\n\tCSkins *pSelf = (CSkins *)pUser;\n\tint l = str_length(pName);\n\tif(l < 4 || IsDir || str_comp(pName+l-4, \".png\") != 0)\n\t\treturn 0;\n\n\tchar aBuf[512];\n\tstr_format(aBuf, sizeof(aBuf), \"skins/%s/%s\", CSkins::ms_apSkinPartNames[pSelf->m_ScanningPart], pName);\n\tCImageInfo Info;\n\tif(!pSelf->Graphics()->LoadPNG(&Info, aBuf, DirType))\n\t{\n\t\tstr_format(aBuf, sizeof(aBuf), \"failed to load skin part '%s'\", pName);\n\t\tpSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"skins\", aBuf);\n\t\treturn 0;\n\t}\n\n\tCSkinPart Part;\n\tPart.m_OrgTexture = pSelf->Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0);\n\tPart.m_BloodColor = vec3(1.0f, 1.0f, 1.0f);\n\n\tunsigned char *d = (unsigned char *)Info.m_pData;\n\tint Pitch = Info.m_Width*4;\n\n\t// dig out blood color\n\tif(pSelf->m_ScanningPart == SKINPART_BODY)\n\t{\n\t\tint PartX = Info.m_Width/2;\n\t\tint PartY = 0;\n\t\tint PartWidth = Info.m_Width/2;\n\t\tint PartHeight = Info.m_Height/2;\n\n\t\tint aColors[3] = {0};\n\t\tfor(int y = PartY; y < PartY+PartHeight; y++)\n\t\t\tfor(int x = PartX; x < PartX+PartWidth; x++)\n\t\t\t{\n\t\t\t\tif(d[y*Pitch+x*4+3] > 128)\n\t\t\t\t{\n\t\t\t\t\taColors[0] += d[y*Pitch+x*4+0];\n\t\t\t\t\taColors[1] += d[y*Pitch+x*4+1];\n\t\t\t\t\taColors[2] += d[y*Pitch+x*4+2];\n\t\t\t\t}\n\t\t\t}\n\n\t\tPart.m_BloodColor = normalize(vec3(aColors[0], aColors[1], aColors[2]));\n\t}\n\n\t// create colorless version\n\tint Step = Info.m_Format == CImageInfo::FORMAT_RGBA ? 4 : 3;\n\n\t// make the texture gray scale\n\tfor(int i = 0; i < Info.m_Width*Info.m_Height; i++)\n\t{\n\t\tint v = (d[i*Step]+d[i*Step+1]+d[i*Step+2])/3;\n\t\td[i*Step] = v;\n\t\td[i*Step+1] = v;\n\t\td[i*Step+2] = v;\n\t}\n\n\tPart.m_ColorTexture = pSelf->Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0);\n\tmem_free(Info.m_pData);\n\n\t// set skin part data\n\tPart.m_Flags = 0;\n\tif(pName[0] == 'x' && pName[1] == '_')\n\t\tPart.m_Flags |= SKINFLAG_SPECIAL;\n\tif(DirType != IStorage::TYPE_SAVE)\n\t\tPart.m_Flags |= SKINFLAG_STANDARD;\n\tstr_copy(Part.m_aName, pName, min((int)sizeof(Part.m_aName),l-3));\n\tif(g_Config.m_Debug)\n\t{\n\t\tstr_format(aBuf, sizeof(aBuf), \"load skin part %s\", Part.m_aName);\n\t\tpSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"skins\", aBuf);\n\t}\n\tpSelf->m_aaSkinParts[pSelf->m_ScanningPart].add(Part);\n\n\treturn 0;\n}\n\nint CSkins::SkinScan(const char *pName, int IsDir, int DirType, void *pUser)\n{\n\tint l = str_length(pName);\n\tif(l < 5 || IsDir || str_comp(pName+l-5, \".json\") != 0)\n\t\treturn 0;\n\n\tCSkins *pSelf = (CSkins *)pUser;\n\n\t// read file data into buffer\n\tchar aBuf[512];\n\tstr_format(aBuf, sizeof(aBuf), \"skins/%s\", pName);\n\tIOHANDLE File = pSelf->Storage()->OpenFile(aBuf, IOFLAG_READ, IStorage::TYPE_ALL);\n\tif(!File)\n\t\treturn 0;\n\tint FileSize = (int)io_length(File);\n\tchar *pFileData = (char *)mem_alloc(FileSize+1, 1);\n\tio_read(File, pFileData, FileSize);\n\tpFileData[FileSize] = 0;\n\tio_close(File);\n\n\t// init\n\tCSkin Skin = pSelf->m_DummySkin;\n\tbool SpecialSkin = pName[0] == 'x' && pName[1] == '_';\n\n\t// parse json data\n\tjson_settings JsonSettings;\n\tmem_zero(&JsonSettings, sizeof(JsonSettings));\n\tchar aError[256];\n\tjson_value *pJsonData = json_parse_ex(&JsonSettings, pFileData, aError);\n\tif(pJsonData == 0)\n\t{\n\t\tpSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, aBuf, aError);\n\t\tmem_free(pFileData);\n\t\treturn 0;\n\t}\n\n\t// extract data\n\tconst json_value &rStart = (*pJsonData)[\"skin\"];\n\tif(rStart.type == json_object)\n\t{\n\t\tfor(int PartIndex = 0; PartIndex < NUM_SKINPARTS; ++PartIndex)\n\t\t{\n\t\t\tconst json_value &rPart = rStart[(const char *)ms_apSkinPartNames[PartIndex]];\n\t\t\tif(rPart.type != json_object)\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\t// filename\n\t\t\tconst json_value &rFilename = rPart[\"filename\"];\n\t\t\tif(rFilename.type == json_string)\n\t\t\t{\n\t\t\t\tint SkinPart = pSelf->FindSkinPart(PartIndex, (const char *)rFilename, SpecialSkin);\n\t\t\t\tif(SkinPart > -1)\n\t\t\t\t\tSkin.m_apParts[PartIndex] = pSelf->GetSkinPart(PartIndex, SkinPart);\n\t\t\t}\n\n\t\t\t// use custom colors\n\t\t\tbool UseCustomColors = false;\n\t\t\tconst json_value &rColour = rPart[\"custom_colors\"];\n\t\t\tif(rColour.type == json_string)\n\t\t\t{\n\t\t\t\tUseCustomColors = str_comp((const char *)rColour, \"true\") == 0;\n\t\t\t}\n\t\t\tSkin.m_aUseCustomColors[PartIndex] = UseCustomColors;\n\n\t\t\t// color components\n\t\t\tif(!UseCustomColors)\n\t\t\t\tcontinue;\n\t\t\t\t\n\t\t\tfor(int i = 0; i < NUM_COLOR_COMPONENTS; i++)\n\t\t\t{\n\t\t\t\tif(PartIndex != SKINPART_TATTOO && i == 3)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tconst json_value &rComponent = rPart[(const char *)ms_apColorComponents[i]];\n\t\t\t\tif(rComponent.type == json_integer)\n\t\t\t\t{\n\t\t\t\t\tswitch(i)\n\t\t\t\t\t{\n\t\t\t\t\tcase 0: Skin.m_aPartColors[PartIndex] = (Skin.m_aPartColors[PartIndex]&0xFF00FFFF) | (rComponent.u.integer << 16); break;\n\t\t\t\t\tcase 1:\tSkin.m_aPartColors[PartIndex] = (Skin.m_aPartColors[PartIndex]&0xFFFF00FF) | (rComponent.u.integer << 8); break;\n\t\t\t\t\tcase 2: Skin.m_aPartColors[PartIndex] = (Skin.m_aPartColors[PartIndex]&0xFFFFFF00) | rComponent.u.integer; break;\n\t\t\t\t\tcase 3: Skin.m_aPartColors[PartIndex] = (Skin.m_aPartColors[PartIndex]&0x00FFFFFF) | (rComponent.u.integer << 24); break;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// clean up\n\tjson_value_free(pJsonData);\n\tmem_free(pFileData);\n\n\t// set skin data\n\tSkin.m_Flags = SpecialSkin ? SKINFLAG_SPECIAL : 0;\n\tif(DirType != IStorage::TYPE_SAVE)\n\t\tSkin.m_Flags |= SKINFLAG_STANDARD;\n\tstr_copy(Skin.m_aName, pName, min((int)sizeof(Skin.m_aName),l-4));\n\tif(g_Config.m_Debug)\n\t{\n\t\tstr_format(aBuf, sizeof(aBuf), \"load skin %s\", Skin.m_aName);\n\t\tpSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"skins\", aBuf);\n\t}\n\tpSelf->m_aSkins.add(Skin);\n\n\treturn 0;\n}\n\n\nvoid CSkins::OnInit()\n{\n\tfor(int p = 0; p < NUM_SKINPARTS; p++)\n\t{\n\t\tm_aaSkinParts[p].clear();\n\n\t\t// add none part\n\t\tif(p == SKINPART_TATTOO || p == SKINPART_DECORATION)\n\t\t{\n\t\t\tCSkinPart NoneSkinPart;\n\t\t\tNoneSkinPart.m_Flags = SKINFLAG_STANDARD;\n\t\t\tstr_copy(NoneSkinPart.m_aName, \"\", sizeof(NoneSkinPart.m_aName));\n\t\t\tNoneSkinPart.m_BloodColor = vec3(1.0f, 1.0f, 1.0f);\n\t\t\tm_aaSkinParts[p].add(NoneSkinPart);\n\t\t}\n\n\t\t// load skin parts\n\t\tchar aBuf[64];\n\t\tstr_format(aBuf, sizeof(aBuf), \"skins/%s\", ms_apSkinPartNames[p]);\n\t\tm_ScanningPart = p;\n\t\tStorage()->ListDirectory(IStorage::TYPE_ALL, aBuf, SkinPartScan, this);\n\n\t\t// add dummy skin part\n\t\tif(!m_aaSkinParts[p].size())\n\t\t{\n\t\t\tCSkinPart DummySkinPart;\n\t\t\tDummySkinPart.m_Flags = SKINFLAG_STANDARD;\n\t\t\tstr_copy(DummySkinPart.m_aName, \"dummy\", sizeof(DummySkinPart.m_aName));\n\t\t\tDummySkinPart.m_BloodColor = vec3(1.0f, 1.0f, 1.0f);\n\t\t\tm_aaSkinParts[p].add(DummySkinPart);\n\t\t}\n\t}\n\n\t// create dummy skin\n\tm_DummySkin.m_Flags = SKINFLAG_STANDARD;\n\tstr_copy(m_DummySkin.m_aName, \"dummy\", sizeof(m_DummySkin.m_aName));\n\tfor(int p = 0; p < NUM_SKINPARTS; p++)\n\t{\n\t\tint Default;\n\t\tif(p == SKINPART_TATTOO || p == SKINPART_DECORATION)\n\t\t\tDefault = FindSkinPart(p, \"\", false);\n\t\telse\n\t\t\tDefault = FindSkinPart(p, \"standard\", false);\n\t\tif(Default < 0)\n\t\t\tDefault = 0;\n\t\tm_DummySkin.m_apParts[p] = GetSkinPart(p, Default);\n\t\tm_DummySkin.m_aPartColors[p] = p==SKINPART_TATTOO ? (255<<24)+65408 : 65408;\n\t\tm_DummySkin.m_aUseCustomColors[p] = 0;\n\t}\n\n\t// load skins\n\tm_aSkins.clear();\n\tStorage()->ListDirectory(IStorage::TYPE_ALL, \"skins\", SkinScan, this);\n\n\t// add dummy skin\n\tif(!m_aSkins.size())\n\t\tm_aSkins.add(m_DummySkin);\n}\n\nvoid CSkins::AddSkin(const char *pSkinName)\n{\n\tCSkin Skin = m_DummySkin;\n\tSkin.m_Flags = 0;\n\tstr_copy(Skin.m_aName, pSkinName, sizeof(Skin.m_aName));\n\tfor(int PartIndex = 0; PartIndex < NUM_SKINPARTS; ++PartIndex)\n\t{\n\t\tint SkinPart = FindSkinPart(PartIndex, ms_apSkinVariables[PartIndex], false);\n\t\tif(SkinPart > -1)\n\t\t\tSkin.m_apParts[PartIndex] = GetSkinPart(PartIndex, SkinPart);\n\t\tSkin.m_aUseCustomColors[PartIndex] = *ms_apUCCVariables[PartIndex];\n\t\tSkin.m_aPartColors[PartIndex] = *ms_apColorVariables[PartIndex];\n\t}\n\tm_aSkins.add(Skin);\n}\n\nvoid CSkins::RemoveSkin(const CSkin *pSkin)\n{\n\tm_aSkins.remove(*pSkin);\n}\n\nint CSkins::Num()\n{\n\treturn m_aSkins.size();\n}\n\nint CSkins::NumSkinPart(int Part)\n{\n\treturn m_aaSkinParts[Part].size();\n}\n\nconst CSkins::CSkin *CSkins::Get(int Index)\n{\n\treturn &m_aSkins[max(0, Index%m_aSkins.size())];\n}\n\nint CSkins::Find(const char *pName, bool AllowSpecialSkin)\n{\n\tfor(int i = 0; i < m_aSkins.size(); i++)\n\t{\n\t\tif(str_comp(m_aSkins[i].m_aName, pName) == 0 && ((m_aSkins[i].m_Flags&SKINFLAG_SPECIAL) == 0 || AllowSpecialSkin))\n\t\t\treturn i;\n\t}\n\treturn -1;\n}\n\nconst CSkins::CSkinPart *CSkins::GetSkinPart(int Part, int Index)\n{\n\tint Size = m_aaSkinParts[Part].size();\n\treturn &m_aaSkinParts[Part][max(0, Index%Size)];\n}\n\nint CSkins::FindSkinPart(int Part, const char *pName, bool AllowSpecialPart)\n{\n\tfor(int i = 0; i < m_aaSkinParts[Part].size(); i++)\n\t{\n\t\tif(str_comp(m_aaSkinParts[Part][i].m_aName, pName) == 0 && ((m_aaSkinParts[Part][i].m_Flags&SKINFLAG_SPECIAL) == 0 || AllowSpecialPart))\n\t\t\treturn i;\n\t}\n\treturn -1;\n}\n\nvec3 CSkins::GetColorV3(int v) const\n{\n\tfloat Dark = DARKEST_COLOR_LGT/255.0f;\n\treturn HslToRgb(vec3(((v>>16)&0xff)/255.0f, ((v>>8)&0xff)/255.0f, Dark+(v&0xff)/255.0f*(1.0f-Dark)));\n}\n\nvec4 CSkins::GetColorV4(int v, bool UseAlpha) const\n{\n\tvec3 r = GetColorV3(v);\n\tfloat Alpha = UseAlpha ? ((v>>24)&0xff)/255.0f : 1.0f;\n\treturn vec4(r.r, r.g, r.b, Alpha);\n}\n\nint CSkins::GetTeamColor(int UseCustomColors, int PartColor, int Team, int Part) const\n{\n\tstatic const int s_aTeamColors[3] = {12895054, 65387, 10223467};\n\tif(!UseCustomColors)\n\t{\n\t\tint ColorVal = s_aTeamColors[Team+1];\n\t\tif(Part == SKINPART_TATTOO)\n\t\t\tColorVal |= 0xff000000;\n\t\treturn ColorVal;\n\t}\n\n\t/*blue128:  128/PI*ARCSIN(COS((PI*(x+10)/128)))+182 // (decoration, tattoo, hands)\n\tblue64:  64/PI*ARCSIN(COS((PI*(x-76)/64)))+172 // (body, feet, eyes)\n\tred128:   Mod((128/PI*ARCSIN(COS((PI*(x-105)/128)))+297),256)\n\tred64:    Mod((64/PI*ARCSIN(COS((PI*(x-56)/64)))+280),256)*/\n\n\tint MinSat = 160;\n\tint MaxSat = 255;\n\tfloat Dark = DARKEST_COLOR_LGT/255.0f;\n\tint MinLgt = Dark + 64*(1.0f-Dark);\n\tint MaxLgt = Dark + 191*(1.0f-Dark);\n\n\tint Hue = 0;\n\tint Sat = (PartColor>>8)&0xff;\n\tint Lgt = PartColor&0xff;\n\n\tint NewHue;\n\tif(Team == TEAM_RED)\n\t{\n\t\tif(Part == SKINPART_TATTOO || Part == SKINPART_DECORATION || Part == SKINPART_HANDS)\n\t\t\tNewHue = (int)(128.0f/pi*asinf(cosf(pi/128.0f*(Hue-105.0f))) + 297.0f) % 256;\n\t\telse\n\t\t\tNewHue = (int)(64.0f/pi*asinf(cosf(pi/64.0f*(Hue-56.0f))) + 280.0f) % 256;\n\t}\n\telse\n\t\tNewHue = 64.0f/pi*asinf(cosf(pi/64.0f*(Hue-76.0f))) + 172.0f;\n\n\tint NewSat = clamp(Sat, MinSat, MaxSat);\n\tint NewLgt = clamp(Lgt, MinLgt, MaxLgt);\n\tint ColorVal = (NewHue<<16) + (NewSat<<8) + NewLgt;\n\n\tif(Part == SKINPART_TATTOO)\n\t\tColorVal += PartColor&0xff000000;\n\n\treturn ColorVal;\n}\n"
  },
  {
    "path": "src/game/client/components/skins.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_SKINS_H\n#define GAME_CLIENT_COMPONENTS_SKINS_H\n#include <base/vmath.h>\n#include <base/tl/sorted_array.h>\n#include <game/client/component.h>\n\n// todo: fix duplicate skins (different paths)\nclass CSkins : public CComponent\n{\npublic:\n\tenum\n\t{\n\t\tSKINFLAG_SPECIAL=1<<0,\n\t\tSKINFLAG_STANDARD=1<<1,\n\n\t\tSKINPART_BODY=0,\n\t\tSKINPART_TATTOO,\n\t\tSKINPART_DECORATION,\n\t\tSKINPART_HANDS,\n\t\tSKINPART_FEET,\n\t\tSKINPART_EYES,\n\t\tNUM_SKINPARTS,\n\n\t\tDARKEST_COLOR_LGT=61,\n\t\t\n\t\tNUM_COLOR_COMPONENTS=4\n\t};\n\n\tstruct CSkinPart\n\t{\n\t\tint m_Flags;\n\t\tchar m_aName[24];\n\t\tIGraphics::CTextureHandle m_OrgTexture;\n\t\tIGraphics::CTextureHandle m_ColorTexture;\n\t\tvec3 m_BloodColor;\n\n\t\tbool operator<(const CSkinPart &Other) { return str_comp_nocase(m_aName, Other.m_aName) < 0; }\n\t};\n\n\tstruct CSkin\n\t{\n\t\tint m_Flags;\n\t\tchar m_aName[24];\n\t\tconst CSkinPart *m_apParts[NUM_SKINPARTS];\n\t\tint m_aPartColors[NUM_SKINPARTS];\n\t\tint m_aUseCustomColors[NUM_SKINPARTS];\n\n\t\tbool operator<(const CSkin &Other) { return str_comp_nocase(m_aName, Other.m_aName) < 0; }\n\t\tbool operator==(const CSkin &Other) { return mem_comp(this, &Other, sizeof(CSkin)) == 0; }\n\t};\n\n\tstatic const char * const ms_apSkinPartNames[NUM_SKINPARTS];\n\tstatic const char * const ms_apColorComponents[NUM_COLOR_COMPONENTS];\n\n\tstatic char * const ms_apSkinVariables[NUM_SKINPARTS];\n\tstatic int * const ms_apUCCVariables[NUM_SKINPARTS]; // use custom color\n\tstatic int * const ms_apColorVariables[NUM_SKINPARTS];\n\n\t//\n\tvoid OnInit();\n\n\tvoid AddSkin(const char *pSkinName);\n\tvoid RemoveSkin(const CSkin *pSkin);\n\n\tint Num();\n\tint NumSkinPart(int Part);\n\tconst CSkin *Get(int Index);\n\tint Find(const char *pName, bool AllowSpecialSkin);\n\tconst CSkinPart *GetSkinPart(int Part, int Index);\n\tint FindSkinPart(int Part, const char *pName, bool AllowSpecialPart);\n\n\tvec3 GetColorV3(int v) const;\n\tvec4 GetColorV4(int v, bool UseAlpha) const;\n\tint GetTeamColor(int UseCustomColors, int PartColor, int Team, int Part) const;\n\nprivate:\n\tint m_ScanningPart;\n\tsorted_array<CSkinPart> m_aaSkinParts[NUM_SKINPARTS];\n\tsorted_array<CSkin> m_aSkins;\n\tCSkin m_DummySkin;\n\n\tstatic int SkinPartScan(const char *pName, int IsDir, int DirType, void *pUser);\n\tstatic int SkinScan(const char *pName, int IsDir, int DirType, void *pUser);\n};\n\n#endif\n"
  },
  {
    "path": "src/game/client/components/sounds.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/engine.h>\n#include <engine/sound.h>\n#include <engine/shared/config.h>\n#include <game/generated/client_data.h>\n#include <game/client/gameclient.h>\n#include <game/client/components/camera.h>\n#include <game/client/components/menus.h>\n#include \"sounds.h\"\n\n\nstruct CUserData\n{\n\tCGameClient *m_pGameClient;\n\tbool m_Render;\n} g_UserData;\n\nstatic int LoadSoundsThread(void *pUser)\n{\n\tCUserData *pData = static_cast<CUserData *>(pUser);\n\n\tfor(int s = 0; s < g_pData->m_NumSounds; s++)\n\t{\n\t\tfor(int i = 0; i < g_pData->m_aSounds[s].m_NumSounds; i++)\n\t\t{\n\t\t\tISound::CSampleHandle Id = pData->m_pGameClient->Sound()->LoadWV(g_pData->m_aSounds[s].m_aSounds[i].m_pFilename);\n\t\t\tg_pData->m_aSounds[s].m_aSounds[i].m_Id = Id;\n\t\t}\n\n\t\tif(pData->m_Render)\n\t\t\tpData->m_pGameClient->m_pMenus->RenderLoading();\n\t}\n\n\treturn 0;\n}\n\nISound::CSampleHandle CSounds::GetSampleId(int SetId)\n{\n\tif(!g_Config.m_SndEnable || !Sound()->IsSoundEnabled() || m_WaitForSoundJob || SetId < 0 || SetId >= g_pData->m_NumSounds)\n\t\treturn ISound::CSampleHandle();\n\t\n\tCDataSoundset *pSet = &g_pData->m_aSounds[SetId];\n\tif(!pSet->m_NumSounds)\n\t\treturn ISound::CSampleHandle();\n\n\tif(pSet->m_NumSounds == 1)\n\t\treturn pSet->m_aSounds[0].m_Id;\n\n\t// return random one\n\tint Id;\n\tdo\n\t{\n\t\tId = rand() % pSet->m_NumSounds;\n\t}\n\twhile(Id == pSet->m_Last);\n\tpSet->m_Last = Id;\n\treturn pSet->m_aSounds[Id].m_Id;\n}\n\nvoid CSounds::OnInit()\n{\n\t// setup sound channels\n\tSound()->SetChannel(CSounds::CHN_GUI, 1.0f, 0.0f);\n\tSound()->SetChannel(CSounds::CHN_MUSIC, 1.0f, 0.0f);\n\tSound()->SetChannel(CSounds::CHN_WORLD, 0.9f, 1.0f);\n\tSound()->SetChannel(CSounds::CHN_GLOBAL, 1.0f, 0.0f);\n\n\tSound()->SetListenerPos(0.0f, 0.0f);\n\n\tClearQueue();\n\n\t// load sounds\n\tif(g_Config.m_ClThreadsoundloading)\n\t{\n\t\tg_UserData.m_pGameClient = m_pClient;\n\t\tg_UserData.m_Render = false;\n\t\tm_pClient->Engine()->AddJob(&m_SoundJob, LoadSoundsThread, &g_UserData);\n\t\tm_WaitForSoundJob = true;\n\t}\n\telse\n\t{\n\t\tg_UserData.m_pGameClient = m_pClient;\n\t\tg_UserData.m_Render = true;\n\t\tLoadSoundsThread(&g_UserData);\n\t\tm_WaitForSoundJob = false;\n\t}\n}\n\nvoid CSounds::OnReset()\n{\n\tif(Client()->State() >= IClient::STATE_ONLINE)\n\t{\n\t\tSound()->StopAll();\n\t\tClearQueue();\n\t}\n}\n\nvoid CSounds::OnStateChange(int NewState, int OldState)\n{\n\tif(NewState == IClient::STATE_ONLINE || NewState == IClient::STATE_DEMOPLAYBACK)\n\t\tOnReset();\n}\n\nvoid CSounds::OnRender()\n{\n\t// check for sound initialisation\n\tif(m_WaitForSoundJob)\n\t{\n\t\tif(m_SoundJob.Status() == CJob::STATE_DONE)\n\t\t\tm_WaitForSoundJob = false;\n\t\telse\n\t\t\treturn;\n\t}\n\n\t// set listner pos\n\tSound()->SetListenerPos(m_pClient->m_pCamera->m_Center.x, m_pClient->m_pCamera->m_Center.y);\n\n\t// play sound from queue\n\tif(m_QueuePos > 0)\n\t{\n\t\tint64 Now = time_get();\n\t\tif(m_QueueWaitTime <= Now)\n\t\t{\n\t\t\tPlay(m_aQueue[0].m_Channel, m_aQueue[0].m_SetId, 1.0f);\n\t\t\tm_QueueWaitTime = Now+time_freq()*3/10; // wait 300ms before playing the next one\n\t\t\tif(--m_QueuePos > 0)\n\t\t\t\tmem_move(m_aQueue, m_aQueue+1, m_QueuePos*sizeof(QueueEntry));\n\t\t}\n\t}\n}\n\nvoid CSounds::ClearQueue()\n{\n\tmem_zero(m_aQueue, sizeof(m_aQueue));\n\tm_QueuePos = 0;\n\tm_QueueWaitTime = time_get();\n}\n\nvoid CSounds::Enqueue(int Channel, int SetId)\n{\n\t// add sound to the queue\n\tif(m_QueuePos < QUEUE_SIZE)\n\t{\n\t\tif(Channel == CHN_MUSIC || !g_Config.m_ClEditor)\n\t\t{\n\t\t\tm_aQueue[m_QueuePos].m_Channel = Channel;\n\t\t\tm_aQueue[m_QueuePos++].m_SetId = SetId;\n\t\t}\n\t}\n}\n\nvoid CSounds::Play(int Chn, int SetId, float Vol)\n{\n\tif(Chn == CHN_MUSIC && !g_Config.m_SndMusic)\n\t\treturn;\n\n\tISound::CSampleHandle SampleId = GetSampleId(SetId);\n\tif(!SampleId.IsValid())\n\t\treturn;\n\n\tint Flags = 0;\n\tif(Chn == CHN_MUSIC)\n\t\tFlags = ISound::FLAG_LOOP;\n\n\tSound()->Play(Chn, SampleId, Flags);\n}\n\nvoid CSounds::PlayAt(int Chn, int SetId, float Vol, vec2 Pos)\n{\n\tif(Chn == CHN_MUSIC && !g_Config.m_SndMusic)\n\t\treturn;\n\t\n\tISound::CSampleHandle SampleId = GetSampleId(SetId);\n\tif(!SampleId.IsValid())\n\t\treturn;\n\n\tint Flags = 0;\n\tif(Chn == CHN_MUSIC)\n\t\tFlags = ISound::FLAG_LOOP;\n\n\tSound()->PlayAt(Chn, SampleId, Flags, Pos.x, Pos.y);\n}\n\nvoid CSounds::Stop(int SetId)\n{\n\tif(m_WaitForSoundJob || SetId < 0 || SetId >= g_pData->m_NumSounds)\n\t\treturn;\n\n\tCDataSoundset *pSet = &g_pData->m_aSounds[SetId];\n\n\tfor(int i = 0; i < pSet->m_NumSounds; i++)\n\t\tSound()->Stop(pSet->m_aSounds[i].m_Id);\n}\n"
  },
  {
    "path": "src/game/client/components/sounds.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_SOUNDS_H\n#define GAME_CLIENT_COMPONENTS_SOUNDS_H\n\n#include <engine/sound.h>\n#include <game/client/component.h>\n\nclass CSounds : public CComponent\n{\n\tenum\n\t{\n\t\tQUEUE_SIZE = 32,\n\t};\n\tstruct QueueEntry\n\t{\n\t\tint m_Channel;\n\t\tint m_SetId;\n\t} m_aQueue[QUEUE_SIZE];\n\tint m_QueuePos;\n\tint64 m_QueueWaitTime;\n\tclass CJob m_SoundJob;\n\tbool m_WaitForSoundJob;\n\t\n\tISound::CSampleHandle GetSampleId(int SetId);\n\npublic:\n\t// sound channels\n\tenum\n\t{\n\t\tCHN_GUI=0,\n\t\tCHN_MUSIC,\n\t\tCHN_WORLD,\n\t\tCHN_GLOBAL,\n\t};\n\n\tvirtual void OnInit();\n\tvirtual void OnReset();\n\tvirtual void OnStateChange(int NewState, int OldState);\n\tvirtual void OnRender();\n\n\tvoid ClearQueue();\n\tvoid Enqueue(int Channel, int SetId);\n\tvoid Play(int Channel, int SetId, float Vol);\n\tvoid PlayAt(int Channel, int SetId, float Vol, vec2 Pos);\n\tvoid Stop(int SetId);\n};\n\n\n#endif\n"
  },
  {
    "path": "src/game/client/components/spectator.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/demo.h>\n#include <engine/graphics.h>\n#include <engine/textrender.h>\n#include <engine/shared/config.h>\n\n#include <game/generated/client_data.h>\n#include <game/generated/protocol.h>\n\n#include <game/client/animstate.h>\n#include <game/client/render.h>\n\n#include \"spectator.h\"\n\n\nvoid CSpectator::ConKeySpectator(IConsole::IResult *pResult, void *pUserData)\n{\n\tCSpectator *pSelf = (CSpectator *)pUserData;\n\tif(pSelf->m_pClient->m_Snap.m_SpecInfo.m_Active &&\n\t\t(pSelf->Client()->State() != IClient::STATE_DEMOPLAYBACK || pSelf->DemoPlayer()->GetDemoType() == IDemoPlayer::DEMOTYPE_SERVER))\n\t\tpSelf->m_Active = pResult->GetInteger(0) != 0;\n}\n\nvoid CSpectator::ConSpectate(IConsole::IResult *pResult, void *pUserData)\n{\n\t((CSpectator *)pUserData)->Spectate(pResult->GetInteger(0));\n}\n\nvoid CSpectator::ConSpectateNext(IConsole::IResult *pResult, void *pUserData)\n{\n\tCSpectator *pSelf = (CSpectator *)pUserData;\n\tint NewSpectatorID;\n\tbool GotNewSpectatorID = false;\n\n\tif(pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW)\n\t{\n\t\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t\t{\n\t\t\tif(!pSelf->m_pClient->m_aClients[i].m_Active || pSelf->m_pClient->m_aClients[i].m_Team == TEAM_SPECTATORS)\n\t\t\t\tcontinue;\n\n\t\t\tNewSpectatorID = i;\n\t\t\tGotNewSpectatorID = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\telse\n\t{\n\t\tfor(int i = pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID + 1; i < MAX_CLIENTS; i++)\n\t\t{\n\t\t\tif(!pSelf->m_pClient->m_aClients[i].m_Active || pSelf->m_pClient->m_aClients[i].m_Team == TEAM_SPECTATORS)\n\t\t\t\tcontinue;\n\n\t\t\tNewSpectatorID = i;\n\t\t\tGotNewSpectatorID = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tif(!GotNewSpectatorID)\n\t\t{\n\t\t\tfor(int i = 0; i < pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID; i++)\n\t\t\t{\n\t\t\t\tif(!pSelf->m_pClient->m_aClients[i].m_Active || pSelf->m_pClient->m_aClients[i].m_Team == TEAM_SPECTATORS)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tNewSpectatorID = i;\n\t\t\t\tGotNewSpectatorID = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tif(GotNewSpectatorID)\n\t\tpSelf->Spectate(NewSpectatorID);\n}\n\nvoid CSpectator::ConSpectatePrevious(IConsole::IResult *pResult, void *pUserData)\n{\n\tCSpectator *pSelf = (CSpectator *)pUserData;\n\tint NewSpectatorID;\n\tbool GotNewSpectatorID = false;\n\n\tif(pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW)\n\t{\n\t\tfor(int i = MAX_CLIENTS -1; i > -1; i--)\n\t\t{\n\t\t\tif(!pSelf->m_pClient->m_aClients[i].m_Active || pSelf->m_pClient->m_aClients[i].m_Team == TEAM_SPECTATORS)\n\t\t\t\tcontinue;\n\n\t\t\tNewSpectatorID = i;\n\t\t\tGotNewSpectatorID = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\telse\n\t{\n\t\tfor(int i = pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID - 1; i > -1; i--)\n\t\t{\n\t\t\tif(!pSelf->m_pClient->m_aClients[i].m_Active || pSelf->m_pClient->m_aClients[i].m_Team == TEAM_SPECTATORS)\n\t\t\t\tcontinue;\n\n\t\t\tNewSpectatorID = i;\n\t\t\tGotNewSpectatorID = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tif(!GotNewSpectatorID)\n\t\t{\n\t\t\tfor(int i = MAX_CLIENTS - 1; i > pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID; i--)\n\t\t\t{\n\t\t\t\tif(!pSelf->m_pClient->m_aClients[i].m_Active || pSelf->m_pClient->m_aClients[i].m_Team == TEAM_SPECTATORS)\n\t\t\t\t\tcontinue;\n\n\t\t\tNewSpectatorID = i;\n\t\t\tGotNewSpectatorID = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tif(GotNewSpectatorID)\n\t\tpSelf->Spectate(NewSpectatorID);\n}\n\nCSpectator::CSpectator()\n{\n\tOnReset();\n}\n\nvoid CSpectator::OnConsoleInit()\n{\n\tConsole()->Register(\"+spectate\", \"\", CFGFLAG_CLIENT, ConKeySpectator, this, \"Open spectator mode selector\");\n\tConsole()->Register(\"spectate\", \"i\", CFGFLAG_CLIENT, ConSpectate, this, \"Switch spectator mode\");\n\tConsole()->Register(\"spectate_next\", \"\", CFGFLAG_CLIENT, ConSpectateNext, this, \"Spectate the next player\");\n\tConsole()->Register(\"spectate_previous\", \"\", CFGFLAG_CLIENT, ConSpectatePrevious, this, \"Spectate the previous player\");\n}\n\nbool CSpectator::OnMouseMove(float x, float y)\n{\n\tif(!m_Active)\n\t\treturn false;\n\n\tUI()->ConvertMouseMove(&x, &y);\n\tm_SelectorMouse += vec2(x,y);\n\treturn true;\n}\n\nvoid CSpectator::OnRelease()\n{\n\tOnReset();\n}\n\nvoid CSpectator::OnRender()\n{\n\tif(!m_Active)\n\t{\n\t\tif(m_WasActive)\n\t\t{\n\t\t\tif(m_SelectedSpectatorID != NO_SELECTION)\n\t\t\t\tSpectate(m_SelectedSpectatorID);\n\t\t\tm_WasActive = false;\n\t\t}\n\t\treturn;\n\t}\n\n\tif(!m_pClient->m_Snap.m_SpecInfo.m_Active)\n\t{\n\t\tm_Active = false;\n\t\tm_WasActive = false;\n\t\treturn;\n\t}\n\n\tm_WasActive = true;\n\tm_SelectedSpectatorID = NO_SELECTION;\n\n\t// draw background\n\tfloat Width = 400*3.0f*Graphics()->ScreenAspect();\n\tfloat Height = 400*3.0f;\n\n\tGraphics()->MapScreen(0, 0, Width, Height);\n\n\tGraphics()->BlendNormal();\n\tGraphics()->TextureClear();\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(0.0f, 0.0f, 0.0f, 0.3f);\n\tRenderTools()->DrawRoundRect(Width/2.0f-300.0f, Height/2.0f-300.0f, 600.0f, 600.0f, 20.0f);\n\tGraphics()->QuadsEnd();\n\n\t// clamp mouse position to selector area\n\tm_SelectorMouse.x = clamp(m_SelectorMouse.x, -280.0f, 280.0f);\n\tm_SelectorMouse.y = clamp(m_SelectorMouse.y, -280.0f, 280.0f);\n\n\t// draw selections\n\tfloat FontSize = 20.0f;\n\tfloat StartY = -190.0f;\n\tfloat LineHeight = 60.0f;\n\tbool Selected = false;\n\n\tif(m_pClient->m_aClients[m_pClient->m_LocalClientID].m_Team == TEAM_SPECTATORS)\n\t{\n\t\tif(m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW)\n\t\t{\n\t\t\tGraphics()->TextureClear();\n\t\t\tGraphics()->QuadsBegin();\n\t\t\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 0.25f);\n\t\t\tRenderTools()->DrawRoundRect(Width/2.0f-280.0f, Height/2.0f-280.0f, 270.0f, 60.0f, 20.0f);\n\t\t\tGraphics()->QuadsEnd();\n\t\t}\n\n\t\tif(m_SelectorMouse.x >= -280.0f && m_SelectorMouse.x <= -10.0f &&\n\t\t\tm_SelectorMouse.y >= -280.0f && m_SelectorMouse.y <= -220.0f)\n\t\t{\n\t\t\tm_SelectedSpectatorID = SPEC_FREEVIEW;\n\t\t\tSelected = true;\n\t\t}\n\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, Selected?1.0f:0.5f);\n\t\tTextRender()->Text(0, Width/2.0f-240.0f, Height/2.0f-265.0f, FontSize, Localize(\"Free-View\"), -1);\n\t}\n\n\tfloat x = -270.0f, y = StartY;\n\tfor(int i = 0, Count = 0; i < MAX_CLIENTS; ++i)\n\t{\n\t\tif(!m_pClient->m_Snap.m_paPlayerInfos[i] || m_pClient->m_aClients[i].m_Team == TEAM_SPECTATORS ||\n\t\t\t(m_pClient->m_aClients[m_pClient->m_LocalClientID].m_Team != TEAM_SPECTATORS && (m_pClient->m_Snap.m_paPlayerInfos[i]->m_PlayerFlags&PLAYERFLAG_DEAD ||\n\t\t\tm_pClient->m_aClients[m_pClient->m_LocalClientID].m_Team != m_pClient->m_aClients[i].m_Team || i == m_pClient->m_LocalClientID)))\n\t\t\tcontinue;\n\n\t\tif(++Count%9 == 0)\n\t\t{\n\t\t\tx += 290.0f;\n\t\t\ty = StartY;\n\t\t}\n\n\t\tif(m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == i)\n\t\t{\n\t\t\tGraphics()->TextureClear();\n\t\t\tGraphics()->QuadsBegin();\n\t\t\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 0.25f);\n\t\t\tRenderTools()->DrawRoundRect(Width/2.0f+x-10.0f, Height/2.0f+y-10.0f, 270.0f, 60.0f, 20.0f);\n\t\t\tGraphics()->QuadsEnd();\n\t\t}\n\n\t\tSelected = false;\n\t\tif(m_SelectorMouse.x >= x-10.0f && m_SelectorMouse.x <= x+260.0f &&\n\t\t\tm_SelectorMouse.y >= y-10.0f && m_SelectorMouse.y <= y+50.0f)\n\t\t{\n\t\t\tm_SelectedSpectatorID = i;\n\t\t\tSelected = true;\n\t\t}\n\t\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, Selected?1.0f:0.5f);\n\t\tTextRender()->Text(0, Width/2.0f+x+50.0f, Height/2.0f+y+5.0f, FontSize, m_pClient->m_aClients[i].m_aName, 220.0f);\n\n\t\t// flag\n\t\tif(m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_FLAGS &&\n\t\t\tm_pClient->m_Snap.m_pGameDataFlag && (m_pClient->m_Snap.m_pGameDataFlag->m_FlagCarrierRed == i ||\n\t\t\tm_pClient->m_Snap.m_pGameDataFlag->m_FlagCarrierBlue == i))\n\t\t{\n\t\t\tGraphics()->BlendNormal();\n\t\t\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);\n\t\t\tGraphics()->QuadsBegin();\n\n\t\t\tRenderTools()->SelectSprite(m_pClient->m_aClients[i].m_Team==TEAM_RED ? SPRITE_FLAG_BLUE : SPRITE_FLAG_RED, SPRITE_FLAG_FLIP_X);\n\n\t\t\tfloat Size = LineHeight;\n\t\t\tIGraphics::CQuadItem QuadItem(Width/2.0f+x-LineHeight/5.0f, Height/2.0f+y-LineHeight/3.0f, Size/2.0f, Size);\n\t\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t\t\tGraphics()->QuadsEnd();\n\t\t}\n\n\t\tCTeeRenderInfo TeeInfo = m_pClient->m_aClients[i].m_RenderInfo;\n\t\tRenderTools()->RenderTee(CAnimState::GetIdle(), &TeeInfo, EMOTE_NORMAL, vec2(1.0f, 0.0f), vec2(Width/2.0f+x+20.0f, Height/2.0f+y+20.0f));\n\n\t\ty += LineHeight;\n\t}\n\tTextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f);\n\n\t// draw cursor\n\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_CURSOR].m_Id);\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);\n\tIGraphics::CQuadItem QuadItem(m_SelectorMouse.x+Width/2.0f, m_SelectorMouse.y+Height/2.0f, 48.0f, 48.0f);\n\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n}\n\nvoid CSpectator::OnReset()\n{\n\tm_WasActive = false;\n\tm_Active = false;\n\tm_SelectedSpectatorID = NO_SELECTION;\n}\n\nvoid CSpectator::Spectate(int SpectatorID)\n{\n\tif(Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tm_pClient->m_DemoSpecID = clamp(SpectatorID, (int)SPEC_FREEVIEW, MAX_CLIENTS-1);\n\t\treturn;\n\t}\n\n\tif(m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SpectatorID)\n\t\treturn;\n\n\tCNetMsg_Cl_SetSpectatorMode Msg;\n\tMsg.m_SpectatorID = SpectatorID;\n\tClient()->SendPackMsg(&Msg, MSGFLAG_VITAL);\n}\n"
  },
  {
    "path": "src/game/client/components/spectator.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_SPECTATOR_H\n#define GAME_CLIENT_COMPONENTS_SPECTATOR_H\n#include <base/vmath.h>\n\n#include <game/client/component.h>\n\nclass CSpectator : public CComponent\n{\n\tenum\n\t{\n\t\tNO_SELECTION=-2,\n\t};\n\n\tbool m_Active;\n\tbool m_WasActive;\n\n\tint m_SelectedSpectatorID;\n\tvec2 m_SelectorMouse;\n\n\tstatic void ConKeySpectator(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConSpectate(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConSpectateNext(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConSpectatePrevious(IConsole::IResult *pResult, void *pUserData);\n\npublic:\n\tCSpectator();\n\n\tvirtual void OnConsoleInit();\n\tvirtual bool OnMouseMove(float x, float y);\n\tvirtual void OnRender();\n\tvirtual void OnRelease();\n\tvirtual void OnReset();\n\n\tvoid Spectate(int SpectatorID);\n};\n\n#endif\n"
  },
  {
    "path": "src/game/client/components/voting.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/vmath.h>\n\n#include <engine/shared/config.h>\n\n#include <game/client/render.h>\n#include <game/generated/protocol.h>\n\n#include \"chat.h\"\n#include \"voting.h\"\n\n\nvoid CVoting::ConVote(IConsole::IResult *pResult, void *pUserData)\n{\n\tCVoting *pSelf = (CVoting *)pUserData;\n\tif(str_comp_nocase(pResult->GetString(0), \"yes\") == 0)\n\t\tpSelf->Vote(1);\n\telse if(str_comp_nocase(pResult->GetString(0), \"no\") == 0)\n\t\tpSelf->Vote(-1);\n}\n\nvoid CVoting::Callvote(const char *pType, const char *pValue, const char *pReason, bool ForceVote)\n{\n\tCNetMsg_Cl_CallVote Msg = {0};\n\tMsg.m_Type = pType;\n\tMsg.m_Value = pValue;\n\tMsg.m_Reason = pReason;\n\tMsg.m_Force = ForceVote;\n\tClient()->SendPackMsg(&Msg, MSGFLAG_VITAL);\n}\n\nvoid CVoting::CallvoteSpectate(int ClientID, const char *pReason, bool ForceVote)\n{\n\tchar aBuf[32];\n\tstr_format(aBuf, sizeof(aBuf), \"%d\", ClientID);\n\tCallvote(\"spectate\", aBuf, pReason, ForceVote);\n}\n\nvoid CVoting::CallvoteKick(int ClientID, const char *pReason, bool ForceVote)\n{\n\tchar aBuf[32];\n\tstr_format(aBuf, sizeof(aBuf), \"%d\", ClientID);\n\tCallvote(\"kick\", aBuf, pReason, ForceVote);\n}\n\nvoid CVoting::CallvoteOption(int OptionID, const char *pReason, bool ForceVote)\n{\n\tCVoteOptionClient *pOption = m_pFirst;\n\twhile(pOption && OptionID >= 0)\n\t{\n\t\tif(OptionID == 0)\n\t\t{\n\t\t\tCallvote(\"option\", pOption->m_aDescription, pReason, ForceVote);\n\t\t\tbreak;\n\t\t}\n\n\t\tOptionID--;\n\t\tpOption = pOption->m_pNext;\n\t}\n}\n\nvoid CVoting::RemovevoteOption(int OptionID)\n{\n\tCVoteOptionClient *pOption = m_pFirst;\n\twhile(pOption && OptionID >= 0)\n\t{\n\t\tif(OptionID == 0)\n\t\t{\n\t\t\tchar aBuf[128];\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"remove_vote \\\"%s\\\"\", pOption->m_aDescription);\n\t\t\tClient()->Rcon(aBuf);\n\t\t\tbreak;\n\t\t}\n\n\t\tOptionID--;\n\t\tpOption = pOption->m_pNext;\n\t}\n}\n\nvoid CVoting::AddvoteOption(const char *pDescription, const char *pCommand)\n{\n\tchar aBuf[128];\n\tstr_format(aBuf, sizeof(aBuf), \"add_vote \\\"%s\\\" %s\", pDescription, pCommand);\n\tClient()->Rcon(aBuf);\n}\n\nvoid CVoting::Vote(int v)\n{\n\tCNetMsg_Cl_Vote Msg = {v};\n\tClient()->SendPackMsg(&Msg, MSGFLAG_VITAL);\n}\n\nCVoting::CVoting()\n{\n\tClearOptions();\n\t\n\tm_Closetime = 0;\n\tm_aDescription[0] = 0;\n\tm_aReason[0] = 0;\n\tm_Yes = m_No = m_Pass = m_Total = 0;\n\tm_Voted = 0;\n}\n\nvoid CVoting::AddOption(const char *pDescription)\n{\n\tCVoteOptionClient *pOption;\n\tif(m_pRecycleFirst)\n\t{\n\t\tpOption = m_pRecycleFirst;\n\t\tm_pRecycleFirst = m_pRecycleFirst->m_pNext;\n\t\tif(m_pRecycleFirst)\n\t\t\tm_pRecycleFirst->m_pPrev = 0;\n\t\telse\n\t\t\tm_pRecycleLast = 0;\n\t}\n\telse\n\t\tpOption = (CVoteOptionClient *)m_Heap.Allocate(sizeof(CVoteOptionClient));\n\n\tpOption->m_pNext = 0;\n\tpOption->m_pPrev = m_pLast;\n\tif(pOption->m_pPrev)\n\t\tpOption->m_pPrev->m_pNext = pOption;\n\tm_pLast = pOption;\n\tif(!m_pFirst)\n\t\tm_pFirst = pOption;\n\n\tstr_copy(pOption->m_aDescription, pDescription, sizeof(pOption->m_aDescription));\n\t++m_NumVoteOptions;\n}\n\nvoid CVoting::ClearOptions()\n{\n\tm_Heap.Reset();\n\n\tm_NumVoteOptions = 0;\n\tm_pFirst = 0;\n\tm_pLast = 0;\n\n\tm_pRecycleFirst = 0;\n\tm_pRecycleLast = 0;\n}\n\nvoid CVoting::OnReset()\n{\n\tif(Client()->State() == IClient::STATE_LOADING)\t// do not reset active vote while connecting\n\t\treturn;\n\n\tm_Closetime = 0;\n\tm_aDescription[0] = 0;\n\tm_aReason[0] = 0;\n\tm_Yes = m_No = m_Pass = m_Total = 0;\n\tm_Voted = 0;\n\tm_CallvoteBlockTick = 0;\n}\n\nvoid CVoting::OnConsoleInit()\n{\n\tConsole()->Register(\"vote\", \"r\", CFGFLAG_CLIENT, ConVote, this, \"Vote yes/no\");\n}\n\nvoid CVoting::OnMessage(int MsgType, void *pRawMsg)\n{\n\tif(MsgType == NETMSGTYPE_SV_VOTESET)\n\t{\n\t\tCNetMsg_Sv_VoteSet *pMsg = (CNetMsg_Sv_VoteSet *)pRawMsg;\n\t\tint BlockTick = m_CallvoteBlockTick;\n\t\tchar aBuf[128];\n\t\tif(pMsg->m_Timeout)\n\t\t{\n\t\t\tOnReset();\n\t\t\tstr_copy(m_aDescription, pMsg->m_pDescription, sizeof(m_aDescription));\n\t\t\tstr_copy(m_aReason, pMsg->m_pReason, sizeof(m_aReason));\n\t\t\tm_Closetime = time_get() + time_freq() * pMsg->m_Timeout;\n\t\t\tif(pMsg->m_ClientID != -1)\n\t\t\t{\n\t\t\t\tswitch(pMsg->m_Type)\n\t\t\t\t{\n\t\t\t\tcase VOTE_START_OP:\n\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"'%s' called vote to change server option '%s' (%s)\"), m_pClient->m_aClients[pMsg->m_ClientID].m_aName, \n\t\t\t\t\t\t\t\tpMsg->m_pDescription, pMsg->m_pReason);\n\t\t\t\t\tm_pClient->m_pChat->AddLine(-1, 0, aBuf);\n\t\t\t\t\tbreak;\n\t\t\t\tcase VOTE_START_KICK:\n\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"'%s' called for vote to kick '%s' (%s)\"), m_pClient->m_aClients[pMsg->m_ClientID].m_aName, \n\t\t\t\t\t\t\t\tpMsg->m_pDescription, pMsg->m_pReason);\n\t\t\t\t\tm_pClient->m_pChat->AddLine(-1, 0, aBuf);\n\t\t\t\t\tbreak;\n\t\t\t\tcase VOTE_START_SPEC:\n\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"'%s' called for vote to move '%s' to spectators (%s)\"), m_pClient->m_aClients[pMsg->m_ClientID].m_aName, \n\t\t\t\t\t\t\t\tpMsg->m_pDescription, pMsg->m_pReason);\n\t\t\t\t\tm_pClient->m_pChat->AddLine(-1, 0, aBuf);\n\t\t\t\t}\n\t\t\t\tif(pMsg->m_ClientID == m_pClient->m_LocalClientID)\n\t\t\t\t\tm_CallvoteBlockTick = Client()->GameTick()+Client()->GameTickSpeed()*VOTE_COOLDOWN;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tswitch(pMsg->m_Type)\n\t\t\t{\n\t\t\tcase VOTE_START_OP:\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"Admin forced server option '%s' (%s)\"), pMsg->m_pDescription, pMsg->m_pReason);\n\t\t\t\tm_pClient->m_pChat->AddLine(-1, 0, aBuf);\n\t\t\t\tbreak;\n\t\t\tcase VOTE_START_SPEC:\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"Admin moved '%s' to spectator (%s)\"), pMsg->m_pDescription, pMsg->m_pReason);\n\t\t\t\tm_pClient->m_pChat->AddLine(-1, 0, aBuf);\n\t\t\t\tbreak;\n\t\t\tcase VOTE_END_ABORT:\n\t\t\t\tOnReset();\n\t\t\t\tm_pClient->m_pChat->AddLine(-1, 0, Localize(\"Vote aborted\"));\n\t\t\t\tbreak;\n\t\t\tcase VOTE_END_PASS:\n\t\t\t\tOnReset();\n\t\t\t\tif(pMsg->m_ClientID == -1)\n\t\t\t\t\tm_pClient->m_pChat->AddLine(-1, 0, Localize(\"Admin forced vote yes\"));\n\t\t\t\telse\n\t\t\t\t\tm_pClient->m_pChat->AddLine(-1, 0, Localize(\"Vote passed\"));\n\t\t\t\tbreak;\n\t\t\tcase  VOTE_END_FAIL:\n\t\t\t\tOnReset();\n\t\t\t\tif(pMsg->m_ClientID == -1)\n\t\t\t\t\tm_pClient->m_pChat->AddLine(-1, 0, Localize(\"Admin forced vote no\"));\n\t\t\t\telse\n\t\t\t\t\tm_pClient->m_pChat->AddLine(-1, 0, Localize(\"Vote failed\"));\n\t\t\t\tm_CallvoteBlockTick = BlockTick;\n\t\t\t}\n\t\t}\n\t}\n\telse if(MsgType == NETMSGTYPE_SV_VOTESTATUS)\n\t{\n\t\tCNetMsg_Sv_VoteStatus *pMsg = (CNetMsg_Sv_VoteStatus *)pRawMsg;\n\t\tm_Yes = pMsg->m_Yes;\n\t\tm_No = pMsg->m_No;\n\t\tm_Pass = pMsg->m_Pass;\n\t\tm_Total = pMsg->m_Total;\n\t}\n\telse if(MsgType == NETMSGTYPE_SV_VOTECLEAROPTIONS)\n\t{\n\t\tClearOptions();\n\t}\n\telse if(MsgType == NETMSGTYPE_SV_VOTEOPTIONADD)\n\t{\n\t\tCNetMsg_Sv_VoteOptionAdd *pMsg = (CNetMsg_Sv_VoteOptionAdd *)pRawMsg;\n\t\tAddOption(pMsg->m_pDescription);\n\t}\n\telse if(MsgType == NETMSGTYPE_SV_VOTEOPTIONREMOVE)\n\t{\n\t\tCNetMsg_Sv_VoteOptionRemove *pMsg = (CNetMsg_Sv_VoteOptionRemove *)pRawMsg;\n\n\t\tfor(CVoteOptionClient *pOption = m_pFirst; pOption; pOption = pOption->m_pNext)\n\t\t{\n\t\t\tif(str_comp(pOption->m_aDescription, pMsg->m_pDescription) == 0)\n\t\t\t{\n\t\t\t\t// remove it from the list\n\t\t\t\tif(m_pFirst == pOption)\n\t\t\t\t\tm_pFirst = m_pFirst->m_pNext;\n\t\t\t\tif(m_pLast == pOption)\n\t\t\t\t\tm_pLast = m_pLast->m_pPrev;\n\t\t\t\tif(pOption->m_pPrev)\n\t\t\t\t\tpOption->m_pPrev->m_pNext = pOption->m_pNext;\n\t\t\t\tif(pOption->m_pNext)\n\t\t\t\t\tpOption->m_pNext->m_pPrev = pOption->m_pPrev;\n\t\t\t\t--m_NumVoteOptions;\n\n\t\t\t\t// add it to recycle list\n\t\t\t\tpOption->m_pNext = 0;\n\t\t\t\tpOption->m_pPrev = m_pRecycleLast;\n\t\t\t\tif(pOption->m_pPrev)\n\t\t\t\t\tpOption->m_pPrev->m_pNext = pOption;\n\t\t\t\tm_pRecycleLast = pOption;\n\t\t\t\tif(!m_pRecycleFirst)\n\t\t\t\t\tm_pRecycleLast = pOption;\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid CVoting::OnRender()\n{\n}\n\n\nvoid CVoting::RenderBars(CUIRect Bars, bool Text)\n{\n\tRenderTools()->DrawUIRect(&Bars, vec4(0.8f,0.8f,0.8f,0.5f), CUI::CORNER_ALL, Bars.h/3);\n\n\tCUIRect Splitter = Bars;\n\tSplitter.x = Splitter.x+Splitter.w/2;\n\tSplitter.w = Splitter.h/2.0f;\n\tSplitter.x -= Splitter.w/2;\n\tRenderTools()->DrawUIRect(&Splitter, vec4(0.4f,0.4f,0.4f,0.5f), CUI::CORNER_ALL, Splitter.h/4);\n\n\tif(m_Total)\n\t{\n\t\tCUIRect PassArea = Bars;\n\t\tif(m_Yes)\n\t\t{\n\t\t\tCUIRect YesArea = Bars;\n\t\t\tYesArea.w *= m_Yes/(float)m_Total;\n\t\t\tRenderTools()->DrawUIRect(&YesArea, vec4(0.2f,0.9f,0.2f,0.85f), CUI::CORNER_ALL, Bars.h/3);\n\n\t\t\tif(Text)\n\t\t\t{\n\t\t\t\tchar Buf[256];\n\t\t\t\tstr_format(Buf, sizeof(Buf), \"%d\", m_Yes);\n\t\t\t\tUI()->DoLabel(&YesArea, Buf, Bars.h*0.75f, 0);\n\t\t\t}\n\n\t\t\tPassArea.x += YesArea.w;\n\t\t\tPassArea.w -= YesArea.w;\n\t\t}\n\n\t\tif(m_No)\n\t\t{\n\t\t\tCUIRect NoArea = Bars;\n\t\t\tNoArea.w *= m_No/(float)m_Total;\n\t\t\tNoArea.x = (Bars.x + Bars.w)-NoArea.w;\n\t\t\tRenderTools()->DrawUIRect(&NoArea, vec4(0.9f,0.2f,0.2f,0.85f), CUI::CORNER_ALL, Bars.h/3);\n\n\t\t\tif(Text)\n\t\t\t{\n\t\t\t\tchar Buf[256];\n\t\t\t\tstr_format(Buf, sizeof(Buf), \"%d\", m_No);\n\t\t\t\tUI()->DoLabel(&NoArea, Buf, Bars.h*0.75f, 0);\n\t\t\t}\n\n\t\t\tPassArea.w -= NoArea.w;\n\t\t}\n\n\t\tif(Text && m_Pass)\n\t\t{\n\t\t\tchar Buf[256];\n\t\t\tstr_format(Buf, sizeof(Buf), \"%d\", m_Pass);\n\t\t\tUI()->DoLabel(&PassArea, Buf, Bars.h*0.75f, 0);\n\t\t}\n\t}\n}\n\n\n"
  },
  {
    "path": "src/game/client/components/voting.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_COMPONENTS_VOTING_H\n#define GAME_CLIENT_COMPONENTS_VOTING_H\n\n#include <engine/shared/memheap.h>\n\n#include <game/voting.h>\n#include <game/client/component.h>\n#include <game/client/ui.h>\n\nclass CVoting : public CComponent\n{\n\tCHeap m_Heap;\n\n\tstatic void ConVote(IConsole::IResult *pResult, void *pUserData);\n\n\tint64 m_Closetime;\n\tchar m_aDescription[VOTE_DESC_LENGTH];\n\tchar m_aReason[VOTE_REASON_LENGTH];\n\tint m_Voted;\n\tint m_Yes, m_No, m_Pass, m_Total;\n\tint m_CallvoteBlockTick;\n\n\tvoid ClearOptions();\n\tvoid Callvote(const char *pType, const char *pValue, const char *pReason, bool ForceVote);\n\npublic:\n\tint m_NumVoteOptions;\n\tCVoteOptionClient *m_pFirst;\n\tCVoteOptionClient *m_pLast;\n\n\tCVoteOptionClient *m_pRecycleFirst;\n\tCVoteOptionClient *m_pRecycleLast;\n\n\tCVoting();\n\tvirtual void OnReset();\n\tvirtual void OnConsoleInit();\n\tvirtual void OnMessage(int Msgtype, void *pRawMsg);\n\tvirtual void OnRender();\n\n\tvoid RenderBars(CUIRect Bars, bool Text);\n\n\tvoid CallvoteSpectate(int ClientID, const char *pReason, bool ForceVote = false);\n\tvoid CallvoteKick(int ClientID, const char *pReason, bool ForceVote = false);\n\tvoid CallvoteOption(int OptionID, const char *pReason, bool ForceVote = false);\n\tvoid AddOption(const char *pDescription);\n\tvoid RemovevoteOption(int OptionID);\n\tvoid AddvoteOption(const char *pDescription, const char *pCommand);\n\n\tvoid Vote(int v); // -1 = no, 1 = yes\n\n\tint SecondsLeft() { return (m_Closetime - time_get())/time_freq(); }\n\tbool IsVoting() { return m_Closetime != 0; }\n\tint TakenChoice() const { return m_Voted; }\n\tconst char *VoteDescription() const { return m_aDescription; }\n\tconst char *VoteReason() const { return m_aReason; }\n\tint CallvoteBlockTime() const { return m_CallvoteBlockTick > Client()->GameTick() ? (m_CallvoteBlockTick-Client()->GameTick())/Client()->GameTickSpeed() : 0; }\n};\n\n#endif\n"
  },
  {
    "path": "src/game/client/gameclient.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/editor.h>\n#include <engine/engine.h>\n#include <engine/friends.h>\n#include <engine/graphics.h>\n#include <engine/textrender.h>\n#include <engine/demo.h>\n#include <engine/map.h>\n#include <engine/storage.h>\n#include <engine/sound.h>\n#include <engine/serverbrowser.h>\n#include <engine/shared/demo.h>\n#include <engine/shared/config.h>\n\n#include <game/generated/protocol.h>\n#include <game/generated/client_data.h>\n\n#include <game/version.h>\n#include \"localization.h\"\n#include \"render.h\"\n\n#include \"gameclient.h\"\n\n#include \"components/binds.h\"\n#include \"components/broadcast.h\"\n#include \"components/camera.h\"\n#include \"components/chat.h\"\n#include \"components/console.h\"\n#include \"components/controls.h\"\n#include \"components/countryflags.h\"\n#include \"components/damageind.h\"\n#include \"components/debughud.h\"\n#include \"components/effects.h\"\n#include \"components/emoticon.h\"\n#include \"components/flow.h\"\n#include \"components/hud.h\"\n#include \"components/items.h\"\n#include \"components/killmessages.h\"\n#include \"components/mapimages.h\"\n#include \"components/maplayers.h\"\n#include \"components/menus.h\"\n#include \"components/motd.h\"\n#include \"components/particles.h\"\n#include \"components/players.h\"\n#include \"components/nameplates.h\"\n#include \"components/scoreboard.h\"\n#include \"components/skins.h\"\n#include \"components/sounds.h\"\n#include \"components/spectator.h\"\n#include \"components/voting.h\"\n\n// instanciate all systems\nstatic CKillMessages gs_KillMessages;\nstatic CCamera gs_Camera;\nstatic CChat gs_Chat;\nstatic CMotd gs_Motd;\nstatic CBroadcast gs_Broadcast;\nstatic CGameConsole gs_GameConsole;\nstatic CBinds gs_Binds;\nstatic CParticles gs_Particles;\nstatic CMenus gs_Menus;\nstatic CSkins gs_Skins;\nstatic CCountryFlags gs_CountryFlags;\nstatic CFlow gs_Flow;\nstatic CHud gs_Hud;\nstatic CDebugHud gs_DebugHud;\nstatic CControls gs_Controls;\nstatic CEffects gs_Effects;\nstatic CScoreboard gs_Scoreboard;\nstatic CSounds gs_Sounds;\nstatic CEmoticon gs_Emoticon;\nstatic CDamageInd gsDamageInd;\nstatic CVoting gs_Voting;\nstatic CSpectator gs_Spectator;\n\nstatic CPlayers gs_Players;\nstatic CNamePlates gs_NamePlates;\nstatic CItems gs_Items;\nstatic CMapImages gs_MapImages;\n\nstatic CMapLayers gs_MapLayersBackGround(CMapLayers::TYPE_BACKGROUND);\nstatic CMapLayers gs_MapLayersForeGround(CMapLayers::TYPE_FOREGROUND);\n\nCGameClient::CStack::CStack() { m_Num = 0; }\nvoid CGameClient::CStack::Add(class CComponent *pComponent) { m_paComponents[m_Num++] = pComponent; }\n\nconst char *CGameClient::Version() { return GAME_VERSION; }\nconst char *CGameClient::NetVersion() { return GAME_NETVERSION; }\nconst char *CGameClient::GetItemName(int Type) { return m_NetObjHandler.GetObjName(Type); }\n\nconst char *CGameClient::GetTeamName(int Team, bool Teamplay) const\n{\n\tif(Teamplay)\n\t{\n\t\tif(Team == TEAM_RED)\n\t\t\treturn Localize(\"red team\");\n\t\telse if(Team == TEAM_BLUE)\n\t\t\treturn Localize(\"blue team\");\n\t}\n\telse if(Team == 0)\n\t\treturn Localize(\"game\");\n\n\treturn Localize(\"spectators\");\n}\n\nenum\n{\n\tDO_CHAT=0,\n\tDO_BROADCAST,\n\tDO_SPECIAL,\n\n\tPARA_NONE=0,\n\tPARA_I,\n\tPARA_II,\n\tPARA_III,\n};\n\nstruct CGameMsg\n{\n\tint m_Action;\n\tint m_ParaType;\n\tconst char *m_pText;\n};\n\nstatic CGameMsg gs_GameMsgList[NUM_GAMEMSGS] = {\n\t{/*GAMEMSG_TEAM_SWAP*/ DO_CHAT, PARA_NONE, \"Teams were swapped\"},\n\t{/*GAMEMSG_SPEC_INVALIDID*/ DO_CHAT, PARA_NONE, \"Invalid spectator id used\"},\t//!\n\t{/*GAMEMSG_TEAM_SHUFFLE*/ DO_CHAT, PARA_NONE, \"Teams were shuffled\"},\n\t{/*GAMEMSG_TEAM_BALANCE*/ DO_CHAT, PARA_NONE, \"Teams have been balanced\"},\n\t{/*GAMEMSG_CTF_DROP*/ DO_SPECIAL, PARA_NONE, \"\"},\t// special - play ctf drop sound\n\t{/*GAMEMSG_CTF_RETURN*/ DO_SPECIAL, PARA_NONE, \"\"},\t// special - play ctf return sound\n\n\t{/*GAMEMSG_TEAM_ALL*/ DO_SPECIAL, PARA_I, \"All players were moved to the %s\"},\t// special - add team name\n\t{/*GAMEMSG_TEAM_BALANCE_VICTIM*/ DO_SPECIAL, PARA_I, \"You were moved to %s due to team balancing\"},\t// special - add team name\n\t{/*GAMEMSG_CTF_GRAB*/ DO_SPECIAL, PARA_I, \"\"},\t// special - play ctf grab sound based on team\n\n\t{/*GAMEMSG_CTF_CAPTURE*/ DO_SPECIAL, PARA_III, \"\"},\t// special - play ctf capture sound + capture chat message\n};\n\nvoid CGameClient::OnConsoleInit()\n{\n\tm_pEngine = Kernel()->RequestInterface<IEngine>();\n\tm_pClient = Kernel()->RequestInterface<IClient>();\n\tm_pTextRender = Kernel()->RequestInterface<ITextRender>();\n\tm_pSound = Kernel()->RequestInterface<ISound>();\n\tm_pInput = Kernel()->RequestInterface<IInput>();\n\tm_pConsole = Kernel()->RequestInterface<IConsole>();\n\tm_pStorage = Kernel()->RequestInterface<IStorage>();\n\tm_pDemoPlayer = Kernel()->RequestInterface<IDemoPlayer>();\n\tm_pDemoRecorder = Kernel()->RequestInterface<IDemoRecorder>();\n\tm_pServerBrowser = Kernel()->RequestInterface<IServerBrowser>();\n\tm_pEditor = Kernel()->RequestInterface<IEditor>();\n\tm_pFriends = Kernel()->RequestInterface<IFriends>();\n\n\t// setup pointers\n\tm_pBinds = &::gs_Binds;\n\tm_pBroadcast = &::gs_Broadcast;\n\tm_pGameConsole = &::gs_GameConsole;\n\tm_pParticles = &::gs_Particles;\n\tm_pMenus = &::gs_Menus;\n\tm_pSkins = &::gs_Skins;\n\tm_pCountryFlags = &::gs_CountryFlags;\n\tm_pChat = &::gs_Chat;\n\tm_pFlow = &::gs_Flow;\n\tm_pCamera = &::gs_Camera;\n\tm_pControls = &::gs_Controls;\n\tm_pEffects = &::gs_Effects;\n\tm_pSounds = &::gs_Sounds;\n\tm_pMotd = &::gs_Motd;\n\tm_pDamageind = &::gsDamageInd;\n\tm_pMapimages = &::gs_MapImages;\n\tm_pVoting = &::gs_Voting;\n\tm_pScoreboard = &::gs_Scoreboard;\n\tm_pItems = &::gs_Items;\n\tm_pMapLayersBackGround = &::gs_MapLayersBackGround;\n\tm_pMapLayersForeGround = &::gs_MapLayersForeGround;\n\n\t// make a list of all the systems, make sure to add them in the corrent render order\n\tm_All.Add(m_pSkins);\n\tm_All.Add(m_pCountryFlags);\n\tm_All.Add(m_pMapimages);\n\tm_All.Add(m_pEffects); // doesn't render anything, just updates effects\n\tm_All.Add(m_pParticles); // doesn't render anything, just updates all the particles\n\tm_All.Add(m_pBinds);\n\tm_All.Add(m_pControls);\n\tm_All.Add(m_pCamera);\n\tm_All.Add(m_pSounds);\n\tm_All.Add(m_pVoting);\n\n\tm_All.Add(&gs_MapLayersBackGround); // first to render\n\tm_All.Add(&m_pParticles->m_RenderTrail);\n\tm_All.Add(m_pItems);\n\tm_All.Add(&gs_Players);\n\tm_All.Add(&gs_MapLayersForeGround);\n\tm_All.Add(&m_pParticles->m_RenderExplosions);\n\tm_All.Add(&gs_NamePlates);\n\tm_All.Add(&m_pParticles->m_RenderGeneral);\n\tm_All.Add(m_pDamageind);\n\tm_All.Add(&gs_Hud);\n\tm_All.Add(&gs_Spectator);\n\tm_All.Add(&gs_Emoticon);\n\tm_All.Add(&gs_KillMessages);\n\tm_All.Add(m_pChat);\n\tm_All.Add(&gs_Broadcast);\n\tm_All.Add(&gs_DebugHud);\n\tm_All.Add(&gs_Scoreboard);\n\tm_All.Add(m_pMotd);\n\tm_All.Add(m_pMenus);\n\tm_All.Add(m_pGameConsole);\n\n\t// build the input stack\n\tm_Input.Add(&m_pMenus->m_Binder); // this will take over all input when we want to bind a key\n\tm_Input.Add(&m_pBinds->m_SpecialBinds);\n\tm_Input.Add(m_pGameConsole);\n\tm_Input.Add(m_pChat); // chat has higher prio due to tha you can quit it by pressing esc\n\tm_Input.Add(m_pMotd); // for pressing esc to remove it\n\tm_Input.Add(m_pMenus);\n\tm_Input.Add(&gs_Spectator);\n\tm_Input.Add(&gs_Emoticon);\n\tm_Input.Add(m_pControls);\n\tm_Input.Add(m_pBinds);\n\n\t// add the some console commands\n\tConsole()->Register(\"kill\", \"\", CFGFLAG_CLIENT, ConKill, this, \"Kill yourself\");\n\tConsole()->Register(\"ready_change\", \"\", CFGFLAG_CLIENT, ConReadyChange, this, \"Change ready state\");\n\n\tConsole()->Chain(\"add_friend\", ConchainFriendUpdate, this);\n\tConsole()->Chain(\"remove_friend\", ConchainFriendUpdate, this);\n\n\tfor(int i = 0; i < m_All.m_Num; i++)\n\t\tm_All.m_paComponents[i]->m_pClient = this;\n\n\t// let all the other components register their console commands\n\tfor(int i = 0; i < m_All.m_Num; i++)\n\t\tm_All.m_paComponents[i]->OnConsoleInit();\n\n\t//\n\tm_SuppressEvents = false;\n}\n\nvoid CGameClient::OnInit()\n{\n\tm_pGraphics = Kernel()->RequestInterface<IGraphics>();\n\n\t// propagate pointers\n\tm_UI.SetGraphics(Graphics(), TextRender());\n\tm_RenderTools.m_pGraphics = Graphics();\n\tm_RenderTools.m_pUI = UI();\n\t\n\tint64 Start = time_get();\n\n\t// set the language\n\tg_Localization.Load(g_Config.m_ClLanguagefile, Storage(), Console());\n\n\t// TODO: this should be different\n\t// setup item sizes\n\tfor(int i = 0; i < NUM_NETOBJTYPES; i++)\n\t\tClient()->SnapSetStaticsize(i, m_NetObjHandler.GetObjSize(i));\n\n\t// load default font\n\tstatic CFont *pDefaultFont = 0;\n\tchar aFontName[256];\n\tstr_format(aFontName, sizeof(aFontName), \"fonts/%s\", g_Config.m_ClFontfile);\n\tchar aFilename[512];\n\tIOHANDLE File = Storage()->OpenFile(aFontName, IOFLAG_READ, IStorage::TYPE_ALL, aFilename, sizeof(aFilename));\n\tif(File)\n\t{\n\t\tio_close(File);\n\t\tpDefaultFont = TextRender()->LoadFont(aFilename);\n\t\tTextRender()->SetDefaultFont(pDefaultFont);\n\t}\n\tif(!pDefaultFont)\n\t{\n\t\tchar aBuf[256];\n\t\tstr_format(aBuf, sizeof(aBuf), \"failed to load font. filename='%s'\", aFontName);\n\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"gameclient\", aBuf);\n\t}\n\n\t// init all components\n\tfor(int i = m_All.m_Num-1; i >= 0; --i)\n\t\tm_All.m_paComponents[i]->OnInit();\n\n\t// setup load amount// load textures\n\tfor(int i = 0; i < g_pData->m_NumImages; i++)\n\t{\n\t\tg_pData->m_aImages[i].m_Id = Graphics()->LoadTexture(g_pData->m_aImages[i].m_pFilename, IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0);\n\t\tm_pMenus->RenderLoading();\n\t}\n\n\tOnReset();\n\n\tint64 End = time_get();\n\tchar aBuf[256];\n\tstr_format(aBuf, sizeof(aBuf), \"initialisation finished after %.2fms\", ((End-Start)*1000)/(float)time_freq());\n\tConsole()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"gameclient\", aBuf);\n\n\tm_ServerMode = SERVERMODE_PURE;\n}\n\nvoid CGameClient::DispatchInput()\n{\n\t// handle mouse movement\n\tfloat x = 0.0f, y = 0.0f;\n\tInput()->MouseRelative(&x, &y);\n\tif(x != 0.0f || y != 0.0f)\n\t{\n\t\tfor(int h = 0; h < m_Input.m_Num; h++)\n\t\t{\n\t\t\tif(m_Input.m_paComponents[h]->OnMouseMove(x, y))\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t// handle key presses\n\tfor(int i = 0; i < Input()->NumEvents(); i++)\n\t{\n\t\tIInput::CEvent e = Input()->GetEvent(i);\n\n\t\tfor(int h = 0; h < m_Input.m_Num; h++)\n\t\t{\n\t\t\tif(m_Input.m_paComponents[h]->OnInput(e))\n\t\t\t{\n\t\t\t\t//dbg_msg(\"\", \"%d char=%d key=%d flags=%d\", h, e.ch, e.key, e.flags);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t// clear all events for this frame\n\tInput()->ClearEvents();\n}\n\n\nint CGameClient::OnSnapInput(int *pData)\n{\n\treturn m_pControls->SnapInput(pData);\n}\n\nvoid CGameClient::OnConnected()\n{\n\tm_Layers.Init(Kernel());\n\tm_Collision.Init(Layers());\n\n\tRenderTools()->RenderTilemapGenerateSkip(Layers());\n\n\tfor(int i = 0; i < m_All.m_Num; i++)\n\t{\n\t\tm_All.m_paComponents[i]->OnMapLoad();\n\t\tm_All.m_paComponents[i]->OnReset();\n\t}\n\n\tm_ServerMode = SERVERMODE_PURE;\n\n\t// send the inital info\n\tSendStartInfo();\n}\n\nvoid CGameClient::OnReset()\n{\n\t// clear out the invalid pointers\n\tm_LastNewPredictedTick = -1;\n\tmem_zero(&m_Snap, sizeof(m_Snap));\n\n\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t\tm_aClients[i].Reset(this);\n\n\tfor(int i = 0; i < m_All.m_Num; i++)\n\t\tm_All.m_paComponents[i]->OnReset();\n\n\tm_LocalClientID = -1;\n\tm_TeamCooldownTick = 0;\n\tmem_zero(&m_GameInfo, sizeof(m_GameInfo));\n\tm_DemoSpecID = SPEC_FREEVIEW;\n\tm_Tuning = CTuningParams();\n}\n\n\nvoid CGameClient::UpdatePositions()\n{\n\t// local character position\n\tif(g_Config.m_ClPredict && Client()->State() != IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tif(!m_Snap.m_pLocalCharacter ||\n\t\t\t(m_Snap.m_pGameData && m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_PAUSED|GAMESTATEFLAG_ROUNDOVER|GAMESTATEFLAG_GAMEOVER)))\n\t\t{\n\t\t\t// don't use predicted\n\t\t}\n\t\telse\n\t\t\tm_LocalCharacterPos = mix(m_PredictedPrevChar.m_Pos, m_PredictedChar.m_Pos, Client()->PredIntraGameTick());\n\t}\n\telse if(m_Snap.m_pLocalCharacter && m_Snap.m_pLocalPrevCharacter)\n\t{\n\t\tm_LocalCharacterPos = mix(\n\t\t\tvec2(m_Snap.m_pLocalPrevCharacter->m_X, m_Snap.m_pLocalPrevCharacter->m_Y),\n\t\t\tvec2(m_Snap.m_pLocalCharacter->m_X, m_Snap.m_pLocalCharacter->m_Y), Client()->IntraGameTick());\n\t}\n\n\t// spectator position\n\tif(m_Snap.m_SpecInfo.m_Active)\n\t{\n\t\tif(Client()->State() == IClient::STATE_DEMOPLAYBACK && DemoPlayer()->GetDemoType() == IDemoPlayer::DEMOTYPE_SERVER &&\n\t\t\tm_Snap.m_SpecInfo.m_SpectatorID != SPEC_FREEVIEW)\n\t\t{\n\t\t\tm_Snap.m_SpecInfo.m_Position = mix(\n\t\t\t\tvec2(m_Snap.m_aCharacters[m_Snap.m_SpecInfo.m_SpectatorID].m_Prev.m_X, m_Snap.m_aCharacters[m_Snap.m_SpecInfo.m_SpectatorID].m_Prev.m_Y),\n\t\t\t\tvec2(m_Snap.m_aCharacters[m_Snap.m_SpecInfo.m_SpectatorID].m_Cur.m_X, m_Snap.m_aCharacters[m_Snap.m_SpecInfo.m_SpectatorID].m_Cur.m_Y),\n\t\t\t\tClient()->IntraGameTick());\n\t\t\tm_Snap.m_SpecInfo.m_UsePosition = true;\n\t\t}\n\t\telse if(m_Snap.m_pSpectatorInfo && (Client()->State() == IClient::STATE_DEMOPLAYBACK || m_Snap.m_SpecInfo.m_SpectatorID != SPEC_FREEVIEW))\n\t\t{\n\t\t\tif(m_Snap.m_pPrevSpectatorInfo)\n\t\t\t\tm_Snap.m_SpecInfo.m_Position = mix(vec2(m_Snap.m_pPrevSpectatorInfo->m_X, m_Snap.m_pPrevSpectatorInfo->m_Y),\n\t\t\t\t\t\t\t\t\t\t\t\t\tvec2(m_Snap.m_pSpectatorInfo->m_X, m_Snap.m_pSpectatorInfo->m_Y), Client()->IntraGameTick());\n\t\t\telse\n\t\t\t\tm_Snap.m_SpecInfo.m_Position = vec2(m_Snap.m_pSpectatorInfo->m_X, m_Snap.m_pSpectatorInfo->m_Y);\n\t\t\tm_Snap.m_SpecInfo.m_UsePosition = true;\n\t\t}\n\t}\n}\n\n\nvoid CGameClient::EvolveCharacter(CNetObj_Character *pCharacter, int Tick)\n{\n\tCWorldCore TempWorld;\n\tCCharacterCore TempCore;\n\tmem_zero(&TempCore, sizeof(TempCore));\n\tTempCore.Init(&TempWorld, Collision());\n\tTempCore.Read(pCharacter);\n\n\twhile(pCharacter->m_Tick < Tick)\n\t{\n\t\tpCharacter->m_Tick++;\n\t\tTempCore.Tick(false);\n\t\tTempCore.Move();\n\t\tTempCore.Quantize();\n\t}\n\n\tTempCore.Write(pCharacter);\n}\n\n\nvoid CGameClient::OnRender()\n{\n\t/*Graphics()->Clear(1,0,0);\n\n\tmenus->render_background();\n\treturn;*/\n\t/*\n\tGraphics()->Clear(1,0,0);\n\tGraphics()->MapScreen(0,0,100,100);\n\n\tGraphics()->QuadsBegin();\n\t\tGraphics()->SetColor(1,1,1,1);\n\t\tGraphics()->QuadsDraw(50, 50, 30, 30);\n\tGraphics()->QuadsEnd();\n\n\treturn;*/\n\n\t// update the local character and spectate position\n\tUpdatePositions();\n\n\t// dispatch all input to systems\n\tDispatchInput();\n\n\t// render all systems\n\tfor(int i = 0; i < m_All.m_Num; i++)\n\t\tm_All.m_paComponents[i]->OnRender();\n}\n\nvoid CGameClient::OnRelease()\n{\n\t// release all systems\n\tfor(int i = 0; i < m_All.m_Num; i++)\n\t\tm_All.m_paComponents[i]->OnRelease();\n}\n\nvoid CGameClient::OnMessage(int MsgId, CUnpacker *pUnpacker)\n{\n\tClient()->RecordGameMessage(true);\n\n\t// special messages\n\tif(MsgId == NETMSGTYPE_SV_EXTRAPROJECTILE)\n\t{\n\t\tint Num = pUnpacker->GetInt();\n\n\t\tfor(int k = 0; k < Num; k++)\n\t\t{\n\t\t\tCNetObj_Projectile Proj;\n\t\t\tfor(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++)\n\t\t\t\t((int *)&Proj)[i] = pUnpacker->GetInt();\n\n\t\t\tif(pUnpacker->Error())\n\t\t\t\treturn;\n\n\t\t\tm_pItems->AddExtraProjectile(&Proj);\n\t\t}\n\n\t\treturn;\n\t}\n\telse if(MsgId == NETMSGTYPE_SV_TUNEPARAMS && Client()->State() != IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tClient()->RecordGameMessage(false);\n\t\t// unpack the new tuning\n\t\tCTuningParams NewTuning;\n\t\tint *pParams = (int *)&NewTuning;\n\t\tfor(unsigned i = 0; i < sizeof(CTuningParams)/sizeof(int); i++)\n\t\t\tpParams[i] = pUnpacker->GetInt();\n\n\t\t// check for unpacking errors\n\t\tif(pUnpacker->Error())\n\t\t\treturn;\n\n\t\tm_ServerMode = SERVERMODE_PURE;\n\n\t\t// apply new tuning\n\t\tm_Tuning = NewTuning;\n\t\treturn;\n\t}\n\telse if(MsgId == NETMSGTYPE_SV_VOTEOPTIONLISTADD)\n\t{\n\t\tint NumOptions = pUnpacker->GetInt();\n\t\tfor(int i = 0; i < NumOptions; i++)\n\t\t{\n\t\t\tconst char *pDescription = pUnpacker->GetString(CUnpacker::SANITIZE_CC);\n\t\t\tif(pUnpacker->Error())\n\t\t\t\treturn;\n\n\t\t\tm_pVoting->AddOption(pDescription);\n\t\t}\n\t}\n\telse if(MsgId == NETMSGTYPE_SV_GAMEMSG)\n\t{\n\t\tint GameMsgID = pUnpacker->GetInt();\n\n\t\tint aParaI[3];\n\t\tint NumParaI = 0;\n\n\t\t// get paras\n\t\tswitch(gs_GameMsgList[GameMsgID].m_ParaType)\n\t\t{\n\t\tcase PARA_III:\n\t\t\taParaI[NumParaI++] = pUnpacker->GetInt();\n\t\tcase PARA_II:\n\t\t\taParaI[NumParaI++] = pUnpacker->GetInt();\n\t\tcase PARA_I:\n\t\t\taParaI[NumParaI++] = pUnpacker->GetInt();\n\t\t}\n\n\t\t// check for unpacking errors\n\t\tif(pUnpacker->Error())\n\t\t\treturn;\n\n\t\t// handle special messages\n\t\tstatic char aBuf[256];\n\t\tif(gs_GameMsgList[GameMsgID].m_Action == DO_SPECIAL)\n\t\t{\n\t\t\tswitch(GameMsgID)\n\t\t\t{\n\t\t\tcase GAMEMSG_CTF_DROP:\n\t\t\t\tif(m_SuppressEvents)\n\t\t\t\t\treturn;\n\t\t\t\tm_pSounds->Enqueue(CSounds::CHN_GLOBAL, SOUND_CTF_DROP);\n\t\t\t\tbreak;\n\t\t\tcase GAMEMSG_CTF_RETURN:\n\t\t\t\tif(m_SuppressEvents)\n\t\t\t\t\treturn;\n\t\t\t\tm_pSounds->Enqueue(CSounds::CHN_GLOBAL, SOUND_CTF_RETURN);\n\t\t\t\tbreak;\n\t\t\tcase GAMEMSG_TEAM_BALANCE_VICTIM:\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), Localize(gs_GameMsgList[GameMsgID].m_pText), GetTeamName(aParaI[0], m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS));\n\t\t\t\tm_pBroadcast->DoBroadcast(aBuf);\n\t\t\t\tbreak;\n\t\t\tcase GAMEMSG_CTF_GRAB:\n\t\t\t\tif(m_SuppressEvents)\n\t\t\t\t\treturn;\n\t\t\t\tif(m_LocalClientID != -1 && (m_aClients[m_LocalClientID].m_Team != aParaI[0] ||\n\t\t\t\t\t(m_Snap.m_SpecInfo.m_Active && m_Snap.m_SpecInfo.m_SpectatorID != -1 && m_aClients[m_Snap.m_SpecInfo.m_SpectatorID].m_Team != aParaI[0])))\n\t\t\t\t\tm_pSounds->Enqueue(CSounds::CHN_GLOBAL, SOUND_CTF_GRAB_PL);\n\t\t\t\telse\n\t\t\t\t\tm_pSounds->Enqueue(CSounds::CHN_GLOBAL, SOUND_CTF_GRAB_EN);\n\t\t\t\tbreak;\n\t\t\tcase GAMEMSG_CTF_CAPTURE:\n\t\t\t\tm_pSounds->Enqueue(CSounds::CHN_GLOBAL, SOUND_CTF_CAPTURE);\n\t\t\t\tif(aParaI[2] <= 60*Client()->GameTickSpeed())\n\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"The %s flag was captured by '%s' (%.2f seconds)\", aParaI[0] ? Localize(\"blue\") : Localize(\"red\"), m_aClients[clamp(aParaI[1], 0, MAX_CLIENTS-1)].m_aName, aParaI[2]/(float)Client()->GameTickSpeed());\n\t\t\t\telse\n\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"The %s flag was captured by '%s'\", aParaI[0] ? Localize(\"blue\") : Localize(\"red\"), m_aClients[clamp(aParaI[1], 0, MAX_CLIENTS-1)].m_aName);\n\t\t\t\tm_pChat->AddLine(-1, 0, aBuf);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// build message\n\t\tconst char *pText = \"\";\n\t\tif(NumParaI == 0)\n\t\t\tpText = Localize(gs_GameMsgList[GameMsgID].m_pText);\n\t\telse\n\t\t{\n\t\t\tif(NumParaI == 1)\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), Localize(gs_GameMsgList[GameMsgID].m_pText), aParaI[0]);\n\t\t\telse if(NumParaI == 2)\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), Localize(gs_GameMsgList[GameMsgID].m_pText), aParaI[0], aParaI[1]);\n\t\t\telse if(NumParaI == 3)\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), Localize(gs_GameMsgList[GameMsgID].m_pText), aParaI[0], aParaI[1], aParaI[2]);\n\t\t\tpText = aBuf;\n\t\t}\n\n\t\t// handle message\n\t\tswitch(gs_GameMsgList[GameMsgID].m_Action)\n\t\t{\n\t\tcase DO_CHAT:\n\t\t\tm_pChat->AddLine(-1, 0, pText);\n\t\t\tbreak;\n\t\tcase DO_BROADCAST:\n\t\t\tm_pBroadcast->DoBroadcast(pText);\n\t\t}\n\t}\n\n\tvoid *pRawMsg = m_NetObjHandler.SecureUnpackMsg(MsgId, pUnpacker);\n\tif(!pRawMsg)\n\t{\n\t\tchar aBuf[256];\n\t\tstr_format(aBuf, sizeof(aBuf), \"dropped weird message '%s' (%d), failed on '%s'\", m_NetObjHandler.GetMsgName(MsgId), MsgId, m_NetObjHandler.FailedMsgOn());\n\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"client\", aBuf);\n\t\treturn;\n\t}\n\n\t// TODO: this should be done smarter\n\tfor(int i = 0; i < m_All.m_Num; i++)\n\t\tm_All.m_paComponents[i]->OnMessage(MsgId, pRawMsg);\n\n\tif(MsgId == NETMSGTYPE_SV_CLIENTINFO && Client()->State() != IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tClient()->RecordGameMessage(false);\n\t\tCNetMsg_Sv_ClientInfo *pMsg = (CNetMsg_Sv_ClientInfo *)pRawMsg;\n\n\t\tif(pMsg->m_Local)\n\t\t{\n\t\t\tif(m_LocalClientID != -1)\n\t\t\t{\n\t\t\t\tif(g_Config.m_Debug)\n\t\t\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"client\", \"invalid local clientinfo\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tm_LocalClientID = pMsg->m_ClientID;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(m_aClients[pMsg->m_ClientID].m_Active)\n\t\t\t{\n\t\t\t\tif(g_Config.m_Debug)\n\t\t\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"client\", \"invalid clientinfo\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif(m_LocalClientID != -1)\n\t\t\t{\n\t\t\t\tDoEnterMessage(pMsg->m_pName, pMsg->m_Team);\n\t\t\t\t\n\t\t\t\tif(m_pDemoRecorder->IsRecording())\n\t\t\t\t{\n\t\t\t\t\tCNetMsg_De_ClientEnter Msg;\n\t\t\t\t\tMsg.m_pName = pMsg->m_pName;\n\t\t\t\t\tMsg.m_Team = pMsg->m_Team;\n\t\t\t\t\tClient()->SendPackMsg(&Msg, MSGFLAG_NOSEND|MSGFLAG_RECORD);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tm_aClients[pMsg->m_ClientID].m_Active = true;\n\t\tm_aClients[pMsg->m_ClientID].m_Team  = pMsg->m_Team;\n\t\tstr_copy(m_aClients[pMsg->m_ClientID].m_aName, pMsg->m_pName, sizeof(m_aClients[pMsg->m_ClientID].m_aName));\n\t\tstr_copy(m_aClients[pMsg->m_ClientID].m_aClan, pMsg->m_pClan, sizeof(m_aClients[pMsg->m_ClientID].m_aClan));\n\t\tm_aClients[pMsg->m_ClientID].m_Country = pMsg->m_Country;\n\t\tfor(int i = 0; i < 6; i++)\n\t\t{\n\t\t\tstr_copy(m_aClients[pMsg->m_ClientID].m_aaSkinPartNames[i], pMsg->m_apSkinPartNames[i], 24);\n\t\t\tm_aClients[pMsg->m_ClientID].m_aUseCustomColors[i] = pMsg->m_aUseCustomColors[i];\n\t\t\tm_aClients[pMsg->m_ClientID].m_aSkinPartColors[i] = pMsg->m_aSkinPartColors[i];\n\t\t}\n\n\t\t// update friend state\n\t\tm_aClients[pMsg->m_ClientID].m_Friend = Friends()->IsFriend(m_aClients[pMsg->m_ClientID].m_aName, m_aClients[pMsg->m_ClientID].m_aClan, true);\n\n\t\tm_aClients[pMsg->m_ClientID].UpdateRenderInfo(this, true);\n\n\t\tm_GameInfo.m_NumPlayers++;\n\t\t// calculate team-balance\n\t\tif(m_aClients[pMsg->m_ClientID].m_Team != TEAM_SPECTATORS)\n\t\t\tm_GameInfo.m_aTeamSize[m_aClients[pMsg->m_ClientID].m_Team]++;\n\t}\n\telse if(MsgId == NETMSGTYPE_SV_CLIENTDROP && Client()->State() != IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tClient()->RecordGameMessage(false);\n\t\tCNetMsg_Sv_ClientDrop *pMsg = (CNetMsg_Sv_ClientDrop *)pRawMsg;\n\n\t\tif(m_LocalClientID == pMsg->m_ClientID || !m_aClients[pMsg->m_ClientID].m_Active)\n\t\t{\n\t\t\tif(g_Config.m_Debug)\n\t\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"client\", \"invalid clientdrop\");\n\t\t\treturn;\n\t\t}\n\n\t\tDoLeaveMessage(m_aClients[pMsg->m_ClientID].m_aName, pMsg->m_pReason);\n\n\t\tCNetMsg_De_ClientLeave Msg;\n\t\tMsg.m_pName = m_aClients[pMsg->m_ClientID].m_aName;\n\t\tMsg.m_pReason = pMsg->m_pReason;\n\t\tClient()->SendPackMsg(&Msg, MSGFLAG_NOSEND|MSGFLAG_RECORD);\n\n\t\tm_GameInfo.m_NumPlayers--;\n\t\t// calculate team-balance\n\t\tif(m_aClients[pMsg->m_ClientID].m_Team != TEAM_SPECTATORS)\n\t\t\tm_GameInfo.m_aTeamSize[m_aClients[pMsg->m_ClientID].m_Team]--;\n\n\t\tm_aClients[pMsg->m_ClientID].Reset(this);\n\t}\n\telse if(MsgId == NETMSGTYPE_SV_GAMEINFO && Client()->State() != IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tClient()->RecordGameMessage(false);\n\t\tCNetMsg_Sv_GameInfo *pMsg = (CNetMsg_Sv_GameInfo *)pRawMsg;\n\n\t\tm_GameInfo.m_GameFlags = pMsg->m_GameFlags;\n\t\tm_GameInfo.m_ScoreLimit = pMsg->m_ScoreLimit;\n\t\tm_GameInfo.m_TimeLimit = pMsg->m_TimeLimit;\n\t\tm_GameInfo.m_MatchNum = pMsg->m_MatchNum;\n\t\tm_GameInfo.m_MatchCurrent = pMsg->m_MatchCurrent;\n\t}\n\telse if(MsgId == NETMSGTYPE_SV_SERVERSETTINGS && Client()->State() != IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tClient()->RecordGameMessage(false);\n\t\tCNetMsg_Sv_ServerSettings *pMsg = (CNetMsg_Sv_ServerSettings *)pRawMsg;\n\n\t\tif(!m_ServerSettings.m_TeamLock && pMsg->m_TeamLock)\n\t\t\tm_pChat->AddLine(-1, 0, Localize(\"Teams were locked\"));\n\t\telse if(m_ServerSettings.m_TeamLock && !pMsg->m_TeamLock)\n\t\t\tm_pChat->AddLine(-1, 0, Localize(\"Teams were unlocked\"));\n\t\tm_ServerSettings.m_KickVote = pMsg->m_KickVote;\n\t\tm_ServerSettings.m_KickMin = pMsg->m_KickMin;\n\t\tm_ServerSettings.m_SpecVote = pMsg->m_SpecVote;\n\t\tm_ServerSettings.m_TeamLock = pMsg->m_TeamLock;\n\t\tm_ServerSettings.m_TeamBalance = pMsg->m_TeamBalance;\n\t\tm_ServerSettings.m_PlayerSlots = pMsg->m_PlayerSlots;\n\t}\n\telse if(MsgId == NETMSGTYPE_SV_TEAM)\n\t{\n\t\tCNetMsg_Sv_Team *pMsg = (CNetMsg_Sv_Team *)pRawMsg;\n\n\t\tif(Client()->State() != IClient::STATE_DEMOPLAYBACK)\n\t\t{\n\t\t\t// calculate team-balance\n\t\t\tif(m_aClients[pMsg->m_ClientID].m_Team != TEAM_SPECTATORS)\n\t\t\t\tm_GameInfo.m_aTeamSize[m_aClients[pMsg->m_ClientID].m_Team]--;\n\t\t\tm_aClients[pMsg->m_ClientID].m_Team = pMsg->m_Team;\n\t\t\tif(m_aClients[pMsg->m_ClientID].m_Team != TEAM_SPECTATORS)\n\t\t\t\tm_GameInfo.m_aTeamSize[m_aClients[pMsg->m_ClientID].m_Team]++;\n\n\t\t\tm_aClients[pMsg->m_ClientID].UpdateRenderInfo(this, false);\n\n\t\t\tif(pMsg->m_ClientID == m_LocalClientID)\n\t\t\t\tm_TeamCooldownTick = pMsg->m_CooldownTick;\n\t\t}\n\n\t\tif(pMsg->m_Silent == 0)\n\t\t{\n\t\t\tDoTeamChangeMessage(m_aClients[pMsg->m_ClientID].m_aName, pMsg->m_Team);\n\t\t}\t\t\n\t}\n\telse if(MsgId == NETMSGTYPE_SV_READYTOENTER)\n\t{\n\t\tClient()->EnterGame();\n\t}\n\telse if (MsgId == NETMSGTYPE_SV_EMOTICON)\n\t{\n\t\tCNetMsg_Sv_Emoticon *pMsg = (CNetMsg_Sv_Emoticon *)pRawMsg;\n\n\t\t// apply\n\t\tm_aClients[pMsg->m_ClientID].m_Emoticon = pMsg->m_Emoticon;\n\t\tm_aClients[pMsg->m_ClientID].m_EmoticonStart = Client()->GameTick();\n\t}\n\telse if(MsgId == NETMSGTYPE_DE_CLIENTENTER && Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tCNetMsg_De_ClientEnter *pMsg = (CNetMsg_De_ClientEnter *)pRawMsg;\n\t\tDoEnterMessage(pMsg->m_pName, pMsg->m_Team);\n\t}\n\telse if(MsgId == NETMSGTYPE_DE_CLIENTLEAVE && Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tCNetMsg_De_ClientLeave *pMsg = (CNetMsg_De_ClientLeave *)pRawMsg;\n\t\tDoLeaveMessage(pMsg->m_pName, pMsg->m_pReason);\n\t}\n}\n\nvoid CGameClient::OnStateChange(int NewState, int OldState)\n{\n\t// reset everything when not already connected (to keep gathered stuff)\n\tif(NewState < IClient::STATE_ONLINE)\n\t\tOnReset();\n\n\t// then change the state\n\tfor(int i = 0; i < m_All.m_Num; i++)\n\t\tm_All.m_paComponents[i]->OnStateChange(NewState, OldState);\n}\n\nvoid CGameClient::OnShutdown() {}\nvoid CGameClient::OnEnterGame() {}\n\nvoid CGameClient::OnGameOver()\n{\n\tif(Client()->State() != IClient::STATE_DEMOPLAYBACK && g_Config.m_ClEditor == 0)\n\t\tClient()->AutoScreenshot_Start();\n}\n\nvoid CGameClient::OnStartGame()\n{\n\tif(Client()->State() != IClient::STATE_DEMOPLAYBACK)\n\t\tClient()->DemoRecorder_HandleAutoStart();\n}\n\nvoid CGameClient::OnRconLine(const char *pLine)\n{\n\tm_pGameConsole->PrintLine(CGameConsole::CONSOLETYPE_REMOTE, pLine);\n}\n\nvoid CGameClient::ProcessEvents()\n{\n\tif(m_SuppressEvents)\n\t\treturn;\n\n\tint SnapType = IClient::SNAP_CURRENT;\n\tint Num = Client()->SnapNumItems(SnapType);\n\tfor(int Index = 0; Index < Num; Index++)\n\t{\n\t\tIClient::CSnapItem Item;\n\t\tconst void *pData = Client()->SnapGetItem(SnapType, Index, &Item);\n\n\t\tif(Item.m_Type == NETEVENTTYPE_DAMAGEIND)\n\t\t{\n\t\t\tCNetEvent_DamageInd *ev = (CNetEvent_DamageInd *)pData;\n\t\t\tm_pEffects->DamageIndicator(vec2(ev->m_X, ev->m_Y), GetDirection(ev->m_Angle));\n\t\t}\n\t\telse if(Item.m_Type == NETEVENTTYPE_EXPLOSION)\n\t\t{\n\t\t\tCNetEvent_Explosion *ev = (CNetEvent_Explosion *)pData;\n\t\t\tm_pEffects->Explosion(vec2(ev->m_X, ev->m_Y));\n\t\t}\n\t\telse if(Item.m_Type == NETEVENTTYPE_HAMMERHIT)\n\t\t{\n\t\t\tCNetEvent_HammerHit *ev = (CNetEvent_HammerHit *)pData;\n\t\t\tm_pEffects->HammerHit(vec2(ev->m_X, ev->m_Y));\n\t\t}\n\t\telse if(Item.m_Type == NETEVENTTYPE_SPAWN)\n\t\t{\n\t\t\tCNetEvent_Spawn *ev = (CNetEvent_Spawn *)pData;\n\t\t\tm_pEffects->PlayerSpawn(vec2(ev->m_X, ev->m_Y));\n\t\t}\n\t\telse if(Item.m_Type == NETEVENTTYPE_DEATH)\n\t\t{\n\t\t\tCNetEvent_Death *ev = (CNetEvent_Death *)pData;\n\t\t\tm_pEffects->PlayerDeath(vec2(ev->m_X, ev->m_Y), ev->m_ClientID);\n\t\t}\n\t\telse if(Item.m_Type == NETEVENTTYPE_SOUNDWORLD)\n\t\t{\n\t\t\tCNetEvent_SoundWorld *ev = (CNetEvent_SoundWorld *)pData;\n\t\t\tm_pSounds->PlayAt(CSounds::CHN_WORLD, ev->m_SoundID, 1.0f, vec2(ev->m_X, ev->m_Y));\n\t\t}\n\t}\n}\n\nvoid CGameClient::ProcessTriggeredEvents(int Events, vec2 Pos)\n{\n\tif(m_SuppressEvents)\n\t\treturn;\n\n\tif(Events&COREEVENTFLAG_GROUND_JUMP)\n\t\tm_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_PLAYER_JUMP, 1.0f, Pos);\n\tif(Events&COREEVENTFLAG_AIR_JUMP)\n\t\tm_pEffects->AirJump(Pos);\n\tif(Events&COREEVENTFLAG_HOOK_ATTACH_PLAYER)\n\t\tm_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_HOOK_ATTACH_PLAYER, 1.0f, Pos);\n\tif(Events&COREEVENTFLAG_HOOK_ATTACH_GROUND)\n\t\tm_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_HOOK_ATTACH_GROUND, 1.0f, Pos);\n\tif(Events&COREEVENTFLAG_HOOK_HIT_NOHOOK)\n\t\tm_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_HOOK_NOATTACH, 1.0f, Pos);\n\t/*if(Events&COREEVENTFLAG_HOOK_LAUNCH)\n\t\tm_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_HOOK_LOOP, 1.0f, Pos);\n\tif(Events&COREEVENTFLAG_HOOK_RETRACT)\n\t\tm_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_PLAYER_JUMP, 1.0f, Pos);*/\n}\n\nvoid CGameClient::OnNewSnapshot()\n{\n\t// clear out the invalid pointers\n\tmem_zero(&m_Snap, sizeof(m_Snap));\n\n\t// secure snapshot\n\t{\n\t\tint Num = Client()->SnapNumItems(IClient::SNAP_CURRENT);\n\t\tfor(int Index = 0; Index < Num; Index++)\n\t\t{\n\t\t\tIClient::CSnapItem Item;\n\t\t\tvoid *pData = Client()->SnapGetItem(IClient::SNAP_CURRENT, Index, &Item);\n\t\t\tif(m_NetObjHandler.ValidateObj(Item.m_Type, pData, Item.m_DataSize) != 0)\n\t\t\t{\n\t\t\t\tif(g_Config.m_Debug)\n\t\t\t\t{\n\t\t\t\t\tchar aBuf[256];\n\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"invalidated index=%d type=%d (%s) size=%d id=%d\", Index, Item.m_Type, m_NetObjHandler.GetObjName(Item.m_Type), Item.m_DataSize, Item.m_ID);\n\t\t\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"game\", aBuf);\n\t\t\t\t}\n\t\t\t\tClient()->SnapInvalidateItem(IClient::SNAP_CURRENT, Index);\n\t\t\t}\n\t\t}\n\t}\n\n\tProcessEvents();\n\n\tif(g_Config.m_DbgStress)\n\t{\n\t\tif((Client()->GameTick()%100) == 0)\n\t\t{\n\t\t\tchar aMessage[64];\n\t\t\tint MsgLen = rand()%(sizeof(aMessage)-1);\n\t\t\tfor(int i = 0; i < MsgLen; i++)\n\t\t\t\taMessage[i] = 'a'+(rand()%('z'-'a'));\n\t\t\taMessage[MsgLen] = 0;\n\n\t\t\tCNetMsg_Cl_Say Msg;\n\t\t\tMsg.m_Team = rand()&1;\n\t\t\tMsg.m_pMessage = aMessage;\n\t\t\tClient()->SendPackMsg(&Msg, MSGFLAG_VITAL);\n\t\t}\n\t}\n\n\tCTuningParams StandardTuning;\n\tif(Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tm_Tuning = StandardTuning;\n\t\tmem_zero(&m_GameInfo, sizeof(m_GameInfo));\n\t}\n\n\t// go trough all the items in the snapshot and gather the info we want\n\t{\n\t\tint Num = Client()->SnapNumItems(IClient::SNAP_CURRENT);\n\t\tfor(int i = 0; i < Num; i++)\n\t\t{\n\t\t\tIClient::CSnapItem Item;\n\t\t\tconst void *pData = Client()->SnapGetItem(IClient::SNAP_CURRENT, i, &Item);\n\n\t\t\t// demo items\n\t\t\tif(Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t\t\t{\n\t\t\t\tif(Item.m_Type == NETOBJTYPE_DE_CLIENTINFO)\n\t\t\t\t{\n\t\t\t\t\tconst CNetObj_De_ClientInfo *pInfo = (const CNetObj_De_ClientInfo *)pData;\n\t\t\t\t\tint ClientID = Item.m_ID;\n\t\t\t\t\tCClientData *pClient = &m_aClients[ClientID];\n\n\t\t\t\t\tif(pInfo->m_Local)\n\t\t\t\t\t\tm_LocalClientID = ClientID;\n\t\t\t\t\tpClient->m_Active = true;\n\t\t\t\t\tpClient->m_Team  = pInfo->m_Team;\n\t\t\t\t\tIntsToStr(pInfo->m_aName, 4, pClient->m_aName);\n\t\t\t\t\tIntsToStr(pInfo->m_aClan, 3, pClient->m_aClan);\n\t\t\t\t\tpClient->m_Country = pInfo->m_Country;\n\n\t\t\t\t\tfor(int p = 0; p < CSkins::NUM_SKINPARTS; p++)\n\t\t\t\t\t{\n\t\t\t\t\t\tIntsToStr(pInfo->m_aaSkinPartNames[p], 6, pClient->m_aaSkinPartNames[p]);\n\t\t\t\t\t\tpClient->m_aUseCustomColors[p] = pInfo->m_aUseCustomColors[p];\n\t\t\t\t\t\tpClient->m_aSkinPartColors[p] = pInfo->m_aSkinPartColors[p];\n\t\t\t\t\t}\n\n\t\t\t\t\tm_GameInfo.m_NumPlayers++;\n\t\t\t\t\t// calculate team-balance\n\t\t\t\t\tif(pClient->m_Team != TEAM_SPECTATORS)\n\t\t\t\t\t\tm_GameInfo.m_aTeamSize[pClient->m_Team]++;\n\t\t\t\t}\n\t\t\t\telse if(Item.m_Type == NETOBJTYPE_DE_GAMEINFO)\n\t\t\t\t{\n\t\t\t\t\tconst CNetObj_De_GameInfo *pInfo = (const CNetObj_De_GameInfo *)pData;\n\n\t\t\t\t\tm_GameInfo.m_GameFlags = pInfo->m_GameFlags;\n\t\t\t\t\tm_GameInfo.m_ScoreLimit = pInfo->m_ScoreLimit;\n\t\t\t\t\tm_GameInfo.m_TimeLimit = pInfo->m_TimeLimit;\n\t\t\t\t\tm_GameInfo.m_MatchNum = pInfo->m_MatchNum;\n\t\t\t\t\tm_GameInfo.m_MatchCurrent = pInfo->m_MatchCurrent;\n\t\t\t\t}\n\t\t\t\telse if(Item.m_Type == NETOBJTYPE_DE_TUNEPARAMS)\n\t\t\t\t{\n\t\t\t\t\tconst CNetObj_De_TuneParams *pInfo = (const CNetObj_De_TuneParams *)pData;\n\n\t\t\t\t\tmem_copy(&m_Tuning, pInfo->m_aTuneParams, sizeof(m_Tuning));\n\t\t\t\t\tm_ServerMode = SERVERMODE_PURE;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t// network items\n\t\t\tif(Item.m_Type == NETOBJTYPE_PLAYERINFO)\n\t\t\t{\n\t\t\t\tconst CNetObj_PlayerInfo *pInfo = (const CNetObj_PlayerInfo *)pData;\n\t\t\t\tint ClientID = Item.m_ID;\n\t\t\t\tif(m_aClients[ClientID].m_Active)\n\t\t\t\t{\n\t\t\t\t\tm_Snap.m_paPlayerInfos[ClientID] = pInfo;\n\t\t\t\t\tm_Snap.m_aInfoByScore[ClientID].m_pPlayerInfo = pInfo;\n\t\t\t\t\tm_Snap.m_aInfoByScore[ClientID].m_ClientID = ClientID;\n\n\t\t\t\t\tif(m_LocalClientID == ClientID)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_Snap.m_pLocalInfo = pInfo;\n\n\t\t\t\t\t\tif(m_aClients[ClientID].m_Team == TEAM_SPECTATORS)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tm_Snap.m_SpecInfo.m_Active = true;\n\t\t\t\t\t\t\tm_Snap.m_SpecInfo.m_SpectatorID = SPEC_FREEVIEW;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(Item.m_Type == NETOBJTYPE_CHARACTER)\n\t\t\t{\n\t\t\t\tconst void *pOld = Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_CHARACTER, Item.m_ID);\n\t\t\t\tm_Snap.m_aCharacters[Item.m_ID].m_Cur = *((const CNetObj_Character *)pData);\n\n\t\t\t\t// clamp ammo count for non ninja weapon\n\t\t\t\tif(m_Snap.m_aCharacters[Item.m_ID].m_Cur.m_Weapon != WEAPON_NINJA)\n\t\t\t\t\tm_Snap.m_aCharacters[Item.m_ID].m_Cur.m_AmmoCount = clamp(m_Snap.m_aCharacters[Item.m_ID].m_Cur.m_AmmoCount, 0, 10);\n\t\t\t\t\n\t\t\t\tif(pOld)\n\t\t\t\t{\n\t\t\t\t\tm_Snap.m_aCharacters[Item.m_ID].m_Active = true;\n\t\t\t\t\tm_Snap.m_aCharacters[Item.m_ID].m_Prev = *((const CNetObj_Character *)pOld);\n\n\t\t\t\t\tif(m_Snap.m_aCharacters[Item.m_ID].m_Prev.m_Tick)\n\t\t\t\t\t\tEvolveCharacter(&m_Snap.m_aCharacters[Item.m_ID].m_Prev, Client()->PrevGameTick());\n\t\t\t\t\tif(m_Snap.m_aCharacters[Item.m_ID].m_Cur.m_Tick)\n\t\t\t\t\t\tEvolveCharacter(&m_Snap.m_aCharacters[Item.m_ID].m_Cur, Client()->GameTick());\n\t\t\t\t}\n\n\t\t\t\tif(Item.m_ID != m_LocalClientID || Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t\t\t\t\tProcessTriggeredEvents(m_Snap.m_aCharacters[Item.m_ID].m_Cur.m_TriggeredEvents, vec2(m_Snap.m_aCharacters[Item.m_ID].m_Cur.m_X, m_Snap.m_aCharacters[Item.m_ID].m_Cur.m_Y));\n\t\t\t}\n\t\t\telse if(Item.m_Type == NETOBJTYPE_SPECTATORINFO)\n\t\t\t{\n\t\t\t\tm_Snap.m_pSpectatorInfo = (const CNetObj_SpectatorInfo *)pData;\n\t\t\t\tm_Snap.m_pPrevSpectatorInfo = (const CNetObj_SpectatorInfo *)Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_SPECTATORINFO, Item.m_ID);\n\t\t\t\tm_Snap.m_SpecInfo.m_Active = true;\n\t\t\t\tm_Snap.m_SpecInfo.m_SpectatorID = m_Snap.m_pSpectatorInfo->m_SpectatorID;\n\t\t\t}\n\t\t\telse if(Item.m_Type == NETOBJTYPE_GAMEDATA)\n\t\t\t{\n\t\t\t\tm_Snap.m_pGameData = (const CNetObj_GameData *)pData;\n\n\t\t\t\tstatic bool s_GameOver = 0;\n\t\t\t\tif(!s_GameOver && m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)\n\t\t\t\t\tOnGameOver();\n\t\t\t\telse if(s_GameOver && !(m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER))\n\t\t\t\t\tOnStartGame();\n\t\t\t\ts_GameOver = m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER;\n\t\t\t}\n\t\t\telse if(Item.m_Type == NETOBJTYPE_GAMEDATATEAM)\n\t\t\t{\n\t\t\t\tm_Snap.m_pGameDataTeam = (const CNetObj_GameDataTeam *)pData;\n\t\t\t}\n\t\t\telse if(Item.m_Type == NETOBJTYPE_GAMEDATAFLAG)\n\t\t\t{\n\t\t\t\tm_Snap.m_pGameDataFlag = (const CNetObj_GameDataFlag *)pData;\n\t\t\t\tm_Snap.m_GameDataFlagSnapID = Item.m_ID;\n\t\t\t}\n\t\t\telse if(Item.m_Type == NETOBJTYPE_FLAG)\n\t\t\t\tm_Snap.m_paFlags[Item.m_ID%2] = (const CNetObj_Flag *)pData;\n\t\t}\n\t}\n\n\t// setup local pointers\n\tif(m_LocalClientID >= 0)\n\t{\n\t\tCSnapState::CCharacterInfo *c = &m_Snap.m_aCharacters[m_LocalClientID];\n\t\tif(c->m_Active)\n\t\t{\n\t\t\tm_Snap.m_pLocalCharacter = &c->m_Cur;\n\t\t\tm_Snap.m_pLocalPrevCharacter = &c->m_Prev;\n\t\t\tm_LocalCharacterPos = vec2(m_Snap.m_pLocalCharacter->m_X, m_Snap.m_pLocalCharacter->m_Y);\n\t\t}\n\t\telse if(Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_CHARACTER, m_LocalClientID))\n\t\t{\n\t\t\t// player died\n\t\t\tm_pControls->OnPlayerDeath();\n\t\t}\n\t}\n\telse\n\t{\n\t\tm_Snap.m_SpecInfo.m_Active = true;\n\t\tif(Client()->State() == IClient::STATE_DEMOPLAYBACK && DemoPlayer()->GetDemoType() == IDemoPlayer::DEMOTYPE_SERVER &&\n\t\t\tm_DemoSpecID != SPEC_FREEVIEW && m_Snap.m_aCharacters[m_DemoSpecID].m_Active)\n\t\t\tm_Snap.m_SpecInfo.m_SpectatorID = m_DemoSpecID;\n\t\telse\n\t\t\tm_Snap.m_SpecInfo.m_SpectatorID = SPEC_FREEVIEW;\n\t}\n\n\t// sort player infos by score\n\tfor(int k = 0; k < MAX_CLIENTS-1; k++) // ffs, bubblesort\n\t{\n\t\tfor(int i = 0; i < MAX_CLIENTS-k-1; i++)\n\t\t{\n\t\t\tif(m_Snap.m_aInfoByScore[i+1].m_pPlayerInfo && (!m_Snap.m_aInfoByScore[i].m_pPlayerInfo ||\n\t\t\t\tm_Snap.m_aInfoByScore[i].m_pPlayerInfo->m_Score < m_Snap.m_aInfoByScore[i+1].m_pPlayerInfo->m_Score))\n\t\t\t{\n\t\t\t\tCPlayerInfoItem Tmp = m_Snap.m_aInfoByScore[i];\n\t\t\t\tm_Snap.m_aInfoByScore[i] = m_Snap.m_aInfoByScore[i+1];\n\t\t\t\tm_Snap.m_aInfoByScore[i+1] = Tmp;\n\t\t\t}\n\t\t}\n\t}\n\n\t// calc some player stats\n\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t{\n\t\tif(!m_Snap.m_paPlayerInfos[i])\n\t\t\tcontinue;\n\n\t\t// count not ready players\n\t\tif((m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_STARTCOUNTDOWN|GAMESTATEFLAG_PAUSED|GAMESTATEFLAG_WARMUP)) &&\n\t\t\tm_Snap.m_pGameData->m_GameStateEndTick == 0 && m_aClients[i].m_Team != TEAM_SPECTATORS && !(m_Snap.m_paPlayerInfos[i]->m_PlayerFlags&PLAYERFLAG_READY))\n\t\t\tm_Snap.m_NotReadyCount++;\n\n\t\t// count alive players per team\n\t\tif((m_GameInfo.m_GameFlags&GAMEFLAG_SURVIVAL) && m_aClients[i].m_Team != TEAM_SPECTATORS && !(m_Snap.m_paPlayerInfos[i]->m_PlayerFlags&PLAYERFLAG_DEAD))\n\t\t\tm_Snap.m_AliveCount[m_aClients[i].m_Team]++;\n\t}\n\n\tif(Client()->State() == IClient::STATE_DEMOPLAYBACK)\n\t{\n\t\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t\t{\n\t\t\tif(m_aClients[i].m_Active)\n\t\t\t\tm_aClients[i].UpdateRenderInfo(this, true);\n\t\t}\n\t}\n\n\tCServerInfo CurrentServerInfo;\n\tClient()->GetServerInfo(&CurrentServerInfo);\n\tif(CurrentServerInfo.m_aGameType[0] != '0')\n\t{\n\t\tif(str_comp(CurrentServerInfo.m_aGameType, \"DM\") != 0 && str_comp(CurrentServerInfo.m_aGameType, \"TDM\") != 0 && str_comp(CurrentServerInfo.m_aGameType, \"CTF\") != 0 &&\n\t\t\tstr_comp(CurrentServerInfo.m_aGameType, \"LMS\") != 0 && str_comp(CurrentServerInfo.m_aGameType, \"SUR\") != 0)\n\t\t\tm_ServerMode = SERVERMODE_MOD;\n\t\telse if(mem_comp(&StandardTuning, &m_Tuning, sizeof(CTuningParams)) == 0)\n\t\t\tm_ServerMode = SERVERMODE_PURE;\n\t\telse\n\t\t\tm_ServerMode = SERVERMODE_PUREMOD;\n\t}\n}\n\nvoid CGameClient::OnDemoRecSnap()\n{\n\t// add client info\n\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t{\n\t\tif(!m_aClients[i].m_Active)\n\t\t\tcontinue;\n\n\t\tCNetObj_De_ClientInfo *pClientInfo = static_cast<CNetObj_De_ClientInfo *>(Client()->SnapNewItem(NETOBJTYPE_DE_CLIENTINFO, i, sizeof(CNetObj_De_ClientInfo)));\n\t\tif(!pClientInfo)\n\t\t\treturn;\n\n\t\tpClientInfo->m_Local = i==m_LocalClientID ? 1 : 0;\n\t\tpClientInfo->m_Team = m_aClients[i].m_Team;\n\t\tStrToInts(pClientInfo->m_aName, 4, m_aClients[i].m_aName);\n\t\tStrToInts(pClientInfo->m_aClan, 3, m_aClients[i].m_aClan);\n\t\tpClientInfo->m_Country = m_aClients[i].m_Country;\n\n\t\tfor(int p = 0; p < 6; p++)\n\t\t{\n\t\t\tStrToInts(pClientInfo->m_aaSkinPartNames[p], 6, m_aClients[i].m_aaSkinPartNames[p]);\n\t\t\tpClientInfo->m_aUseCustomColors[p] = m_aClients[i].m_aUseCustomColors[p];\n\t\t\tpClientInfo->m_aSkinPartColors[p] = m_aClients[i].m_aSkinPartColors[p];\n\t\t}\n\t}\n\n\t// add tuning\n\tCTuningParams StandardTuning;\n\tif(mem_comp(&StandardTuning, &m_Tuning, sizeof(CTuningParams)) != 0)\n\t{\n\t\tCNetObj_De_TuneParams *pTuneParams = static_cast<CNetObj_De_TuneParams *>(Client()->SnapNewItem(NETOBJTYPE_DE_TUNEPARAMS, 0, sizeof(CNetObj_De_TuneParams)));\n\t\tif(!pTuneParams)\n\t\t\treturn;\n\n\t\tmem_copy(pTuneParams->m_aTuneParams, &m_Tuning, sizeof(pTuneParams->m_aTuneParams));\n\t}\n\n\t// add game info\n\tCNetObj_De_GameInfo *pGameInfo = static_cast<CNetObj_De_GameInfo *>(Client()->SnapNewItem(NETOBJTYPE_DE_GAMEINFO, 0, sizeof(CNetObj_De_GameInfo)));\n\tif(!pGameInfo)\n\t\treturn;\n\t\n\tpGameInfo->m_GameFlags = m_GameInfo.m_GameFlags;\n\tpGameInfo->m_ScoreLimit = m_GameInfo.m_ScoreLimit;\n\tpGameInfo->m_TimeLimit = m_GameInfo.m_TimeLimit;\n\tpGameInfo->m_MatchNum = m_GameInfo.m_MatchNum;\n\tpGameInfo->m_MatchCurrent = m_GameInfo.m_MatchCurrent;\n}\n\nvoid CGameClient::OnPredict()\n{\n\t// store the previous values so we can detect prediction errors\n\tCCharacterCore BeforePrevChar = m_PredictedPrevChar;\n\tCCharacterCore BeforeChar = m_PredictedChar;\n\n\t// we can't predict without our own id or own character\n\tif(m_LocalClientID == -1 || !m_Snap.m_aCharacters[m_LocalClientID].m_Active)\n\t\treturn;\n\n\t// don't predict anything if we are paused or round/game is over\n\tif(m_Snap.m_pGameData && m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_PAUSED|GAMESTATEFLAG_ROUNDOVER|GAMESTATEFLAG_GAMEOVER))\n\t{\n\t\tif(m_Snap.m_pLocalCharacter)\n\t\t\tm_PredictedChar.Read(m_Snap.m_pLocalCharacter);\n\t\tif(m_Snap.m_pLocalPrevCharacter)\n\t\t\tm_PredictedPrevChar.Read(m_Snap.m_pLocalPrevCharacter);\n\t\treturn;\n\t}\n\n\t// repredict character\n\tCWorldCore World;\n\tWorld.m_Tuning = m_Tuning;\n\n\t// search for players\n\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t{\n\t\tif(!m_Snap.m_aCharacters[i].m_Active)\n\t\t\tcontinue;\n\n\t\tm_aClients[i].m_Predicted.Init(&World, Collision());\n\t\tWorld.m_apCharacters[i] = &m_aClients[i].m_Predicted;\n\t\tm_aClients[i].m_Predicted.Read(&m_Snap.m_aCharacters[i].m_Cur);\n\t}\n\n\t// predict\n\tfor(int Tick = Client()->GameTick()+1; Tick <= Client()->PredGameTick(); Tick++)\n\t{\n\t\t// fetch the local\n\t\tif(Tick == Client()->PredGameTick() && World.m_apCharacters[m_LocalClientID])\n\t\t\tm_PredictedPrevChar = *World.m_apCharacters[m_LocalClientID];\n\n\t\t// first calculate where everyone should move\n\t\tfor(int c = 0; c < MAX_CLIENTS; c++)\n\t\t{\n\t\t\tif(!World.m_apCharacters[c])\n\t\t\t\tcontinue;\n\n\t\t\tmem_zero(&World.m_apCharacters[c]->m_Input, sizeof(World.m_apCharacters[c]->m_Input));\n\t\t\tif(m_LocalClientID == c)\n\t\t\t{\n\t\t\t\t// apply player input\n\t\t\t\tint *pInput = Client()->GetInput(Tick);\n\t\t\t\tif(pInput)\n\t\t\t\t\tWorld.m_apCharacters[c]->m_Input = *((CNetObj_PlayerInput*)pInput);\n\t\t\t\tWorld.m_apCharacters[c]->Tick(true);\n\t\t\t}\n\t\t\telse\n\t\t\t\tWorld.m_apCharacters[c]->Tick(false);\n\n\t\t}\n\n\t\t// move all players and quantize their data\n\t\tfor(int c = 0; c < MAX_CLIENTS; c++)\n\t\t{\n\t\t\tif(!World.m_apCharacters[c])\n\t\t\t\tcontinue;\n\n\t\t\tWorld.m_apCharacters[c]->Move();\n\t\t\tWorld.m_apCharacters[c]->Quantize();\n\t\t}\n\n\t\t// check if we want to trigger effects\n\t\tif(Tick > m_LastNewPredictedTick)\n\t\t{\n\t\t\tm_LastNewPredictedTick = Tick;\n\n\t\t\tif(m_LocalClientID != -1 && World.m_apCharacters[m_LocalClientID])\n\t\t\t\tProcessTriggeredEvents(World.m_apCharacters[m_LocalClientID]->m_TriggeredEvents, World.m_apCharacters[m_LocalClientID]->m_Pos);\n\t\t}\n\n\t\tif(Tick == Client()->PredGameTick() && World.m_apCharacters[m_LocalClientID])\n\t\t\tm_PredictedChar = *World.m_apCharacters[m_LocalClientID];\n\t}\n\n\tif(g_Config.m_Debug && g_Config.m_ClPredict && m_PredictedTick == Client()->PredGameTick())\n\t{\n\t\tCNetObj_CharacterCore Before = {0}, Now = {0}, BeforePrev = {0}, NowPrev = {0};\n\t\tBeforeChar.Write(&Before);\n\t\tBeforePrevChar.Write(&BeforePrev);\n\t\tm_PredictedChar.Write(&Now);\n\t\tm_PredictedPrevChar.Write(&NowPrev);\n\n\t\tif(mem_comp(&Before, &Now, sizeof(CNetObj_CharacterCore)) != 0)\n\t\t{\n\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"client\", \"prediction error\");\n\t\t\tfor(unsigned i = 0; i < sizeof(CNetObj_CharacterCore)/sizeof(int); i++)\n\t\t\t\tif(((int *)&Before)[i] != ((int *)&Now)[i])\n\t\t\t\t{\n\t\t\t\t\tchar aBuf[256];\n\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"\t%d %d %d (%d %d)\", i, ((int *)&Before)[i], ((int *)&Now)[i], ((int *)&BeforePrev)[i], ((int *)&NowPrev)[i]);\n\t\t\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"client\", aBuf);\n\t\t\t\t}\n\t\t}\n\t}\n\n\tm_PredictedTick = Client()->PredGameTick();\n}\n\nvoid CGameClient::OnActivateEditor()\n{\n\tOnRelease();\n}\n\nvoid CGameClient::CClientData::UpdateRenderInfo(CGameClient *pGameClient, bool UpdateSkinInfo)\n{\n\t// update skin info\n\tif(UpdateSkinInfo)\n\t{\n\t\tm_SkinInfo.m_Size = 64;\n\n\t\tfor(int p = 0; p < CSkins::NUM_SKINPARTS; p++)\n\t\t{\n\t\t\tint ID = pGameClient->m_pSkins->FindSkinPart(p, m_aaSkinPartNames[p], false);\n\t\t\tif(ID < 0)\n\t\t\t{\n\t\t\t\tif(p == CSkins::SKINPART_TATTOO || p == CSkins::SKINPART_DECORATION)\n\t\t\t\t\tID = pGameClient->m_pSkins->FindSkinPart(p, \"\", false);\n\t\t\t\telse\n\t\t\t\t\tID = pGameClient->m_pSkins->FindSkinPart(p, \"standard\", false);\n\n\t\t\t\tif(ID < 0)\n\t\t\t\t\tm_SkinPartIDs[p] = 0;\n\t\t\t\telse\n\t\t\t\t\tm_SkinPartIDs[p] = ID;\n\t\t\t}\n\t\t\telse\n\t\t\t\tm_SkinPartIDs[p] = ID;\n\n\t\t\tconst CSkins::CSkinPart *pSkinPart = pGameClient->m_pSkins->GetSkinPart(p, m_SkinPartIDs[p]);\n\t\t\tif(m_aUseCustomColors[p])\n\t\t\t{\n\t\t\t\tm_SkinInfo.m_aTextures[p] = pSkinPart->m_ColorTexture;\n\t\t\t\tm_SkinInfo.m_aColors[p] = pGameClient->m_pSkins->GetColorV4(m_aSkinPartColors[p], p==CSkins::SKINPART_TATTOO);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_SkinInfo.m_aTextures[p] = pSkinPart->m_OrgTexture;\n\t\t\t\tm_SkinInfo.m_aColors[p] = vec4(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\t}\n\t\t}\n\t}\n\n\tm_RenderInfo = m_SkinInfo;\n\n\t// force team colors\n\tif(pGameClient->m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS)\n\t{\n\t\tfor(int p = 0; p < CSkins::NUM_SKINPARTS; p++)\n\t\t{\n\t\t\tm_RenderInfo.m_aTextures[p] = pGameClient->m_pSkins->GetSkinPart(p, m_SkinPartIDs[p])->m_ColorTexture;\n\t\t\tint ColorVal = pGameClient->m_pSkins->GetTeamColor(m_aUseCustomColors[p], m_aSkinPartColors[p], m_Team, p);\n\t\t\tm_RenderInfo.m_aColors[p] = pGameClient->m_pSkins->GetColorV4(ColorVal, p==CSkins::SKINPART_TATTOO);\n\t\t}\n\t}\n}\n\nvoid CGameClient::CClientData::Reset(CGameClient *pGameClient)\n{\n\tm_aName[0] = 0;\n\tm_aClan[0] = 0;\n\tm_Country = -1;\n\tm_Team = 0;\n\tm_Angle = 0;\n\tm_Emoticon = 0;\n\tm_EmoticonStart = -1;\n\tm_Active = false;\n\tm_ChatIgnore = false;\n\tm_Friend = false;\n\tfor(int p = 0; p < CSkins::NUM_SKINPARTS; p++)\n\t{\n\t\tm_SkinPartIDs[p] = 0;\n\t\tm_SkinInfo.m_aTextures[p] = pGameClient->m_pSkins->GetSkinPart(p, 0)->m_ColorTexture;\n\t\tm_SkinInfo.m_aColors[p] = vec4(1.0f, 1.0f, 1.0f , 1.0f);\n\t}\n\tUpdateRenderInfo(pGameClient, false);\n}\n\nvoid CGameClient::DoEnterMessage(const char *pName, int Team)\n{\n\tchar aBuf[128];\n\tstr_format(aBuf, sizeof(aBuf), Localize(\"'%s' entered and joined the %s\"), pName, GetTeamName(Team, m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS));\n\tm_pChat->AddLine(-1, 0, aBuf);\n}\n\nvoid CGameClient::DoLeaveMessage(const char *pName, const char *pReason)\n{\n\tchar aBuf[128];\n\tif(pReason[0])\n\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"'%s' has left the game (%s)\"), pName, pReason);\n\telse\n\t\tstr_format(aBuf, sizeof(aBuf), Localize(\"'%s' has left the game\"), pName);\n\tm_pChat->AddLine(-1, 0, aBuf);\n}\n\nvoid CGameClient::DoTeamChangeMessage(const char *pName, int Team)\n{\n\tchar aBuf[128];\n\tstr_format(aBuf, sizeof(aBuf), Localize(\"'%s' joined the %s\"), pName, GetTeamName(Team, m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS));\n\tm_pChat->AddLine(-1, 0, aBuf);\n}\n\nvoid CGameClient::SendSwitchTeam(int Team)\n{\n\tCNetMsg_Cl_SetTeam Msg;\n\tMsg.m_Team = Team;\n\tClient()->SendPackMsg(&Msg, MSGFLAG_VITAL);\n}\n\nvoid CGameClient::SendStartInfo()\n{\n\tCNetMsg_Cl_StartInfo Msg;\n\tMsg.m_pName = g_Config.m_PlayerName;\n\tMsg.m_pClan = g_Config.m_PlayerClan;\n\tMsg.m_Country = g_Config.m_PlayerCountry;\n\tfor(int p = 0; p < CSkins::NUM_SKINPARTS; p++)\n\t{\n\t\tMsg.m_apSkinPartNames[p] = CSkins::ms_apSkinVariables[p];\n\t\tMsg.m_aUseCustomColors[p] = *CSkins::ms_apUCCVariables[p];\n\t\tMsg.m_aSkinPartColors[p] = *CSkins::ms_apColorVariables[p];\n\t}\n\tClient()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH);\n}\n\nvoid CGameClient::SendKill()\n{\n\tCNetMsg_Cl_Kill Msg;\n\tClient()->SendPackMsg(&Msg, MSGFLAG_VITAL);\n}\n\nvoid CGameClient::SendReadyChange()\n{\n\tCNetMsg_Cl_ReadyChange Msg;\n\tClient()->SendPackMsg(&Msg, MSGFLAG_VITAL);\n}\n\nvoid CGameClient::ConKill(IConsole::IResult *pResult, void *pUserData)\n{\n\t((CGameClient*)pUserData)->SendKill();\n}\n\nvoid CGameClient::ConReadyChange(IConsole::IResult *pResult, void *pUserData)\n{\n\t((CGameClient*)pUserData)->SendReadyChange();\n}\n\nvoid CGameClient::ConchainFriendUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)\n{\n\tpfnCallback(pResult, pCallbackUserData);\n\tCGameClient *pClient = static_cast<CGameClient *>(pUserData);\n\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t{\n\t\tif(pClient->m_aClients[i].m_Active)\n\t\t\tpClient->m_aClients[i].m_Friend = pClient->Friends()->IsFriend(pClient->m_aClients[i].m_aName, pClient->m_aClients[i].m_aClan, true);\n\t}\n}\n\nIGameClient *CreateGameClient()\n{\n\treturn new CGameClient();\n}\n"
  },
  {
    "path": "src/game/client/gameclient.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_GAMECLIENT_H\n#define GAME_CLIENT_GAMECLIENT_H\n\n#include <base/vmath.h>\n#include <engine/client.h>\n#include <engine/console.h>\n#include <game/layers.h>\n#include <game/gamecore.h>\n#include \"render.h\"\n\nclass CGameClient : public IGameClient\n{\n\tclass CStack\n\t{\n\tpublic:\n\t\tenum\n\t\t{\n\t\t\tMAX_COMPONENTS = 64,\n\t\t};\n\n\t\tCStack();\n\t\tvoid Add(class CComponent *pComponent);\n\n\t\tclass CComponent *m_paComponents[MAX_COMPONENTS];\n\t\tint m_Num;\n\t};\n\n\tCStack m_All;\n\tCStack m_Input;\n\tCNetObjHandler m_NetObjHandler;\n\n\tclass IEngine *m_pEngine;\n\tclass IInput *m_pInput;\n\tclass IGraphics *m_pGraphics;\n\tclass ITextRender *m_pTextRender;\n\tclass IClient *m_pClient;\n\tclass ISound *m_pSound;\n\tclass IConsole *m_pConsole;\n\tclass IStorage *m_pStorage;\n\tclass IDemoPlayer *m_pDemoPlayer;\n\tclass IDemoRecorder *m_pDemoRecorder;\n\tclass IServerBrowser *m_pServerBrowser;\n\tclass IEditor *m_pEditor;\n\tclass IFriends *m_pFriends;\n\n\tCLayers m_Layers;\n\tclass CCollision m_Collision;\n\tCUI m_UI;\n\n\tvoid DispatchInput();\n\tvoid ProcessEvents();\n\tvoid ProcessTriggeredEvents(int Events, vec2 Pos);\n\tvoid UpdatePositions();\n\n\tint m_PredictedTick;\n\tint m_LastNewPredictedTick;\n\n\tstatic void ConKill(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConReadyChange(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConchainFriendUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData);\n\n\n\tvoid EvolveCharacter(CNetObj_Character *pCharacter, int Tick);\n\npublic:\n\tIKernel *Kernel() { return IInterface::Kernel(); }\n\tIEngine *Engine() const { return m_pEngine; }\n\tclass IGraphics *Graphics() const { return m_pGraphics; }\n\tclass IClient *Client() const { return m_pClient; }\n\tclass CUI *UI() { return &m_UI; }\n\tclass ISound *Sound() const { return m_pSound; }\n\tclass IInput *Input() const { return m_pInput; }\n\tclass IStorage *Storage() const { return m_pStorage; }\n\tclass IConsole *Console() { return m_pConsole; }\n\tclass ITextRender *TextRender() const { return m_pTextRender; }\n\tclass IDemoPlayer *DemoPlayer() const { return m_pDemoPlayer; }\n\tclass IDemoRecorder *DemoRecorder() const { return m_pDemoRecorder; }\n\tclass IServerBrowser *ServerBrowser() const { return m_pServerBrowser; }\n\tclass CRenderTools *RenderTools() { return &m_RenderTools; }\n\tclass CLayers *Layers() { return &m_Layers; };\n\tclass CCollision *Collision() { return &m_Collision; };\n\tclass IEditor *Editor() { return m_pEditor; }\n\tclass IFriends *Friends() { return m_pFriends; }\n\n\tint NetobjNumCorrections() { return m_NetObjHandler.NumObjCorrections(); }\n\tconst char *NetobjCorrectedOn() { return m_NetObjHandler.CorrectedObjOn(); }\n\n\tbool m_SuppressEvents;\n\n\t// TODO: move this\n\tCTuningParams m_Tuning;\n\n\tenum\n\t{\n\t\tSERVERMODE_PURE=0,\n\t\tSERVERMODE_MOD,\n\t\tSERVERMODE_PUREMOD,\n\t};\n\tint m_ServerMode;\n\n\tint m_DemoSpecID;\n\n\tvec2 m_LocalCharacterPos;\n\n\t// predicted players\n\tCCharacterCore m_PredictedPrevChar;\n\tCCharacterCore m_PredictedChar;\n\n\tstruct CPlayerInfoItem\n\t{\n\t\tconst CNetObj_PlayerInfo *m_pPlayerInfo;\n\t\tint m_ClientID;\n\t};\n\n\t// snap pointers\n\tstruct CSnapState\n\t{\n\t\tconst CNetObj_Character *m_pLocalCharacter;\n\t\tconst CNetObj_Character *m_pLocalPrevCharacter;\n\t\tconst CNetObj_PlayerInfo *m_pLocalInfo;\n\t\tconst CNetObj_SpectatorInfo *m_pSpectatorInfo;\n\t\tconst CNetObj_SpectatorInfo *m_pPrevSpectatorInfo;\n\t\tconst CNetObj_Flag *m_paFlags[2];\n\t\tconst CNetObj_GameData *m_pGameData;\n\t\tconst CNetObj_GameDataTeam *m_pGameDataTeam;\n\t\tconst CNetObj_GameDataFlag *m_pGameDataFlag;\n\t\tint m_GameDataFlagSnapID;\n\t\t\n\t\tint m_NotReadyCount;\n\t\tint m_AliveCount[NUM_TEAMS];\n\n\t\tconst CNetObj_PlayerInfo *m_paPlayerInfos[MAX_CLIENTS];\n\t\tCPlayerInfoItem m_aInfoByScore[MAX_CLIENTS];\n\n\t\t// spectate data\n\t\tstruct CSpectateInfo\n\t\t{\n\t\t\tbool m_Active;\n\t\t\tint m_SpectatorID;\n\t\t\tbool m_UsePosition;\n\t\t\tvec2 m_Position;\n\t\t} m_SpecInfo;\n\n\t\t//\n\t\tstruct CCharacterInfo\n\t\t{\n\t\t\tbool m_Active;\n\n\t\t\t// snapshots\n\t\t\tCNetObj_Character m_Prev;\n\t\t\tCNetObj_Character m_Cur;\n\n\t\t\t// interpolated position\n\t\t\tvec2 m_Position;\n\t\t};\n\n\t\tCCharacterInfo m_aCharacters[MAX_CLIENTS];\n\t};\n\n\tCSnapState m_Snap;\n\n\t// client data\n\tstruct CClientData\n\t{\n\t\tchar m_aName[MAX_NAME_LENGTH];\n\t\tchar m_aClan[MAX_CLAN_LENGTH];\n\t\tint m_Country;\n\t\tchar m_aaSkinPartNames[6][24];\n\t\tint m_aUseCustomColors[6];\n\t\tint m_aSkinPartColors[6];\n\t\tint m_SkinPartIDs[6];\n\t\tint m_Team;\n\t\tint m_Emoticon;\n\t\tint m_EmoticonStart;\n\t\tCCharacterCore m_Predicted;\n\n\t\tCTeeRenderInfo m_SkinInfo; // this is what the server reports\n\t\tCTeeRenderInfo m_RenderInfo; // this is what we use\n\n\t\tfloat m_Angle;\n\t\tbool m_Active;\n\t\tbool m_ChatIgnore;\n\t\tbool m_Friend;\n\n\t\tvoid UpdateRenderInfo(CGameClient *pGameClient, bool UpdateSkinInfo);\n\t\tvoid Reset(CGameClient *pGameClient);\n\t};\n\n\tCClientData m_aClients[MAX_CLIENTS];\n\tint m_LocalClientID;\n\tint m_TeamCooldownTick;\n\n\tstruct CGameInfo\n\t{\n\t\tint m_GameFlags;\n\t\tint m_ScoreLimit;\n\t\tint m_TimeLimit;\n\t\tint m_MatchNum;\n\t\tint m_MatchCurrent;\n\n\t\tint m_NumPlayers;\n\t\tint m_aTeamSize[NUM_TEAMS];\n\t};\n\n\tCGameInfo m_GameInfo;\n\n\tstruct CServerSettings\n\t{\n\t\tbool m_KickVote;\n\t\tint m_KickMin;\n\t\tbool m_SpecVote;\n\t\tbool m_TeamLock;\n\t\tbool m_TeamBalance;\n\t\tint m_PlayerSlots;\n\t} m_ServerSettings;\n\n\tCRenderTools m_RenderTools;\n\n\tvoid OnReset();\n\n\t// hooks\n\tvirtual void OnConnected();\n\tvirtual void OnRender();\n\tvirtual void OnRelease();\n\tvirtual void OnInit();\n\tvirtual void OnConsoleInit();\n\tvirtual void OnStateChange(int NewState, int OldState);\n\tvirtual void OnMessage(int MsgId, CUnpacker *pUnpacker);\n\tvirtual void OnNewSnapshot();\n\tvirtual void OnDemoRecSnap();\n\tvirtual void OnPredict();\n\tvirtual void OnActivateEditor();\n\tvirtual int OnSnapInput(int *pData);\n\tvirtual void OnShutdown();\n\tvirtual void OnEnterGame();\n\tvirtual void OnRconLine(const char *pLine);\n\tvirtual void OnGameOver();\n\tvirtual void OnStartGame();\n\n\tvirtual const char *GetItemName(int Type);\n\tvirtual const char *Version();\n\tvirtual const char *NetVersion();\n\tconst char *GetTeamName(int Team, bool Teamplay) const;\n\n\t//\n\tvoid DoEnterMessage(const char *pName, int Team);\n\tvoid DoLeaveMessage(const char *pName, const char *pReason);\n\tvoid DoTeamChangeMessage(const char *pName, int Team);\n\n\t// actions\n\t// TODO: move these\n\tvoid SendSwitchTeam(int Team);\n\tvoid SendStartInfo();\n\tvoid SendKill();\n\tvoid SendReadyChange();\n\n\t// pointers to all systems\n\tclass CGameConsole *m_pGameConsole;\n\tclass CBinds *m_pBinds;\n\tclass CBroadcast *m_pBroadcast;\n\tclass CParticles *m_pParticles;\n\tclass CMenus *m_pMenus;\n\tclass CSkins *m_pSkins;\n\tclass CCountryFlags *m_pCountryFlags;\n\tclass CFlow *m_pFlow;\n\tclass CChat *m_pChat;\n\tclass CDamageInd *m_pDamageind;\n\tclass CCamera *m_pCamera;\n\tclass CControls *m_pControls;\n\tclass CEffects *m_pEffects;\n\tclass CSounds *m_pSounds;\n\tclass CMotd *m_pMotd;\n\tclass CMapImages *m_pMapimages;\n\tclass CVoting *m_pVoting;\n\tclass CScoreboard *m_pScoreboard;\n\tclass CItems *m_pItems;\n\tclass CMapLayers *m_pMapLayersBackGround;\n\tclass CMapLayers *m_pMapLayersForeGround;\n};\n\n\ninline float HueToRgb(float v1, float v2, float h)\n{\n\tif(h < 0.0f) h += 1;\n\tif(h > 1.0f) h -= 1;\n\tif((6.0f * h) < 1.0f) return v1 + (v2 - v1) * 6.0f * h;\n\tif((2.0f * h) < 1.0f) return v2;\n\tif((3.0f * h) < 2.0f) return v1 + (v2 - v1) * ((2.0f/3.0f) - h) * 6.0f;\n\treturn v1;\n}\n\ninline vec3 HslToRgb(vec3 HSL)\n{\n\tif(HSL.s == 0.0f)\n\t\treturn vec3(HSL.l, HSL.l, HSL.l);\n\telse\n\t{\n\t\tfloat v2 = HSL.l < 0.5f ? HSL.l * (1.0f + HSL.s) : (HSL.l+HSL.s) - (HSL.s*HSL.l);\n\t\tfloat v1 = 2.0f * HSL.l - v2;\n\n\t\treturn vec3(HueToRgb(v1, v2, HSL.h + (1.0f/3.0f)), HueToRgb(v1, v2, HSL.h), HueToRgb(v1, v2, HSL.h - (1.0f/3.0f)));\n\t}\n}\n\n\nextern const char *Localize(const char *Str, const char *pContext=\"\");\n\n#endif\n"
  },
  {
    "path": "src/game/client/lineinput.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/keys.h>\n#include \"lineinput.h\"\n\nCLineInput::CLineInput()\n{\n\tClear();\n}\n\nvoid CLineInput::Clear()\n{\n\tmem_zero(m_Str, sizeof(m_Str));\n\tm_Len = 0;\n\tm_CursorPos = 0;\n}\n\nvoid CLineInput::Set(const char *pString)\n{\n\tstr_copy(m_Str, pString, sizeof(m_Str));\n\tm_Len = str_length(m_Str);\n\tm_CursorPos = m_Len;\n}\n\nbool CLineInput::Manipulate(IInput::CEvent e, char *pStr, int StrMaxSize, int *pStrLenPtr, int *pCursorPosPtr)\n{\n\tint CursorPos = *pCursorPosPtr;\n\tint Len = *pStrLenPtr;\n\tbool Changes = false;\n\n\tif(CursorPos > Len)\n\t\tCursorPos = Len;\n\n\tint Code = e.m_Unicode;\n\tint k = e.m_Key;\n\n\t// 127 is produced on Mac OS X and corresponds to the delete key\n\tif (!(Code >= 0 && Code < 32) && Code != 127)\n\t{\n\t\tchar Tmp[8];\n\t\tint CharSize = str_utf8_encode(Tmp, Code);\n\n\t\tif (Len < StrMaxSize - CharSize && CursorPos < StrMaxSize - CharSize)\n\t\t{\n\t\t\tmem_move(pStr + CursorPos + CharSize, pStr + CursorPos, Len-CursorPos+1); // +1 == null term\n\t\t\tfor(int i = 0; i < CharSize; i++)\n\t\t\t\tpStr[CursorPos+i] = Tmp[i];\n\t\t\tCursorPos += CharSize;\n\t\t\tLen += CharSize;\n\t\t\tChanges = true;\n\t\t}\n\t}\n\n\tif(e.m_Flags&IInput::FLAG_PRESS)\n\t{\n\t\tif (k == KEY_BACKSPACE && CursorPos > 0)\n\t\t{\n\t\t\tint NewCursorPos = str_utf8_rewind(pStr, CursorPos);\n\t\t\tint CharSize = CursorPos-NewCursorPos;\n\t\t\tmem_move(pStr+NewCursorPos, pStr+CursorPos, Len - NewCursorPos - CharSize + 1); // +1 == null term\n\t\t\tCursorPos = NewCursorPos;\n\t\t\tLen -= CharSize;\n\t\t\tChanges = true;\n\t\t}\n\t\telse if (k == KEY_DELETE && CursorPos < Len)\n\t\t{\n\t\t\tint p = str_utf8_forward(pStr, CursorPos);\n\t\t\tint CharSize = p-CursorPos;\n\t\t\tmem_move(pStr + CursorPos, pStr + CursorPos + CharSize, Len - CursorPos - CharSize + 1); // +1 == null term\n\t\t\tLen -= CharSize;\n\t\t\tChanges = true;\n\t\t}\n\t\telse if (k == KEY_LEFT && CursorPos > 0)\n\t\t\tCursorPos = str_utf8_rewind(pStr, CursorPos);\n\t\telse if (k == KEY_RIGHT && CursorPos < Len)\n\t\t\tCursorPos = str_utf8_forward(pStr, CursorPos);\n\t\telse if (k == KEY_HOME)\n\t\t\tCursorPos = 0;\n\t\telse if (k == KEY_END)\n\t\t\tCursorPos = Len;\n\t}\n\n\t*pCursorPosPtr = CursorPos;\n\t*pStrLenPtr = Len;\n\n\treturn Changes;\n}\n\nvoid CLineInput::ProcessInput(IInput::CEvent e)\n{\n\tManipulate(e, m_Str, sizeof(m_Str), &m_Len, &m_CursorPos);\n}\n"
  },
  {
    "path": "src/game/client/lineinput.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_LINEINPUT_H\n#define GAME_CLIENT_LINEINPUT_H\n\n#include <engine/input.h>\n\n// line input helter\nclass CLineInput\n{\n\tchar m_Str[256];\n\tint m_Len;\n\tint m_CursorPos;\npublic:\n\tstatic bool Manipulate(IInput::CEvent e, char *pStr, int StrMaxSize, int *pStrLenPtr, int *pCursorPosPtr);\n\n\tclass CCallback\n\t{\n\tpublic:\n\t\tvirtual ~CCallback() {}\n\t\tvirtual bool Event(IInput::CEvent e) = 0;\n\t};\n\n\tCLineInput();\n\tvoid Clear();\n\tvoid ProcessInput(IInput::CEvent e);\n\tvoid Set(const char *pString);\n\tconst char *GetString() const { return m_Str; }\n\tint GetLength() const { return m_Len; }\n\tint GetCursorOffset() const { return m_CursorPos; }\n\tvoid SetCursorOffset(int Offset) { m_CursorPos = Offset > m_Len ? m_Len : Offset < 0 ? 0 : Offset; }\n};\n\n#endif\n"
  },
  {
    "path": "src/game/client/localization.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n\n#include \"localization.h\"\n#include <base/tl/algorithm.h>\n\n#include <engine/external/json-parser/json.h>\n#include <engine/console.h>\n#include <engine/storage.h>\n\nconst char *Localize(const char *pStr, const char *pContext)\n{\n\tconst char *pNewStr = g_Localization.FindString(str_quickhash(pStr), str_quickhash(pContext));\n\treturn pNewStr ? pNewStr : pStr;\n}\n\nCLocConstString::CLocConstString(const char *pStr, const char *pContext)\n{\n\tm_pDefaultStr = pStr;\n\tm_Hash = str_quickhash(m_pDefaultStr);\n\tm_ContextHash = str_quickhash(pContext);\n\tm_Version = -1;\n}\n\nvoid CLocConstString::Reload()\n{\n\tm_Version = g_Localization.Version();\n\tconst char *pNewStr = g_Localization.FindString(m_Hash, m_ContextHash);\n\tm_pCurrentStr = pNewStr;\n\tif(!m_pCurrentStr)\n\t\tm_pCurrentStr = m_pDefaultStr;\n}\n\nCLocalizationDatabase::CLocalizationDatabase()\n{\n\tm_VersionCounter = 0;\n\tm_CurrentVersion = 0;\n}\n\nvoid CLocalizationDatabase::AddString(const char *pOrgStr, const char *pNewStr, const char *pContext)\n{\n\tCString s;\n\ts.m_Hash = str_quickhash(pOrgStr);\n\ts.m_ContextHash = str_quickhash(pContext);\n\ts.m_Replacement = *pNewStr ? pNewStr : pOrgStr;\n\tm_Strings.add(s);\n}\n\nbool CLocalizationDatabase::Load(const char *pFilename, IStorage *pStorage, IConsole *pConsole)\n{\n\t// empty string means unload\n\tif(pFilename[0] == 0)\n\t{\n\t\tm_Strings.clear();\n\t\tm_CurrentVersion = 0;\n\t\treturn true;\n\t}\n\n\t// read file data into buffer\n\tIOHANDLE File = pStorage->OpenFile(pFilename, IOFLAG_READ, IStorage::TYPE_ALL);\n\tif(!File)\n\t\treturn false;\n\tint FileSize = (int)io_length(File);\n\tchar *pFileData = (char *)mem_alloc(FileSize+1, 1);\n\tio_read(File, pFileData, FileSize);\n\tpFileData[FileSize] = 0;\n\tio_close(File);\n\n\t// init\n\tchar aBuf[64];\n\tstr_format(aBuf, sizeof(aBuf), \"loaded '%s'\", pFilename);\n\tpConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"localization\", aBuf);\n\tm_Strings.clear();\n\n\t// parse json data\n\tjson_settings JsonSettings;\n\tmem_zero(&JsonSettings, sizeof(JsonSettings));\n\tchar aError[256];\n\tjson_value *pJsonData = json_parse_ex(&JsonSettings, pFileData, aError);\n\tif(pJsonData == 0)\n\t{\n\t\tpConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, pFilename, aError);\n\t\tmem_free(pFileData);\n\t\treturn false;\n\t}\n\n\t// extract data\n\tconst json_value &rStart = (*pJsonData)[\"translated strings\"];\n\tif(rStart.type == json_array)\n\t{\n\t\tfor(unsigned i = 0; i < rStart.u.array.length; ++i)\n\t\t\tAddString((const char *)rStart[i][\"or\"], (const char *)rStart[i][\"tr\"], (const char *)rStart[i][\"context\"]);\n\t}\n\n\t// clean up\n\tjson_value_free(pJsonData);\n\tmem_free(pFileData);\n\tm_CurrentVersion = ++m_VersionCounter;\n\treturn true;\n}\n\nconst char *CLocalizationDatabase::FindString(unsigned Hash, unsigned ContextHash)\n{\n\tCString String;\n\tString.m_Hash = Hash;\n\tsorted_array<CString>::range r = ::find_binary(m_Strings.all(), String);\n\tif(r.empty())\n\t\treturn 0;\n\n\tunsigned DefaultHash = str_quickhash(\"\");\n\tunsigned DefaultIndex = 0;\n\tfor(unsigned i = 0; i < r.size(); ++i)\n\t{\n\t\tconst CString &rStr = r.index(i);\n\t\tif(rStr.m_ContextHash == ContextHash)\n\t\t\treturn rStr.m_Replacement;\n\t\telse if(rStr.m_ContextHash == DefaultHash)\n\t\t\tDefaultIndex = i;\n\t}\n\t\n    return r.index(DefaultIndex).m_Replacement;\n}\n\nCLocalizationDatabase g_Localization;\n"
  },
  {
    "path": "src/game/client/localization.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_LOCALIZATION_H\n#define GAME_LOCALIZATION_H\n#include <base/tl/string.h>\n#include <base/tl/sorted_array.h>\n\nclass CLocalizationDatabase\n{\n\tclass CString\n\t{\n\tpublic:\n\t\tunsigned m_Hash;\n\t\tunsigned m_ContextHash;\n\n\t\t// TODO: do this as an const char * and put everything on a incremental heap\n\t\tstring m_Replacement;\n\n\t\tbool operator <(const CString &Other) const { return m_Hash < Other.m_Hash; }\n\t\tbool operator <=(const CString &Other) const { return m_Hash <= Other.m_Hash; }\n\t\tbool operator ==(const CString &Other) const { return m_Hash == Other.m_Hash; }\n\t};\n\n\tsorted_array<CString> m_Strings;\n\tint m_VersionCounter;\n\tint m_CurrentVersion;\n\npublic:\n\tCLocalizationDatabase();\n\n\tbool Load(const char *pFilename, class IStorage *pStorage, class IConsole *pConsole);\n\n\tint Version() { return m_CurrentVersion; }\n\n\tvoid AddString(const char *pOrgStr, const char *pNewStr, const char *pContext);\n\tconst char *FindString(unsigned Hash, unsigned ContextHash);\n};\n\nextern CLocalizationDatabase g_Localization;\n\nclass CLocConstString\n{\n\tconst char *m_pDefaultStr;\n\tconst char *m_pCurrentStr;\n\tunsigned m_Hash;\n\tunsigned m_ContextHash;\n\tint m_Version;\npublic:\n\tCLocConstString(const char *pStr, const char *pContext=\"\");\n\tvoid Reload();\n\n\tinline operator const char *()\n\t{\n\t\tif(m_Version != g_Localization.Version())\n\t\t\tReload();\n\t\treturn m_pCurrentStr;\n\t}\n};\n\nextern const char *Localize(const char *pStr, const char *pContext);\n#endif\n"
  },
  {
    "path": "src/game/client/render.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <math.h>\n\n#include <base/math.h>\n\n#include <engine/shared/config.h>\n#include <engine/graphics.h>\n#include <engine/map.h>\n#include <game/generated/client_data.h>\n#include <game/generated/protocol.h>\n#include <game/layers.h>\n#include \"animstate.h\"\n#include \"render.h\"\n\nstatic float gs_SpriteWScale;\nstatic float gs_SpriteHScale;\n\n\n/*\nstatic void layershot_begin()\n{\n\tif(!config.cl_layershot)\n\t\treturn;\n\n\tGraphics()->Clear(0,0,0);\n}\n\nstatic void layershot_end()\n{\n\tif(!config.cl_layershot)\n\t\treturn;\n\n\tchar buf[256];\n\tstr_format(buf, sizeof(buf), \"screenshots/layers_%04d.png\", config.cl_layershot);\n\tgfx_screenshot_direct(buf);\n\tconfig.cl_layershot++;\n}*/\n\nvoid CRenderTools::SelectSprite(CDataSprite *pSpr, int Flags, int sx, int sy)\n{\n\tint x = pSpr->m_X+sx;\n\tint y = pSpr->m_Y+sy;\n\tint w = pSpr->m_W;\n\tint h = pSpr->m_H;\n\tint cx = pSpr->m_pSet->m_Gridx;\n\tint cy = pSpr->m_pSet->m_Gridy;\n\n\tfloat f = sqrtf(h*h + w*w);\n\tgs_SpriteWScale = w/f;\n\tgs_SpriteHScale = h/f;\n\n\tfloat x1 = x/(float)cx;\n\tfloat x2 = (x+w)/(float)cx;\n\tfloat y1 = y/(float)cy;\n\tfloat y2 = (y+h)/(float)cy;\n\tfloat Temp = 0;\n\n\tif(Flags&SPRITE_FLAG_FLIP_Y)\n\t{\n\t\tTemp = y1;\n\t\ty1 = y2;\n\t\ty2 = Temp;\n\t}\n\n\tif(Flags&SPRITE_FLAG_FLIP_X)\n\t{\n\t\tTemp = x1;\n\t\tx1 = x2;\n\t\tx2 = Temp;\n\t}\n\n\tGraphics()->QuadsSetSubset(x1, y1, x2, y2);\n}\n\nvoid CRenderTools::SelectSprite(int Id, int Flags, int sx, int sy)\n{\n\tif(Id < 0 || Id >= g_pData->m_NumSprites)\n\t\treturn;\n\tSelectSprite(&g_pData->m_aSprites[Id], Flags, sx, sy);\n}\n\nvoid CRenderTools::DrawSprite(float x, float y, float Size)\n{\n\tIGraphics::CQuadItem QuadItem(x, y, Size*gs_SpriteWScale, Size*gs_SpriteHScale);\n\tGraphics()->QuadsDraw(&QuadItem, 1);\n}\n\nvoid CRenderTools::DrawRoundRectExt(float x, float y, float w, float h, float r, int Corners)\n{\n\tIGraphics::CFreeformItem ArrayF[32];\n\tint NumItems = 0;\n\tint Num = 8;\n\tfor(int i = 0; i < Num; i+=2)\n\t{\n\t\tfloat a1 = i/(float)Num * pi/2;\n\t\tfloat a2 = (i+1)/(float)Num * pi/2;\n\t\tfloat a3 = (i+2)/(float)Num * pi/2;\n\t\tfloat Ca1 = cosf(a1);\n\t\tfloat Ca2 = cosf(a2);\n\t\tfloat Ca3 = cosf(a3);\n\t\tfloat Sa1 = sinf(a1);\n\t\tfloat Sa2 = sinf(a2);\n\t\tfloat Sa3 = sinf(a3);\n\n\t\tif(Corners&1) // TL\n\t\t\tArrayF[NumItems++] = IGraphics::CFreeformItem(\n\t\t\tx+r, y+r,\n\t\t\tx+(1-Ca1)*r, y+(1-Sa1)*r,\n\t\t\tx+(1-Ca3)*r, y+(1-Sa3)*r,\n\t\t\tx+(1-Ca2)*r, y+(1-Sa2)*r);\n\n\t\tif(Corners&2) // TR\n\t\tArrayF[NumItems++] = IGraphics::CFreeformItem(\n\t\t\tx+w-r, y+r,\n\t\t\tx+w-r+Ca1*r, y+(1-Sa1)*r,\n\t\t\tx+w-r+Ca3*r, y+(1-Sa3)*r,\n\t\t\tx+w-r+Ca2*r, y+(1-Sa2)*r);\n\n\t\tif(Corners&4) // BL\n\t\tArrayF[NumItems++] = IGraphics::CFreeformItem(\n\t\t\tx+r, y+h-r,\n\t\t\tx+(1-Ca1)*r, y+h-r+Sa1*r,\n\t\t\tx+(1-Ca3)*r, y+h-r+Sa3*r,\n\t\t\tx+(1-Ca2)*r, y+h-r+Sa2*r);\n\n\t\tif(Corners&8) // BR\n\t\tArrayF[NumItems++] = IGraphics::CFreeformItem(\n\t\t\tx+w-r, y+h-r,\n\t\t\tx+w-r+Ca1*r, y+h-r+Sa1*r,\n\t\t\tx+w-r+Ca3*r, y+h-r+Sa3*r,\n\t\t\tx+w-r+Ca2*r, y+h-r+Sa2*r);\n\n\t\tif(Corners&16) // ITL\n\t\tArrayF[NumItems++] = IGraphics::CFreeformItem(\n\t\t\tx, y,\n\t\t\tx+(1-Ca1)*r, y-r+Sa1*r,\n\t\t\tx+(1-Ca3)*r, y-r+Sa3*r,\n\t\t\tx+(1-Ca2)*r, y-r+Sa2*r);\n\t\n\t\tif(Corners&32) // ITR\n\t\tArrayF[NumItems++] = IGraphics::CFreeformItem(\n\t\t\tx+w, y,\n\t\t\tx+w-r+Ca1*r, y-r+Sa1*r,\n\t\t\tx+w-r+Ca3*r, y-r+Sa3*r,\n\t\t\tx+w-r+Ca2*r, y-r+Sa2*r);\n\t\n\t\tif(Corners&64) // IBL\n\t\tArrayF[NumItems++] = IGraphics::CFreeformItem(\n\t\t\tx, y+h,\n\t\t\tx+(1-Ca1)*r, y+h+(1-Sa1)*r,\n\t\t\tx+(1-Ca3)*r, y+h+(1-Sa3)*r,\n\t\t\tx+(1-Ca2)*r, y+h+(1-Sa2)*r);\n\n\t\tif(Corners&128) // IBR\n\t\tArrayF[NumItems++] = IGraphics::CFreeformItem(\n\t\t\tx+w, y+h,\n\t\t\tx+w-r+Ca1*r, y+h+(1-Sa1)*r,\n\t\t\tx+w-r+Ca3*r, y+h+(1-Sa3)*r,\n\t\t\tx+w-r+Ca2*r, y+h+(1-Sa2)*r);\n\t}\n\tGraphics()->QuadsDrawFreeform(ArrayF, NumItems);\n\n\tIGraphics::CQuadItem ArrayQ[9];\n\tNumItems = 0;\n\tArrayQ[NumItems++] = IGraphics::CQuadItem(x+r, y+r, w-r*2, h-r*2); // center\n\tArrayQ[NumItems++] = IGraphics::CQuadItem(x+r, y, w-r*2, r); // top\n\tArrayQ[NumItems++] = IGraphics::CQuadItem(x+r, y+h-r, w-r*2, r); // bottom\n\tArrayQ[NumItems++] = IGraphics::CQuadItem(x, y+r, r, h-r*2); // left\n\tArrayQ[NumItems++] = IGraphics::CQuadItem(x+w-r, y+r, r, h-r*2); // right\n\n\tif(!(Corners&1)) ArrayQ[NumItems++] = IGraphics::CQuadItem(x, y, r, r); // TL\n\tif(!(Corners&2)) ArrayQ[NumItems++] = IGraphics::CQuadItem(x+w, y, -r, r); // TR\n\tif(!(Corners&4)) ArrayQ[NumItems++] = IGraphics::CQuadItem(x, y+h, r, -r); // BL\n\tif(!(Corners&8)) ArrayQ[NumItems++] = IGraphics::CQuadItem(x+w, y+h, -r, -r); // BR\n\n\tGraphics()->QuadsDrawTL(ArrayQ, NumItems);\n}\n\nvoid CRenderTools::DrawRoundRectExt4(float x, float y, float w, float h, vec4 ColorTopLeft, vec4 ColorTopRight, vec4 ColorBottomLeft, vec4 ColorBottomRight, float r, int Corners)\n{\n\tint Num = 8;\n\tfor(int i = 0; i < Num; i+=2)\n\t{\n\t\tfloat a1 = i/(float)Num * pi/2;\n\t\tfloat a2 = (i+1)/(float)Num * pi/2;\n\t\tfloat a3 = (i+2)/(float)Num * pi/2;\n\t\tfloat Ca1 = cosf(a1);\n\t\tfloat Ca2 = cosf(a2);\n\t\tfloat Ca3 = cosf(a3);\n\t\tfloat Sa1 = sinf(a1);\n\t\tfloat Sa2 = sinf(a2);\n\t\tfloat Sa3 = sinf(a3);\n\n\t\tif(Corners&1) // TL\n\t\t{\n\t\t\tGraphics()->SetColor(ColorTopLeft.r, ColorTopLeft.g, ColorTopLeft.b, ColorTopLeft.a);\n\t\t\tIGraphics::CFreeformItem ItemF = IGraphics::CFreeformItem(\n\t\t\t\t\t\t\t\t\tx+r, y+r,\n\t\t\t\t\t\t\t\t\tx+(1-Ca1)*r, y+(1-Sa1)*r,\n\t\t\t\t\t\t\t\t\tx+(1-Ca3)*r, y+(1-Sa3)*r,\n\t\t\t\t\t\t\t\t\tx+(1-Ca2)*r, y+(1-Sa2)*r);\n\t\t\tGraphics()->QuadsDrawFreeform(&ItemF, 1);\n\t\t}\n\n\t\tif(Corners&2) // TR\n\t\t{\n\t\t\tGraphics()->SetColor(ColorTopRight.r, ColorTopRight.g, ColorTopRight.b, ColorTopRight.a);\n\t\t\tIGraphics::CFreeformItem ItemF = IGraphics::CFreeformItem(\n\t\t\t\t\t\t\t\t\tx+w-r, y+r,\n\t\t\t\t\t\t\t\t\tx+w-r+Ca1*r, y+(1-Sa1)*r,\n\t\t\t\t\t\t\t\t\tx+w-r+Ca3*r, y+(1-Sa3)*r,\n\t\t\t\t\t\t\t\t\tx+w-r+Ca2*r, y+(1-Sa2)*r);\n\t\t\tGraphics()->QuadsDrawFreeform(&ItemF, 1);\n\t\t}\n\n\t\tif(Corners&4) // BL\n\t\t{\n\t\t\tGraphics()->SetColor(ColorBottomLeft.r, ColorBottomLeft.g, ColorBottomLeft.b, ColorBottomLeft.a);\n\t\t\tIGraphics::CFreeformItem ItemF = IGraphics::CFreeformItem(\n\t\t\t\t\t\t\t\t\tx+r, y+h-r,\n\t\t\t\t\t\t\t\t\tx+(1-Ca1)*r, y+h-r+Sa1*r,\n\t\t\t\t\t\t\t\t\tx+(1-Ca3)*r, y+h-r+Sa3*r,\n\t\t\t\t\t\t\t\t\tx+(1-Ca2)*r, y+h-r+Sa2*r);\n\t\t\tGraphics()->QuadsDrawFreeform(&ItemF, 1);\n\t\t}\n\n\t\tif(Corners&8) // BR\n\t\t{\n\t\t\tGraphics()->SetColor(ColorBottomRight.r, ColorBottomRight.g, ColorBottomRight.b, ColorBottomRight.a);\n\t\t\tIGraphics::CFreeformItem ItemF = IGraphics::CFreeformItem(\n\t\t\t\t\t\t\t\t\tx+w-r, y+h-r,\n\t\t\t\t\t\t\t\t\tx+w-r+Ca1*r, y+h-r+Sa1*r,\n\t\t\t\t\t\t\t\t\tx+w-r+Ca3*r, y+h-r+Sa3*r,\n\t\t\t\t\t\t\t\t\tx+w-r+Ca2*r, y+h-r+Sa2*r);\n\t\t\tGraphics()->QuadsDrawFreeform(&ItemF, 1);\n\t\t}\n\n\t\tif(Corners&16) // ITL\n\t\t{\n\t\t\tGraphics()->SetColor(ColorTopLeft.r, ColorTopLeft.g, ColorTopLeft.b, ColorTopLeft.a);\n\t\t\tIGraphics::CFreeformItem ItemF = IGraphics::CFreeformItem(\n\t\t\t\t\t\t\t\t\tx, y,\n\t\t\t\t\t\t\t\t\tx+(1-Ca1)*r, y-r+Sa1*r,\n\t\t\t\t\t\t\t\t\tx+(1-Ca3)*r, y-r+Sa3*r,\n\t\t\t\t\t\t\t\t\tx+(1-Ca2)*r, y-r+Sa2*r);\n\t\t\tGraphics()->QuadsDrawFreeform(&ItemF, 1);\n\t\t}\n\t\n\t\tif(Corners&32) // ITR\n\t\t{\n\t\t\tGraphics()->SetColor(ColorTopRight.r, ColorTopRight.g, ColorTopRight.b, ColorTopRight.a);\n\t\t\tIGraphics::CFreeformItem ItemF = IGraphics::CFreeformItem(\n\t\t\t\t\t\t\t\t\tx+w, y,\n\t\t\t\t\t\t\t\t\tx+w-r+Ca1*r, y-r+Sa1*r,\n\t\t\t\t\t\t\t\t\tx+w-r+Ca3*r, y-r+Sa3*r,\n\t\t\t\t\t\t\t\t\tx+w-r+Ca2*r, y-r+Sa2*r);\n\t\t\tGraphics()->QuadsDrawFreeform(&ItemF, 1);\n\t\t}\n\t\n\t\tif(Corners&64) // IBL\n\t\t{\n\t\t\tGraphics()->SetColor(ColorBottomLeft.r, ColorBottomLeft.g, ColorBottomLeft.b, ColorBottomLeft.a);\n\t\t\tIGraphics::CFreeformItem ItemF = IGraphics::CFreeformItem(\n\t\t\t\t\t\t\t\t\tx, y+h,\n\t\t\t\t\t\t\t\t\tx+(1-Ca1)*r, y+h+(1-Sa1)*r,\n\t\t\t\t\t\t\t\t\tx+(1-Ca3)*r, y+h+(1-Sa3)*r,\n\t\t\t\t\t\t\t\t\tx+(1-Ca2)*r, y+h+(1-Sa2)*r);\n\t\t\tGraphics()->QuadsDrawFreeform(&ItemF, 1);\n\t\t}\n\n\t\tif(Corners&128) // IBR\n\t\t{\n\t\t\tGraphics()->SetColor(ColorBottomRight.r, ColorBottomRight.g, ColorBottomRight.b, ColorBottomRight.a);\n\t\t\tIGraphics::CFreeformItem ItemF = IGraphics::CFreeformItem(\n\t\t\t\t\t\t\t\t\tx+w, y+h,\n\t\t\t\t\t\t\t\t\tx+w-r+Ca1*r, y+h+(1-Sa1)*r,\n\t\t\t\t\t\t\t\t\tx+w-r+Ca3*r, y+h+(1-Sa3)*r,\n\t\t\t\t\t\t\t\t\tx+w-r+Ca2*r, y+h+(1-Sa2)*r);\n\t\t\tGraphics()->QuadsDrawFreeform(&ItemF, 1);\n\t\t}\n\t}\n\n\tGraphics()->SetColor4(ColorTopLeft, ColorTopRight, ColorBottomLeft, ColorBottomRight);\n\tIGraphics::CQuadItem ItemQ = IGraphics::CQuadItem(x+r, y+r, w-r*2, h-r*2); // center\n\tGraphics()->QuadsDrawTL(&ItemQ, 1);\n\tGraphics()->SetColor4(ColorTopLeft, ColorTopRight, ColorTopLeft, ColorTopRight);\n\tItemQ = IGraphics::CQuadItem(x+r, y, w-r*2, r); // top\n\tGraphics()->QuadsDrawTL(&ItemQ, 1);\n\tGraphics()->SetColor4(ColorBottomLeft, ColorBottomRight, ColorBottomLeft, ColorBottomRight);\n\tItemQ = IGraphics::CQuadItem(x+r, y+h-r, w-r*2, r); // bottom\n\tGraphics()->QuadsDrawTL(&ItemQ, 1);\n\tGraphics()->SetColor4(ColorTopLeft, ColorTopLeft, ColorBottomLeft, ColorBottomLeft);\n\tItemQ = IGraphics::CQuadItem(x, y+r, r, h-r*2); // left\n\tGraphics()->QuadsDrawTL(&ItemQ, 1);\n\tGraphics()->SetColor4(ColorTopRight, ColorTopRight, ColorBottomRight, ColorBottomRight);\n\tItemQ = IGraphics::CQuadItem(x+w-r, y+r, r, h-r*2); // right\n\tGraphics()->QuadsDrawTL(&ItemQ, 1);\n\n\tif(!(Corners&1))\n\t{\n\t\tGraphics()->SetColor(ColorTopLeft.r, ColorTopLeft.g, ColorTopLeft.b, ColorTopLeft.a);\n\t\tIGraphics::CQuadItem ItemQ = IGraphics::CQuadItem(x, y, r, r); // TL\n\t\tGraphics()->QuadsDrawTL(&ItemQ, 1);\n\t}\n\tif(!(Corners&2))\n\t{\n\t\tGraphics()->SetColor(ColorTopRight.r, ColorTopRight.g, ColorTopRight.b, ColorTopRight.a);\n\t\tIGraphics::CQuadItem ItemQ = IGraphics::CQuadItem(x+w, y, -r, r); // TR\n\t\tGraphics()->QuadsDrawTL(&ItemQ, 1);\n\t}\n\tif(!(Corners&4))\n\t{\n\t\tGraphics()->SetColor(ColorBottomLeft.r, ColorBottomLeft.g, ColorBottomLeft.b, ColorBottomLeft.a);\n\t\tIGraphics::CQuadItem ItemQ = IGraphics::CQuadItem(x, y+h, r, -r); // BL\n\t\tGraphics()->QuadsDrawTL(&ItemQ, 1);\n\t}\n\tif(!(Corners&8))\n\t{\n\t\tGraphics()->SetColor(ColorBottomRight.r, ColorBottomRight.g, ColorBottomRight.b, ColorBottomRight.a);\n\t\tIGraphics::CQuadItem ItemQ = IGraphics::CQuadItem(x+w, y+h, -r, -r); // BR\n\t\tGraphics()->QuadsDrawTL(&ItemQ, 1);\n\t}\n}\n\nvoid CRenderTools::DrawRoundRect(float x, float y, float w, float h, float r)\n{\n\tDrawRoundRectExt(x,y,w,h,r,0xf);\n}\n\nvoid CRenderTools::DrawUIRect(const CUIRect *r, vec4 Color, int Corners, float Rounding)\n{\n\tGraphics()->TextureClear();\n\n\t// TODO: FIX US\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(Color.r, Color.g, Color.b, Color.a);\n\tDrawRoundRectExt(r->x,r->y,r->w,r->h,Rounding*UI()->Scale(), Corners);\n\tGraphics()->QuadsEnd();\n}\n\nvoid CRenderTools::DrawUIRect4(const CUIRect *r, vec4 ColorTopLeft, vec4 ColorTopRight, vec4 ColorBottomLeft, vec4 ColorBottomRight, int Corners, float Rounding)\n{\n\tGraphics()->TextureClear();\n\n\tGraphics()->QuadsBegin();\n\tDrawRoundRectExt4(r->x,r->y,r->w,r->h,ColorTopLeft,ColorTopRight,ColorBottomLeft,ColorBottomRight,Rounding*UI()->Scale(), Corners);\n\tGraphics()->QuadsEnd();\n}\n\nvoid CRenderTools::RenderTee(CAnimState *pAnim, CTeeRenderInfo *pInfo, int Emote, vec2 Dir, vec2 Pos)\n{\n\tvec2 Direction = Dir;\n\tvec2 Position = Pos;\n\n\t//Graphics()->TextureSet(data->images[IMAGE_CHAR_DEFAULT].id);\n\n\t// TODO: FIX ME\n\t//Graphics()->QuadsDraw(pos.x, pos.y-128, 128, 128);\n\n\t// first pass we draw the outline\n\t// second pass we draw the filling\n\tfor(int p = 0; p < 2; p++)\n\t{\n\t\tbool OutLine = p==0;\n\n\t\tfor(int f = 0; f < 2; f++)\n\t\t{\n\t\t\tfloat AnimScale = pInfo->m_Size * 1.0f/64.0f;\n\t\t\tfloat BaseSize = pInfo->m_Size;\n\t\t\tif(f == 1)\n\t\t\t{\n\t\t\t\tvec2 BodyPos = Position + vec2(pAnim->GetBody()->m_X, pAnim->GetBody()->m_Y)*AnimScale;\n\t\t\t\tIGraphics::CQuadItem BodyItem(BodyPos.x, BodyPos.y, BaseSize, BaseSize);\n\t\t\t\tIGraphics::CQuadItem Item;\n\n\t\t\t\t// draw decoration\n\t\t\t\tif(pInfo->m_aTextures[2].IsValid())\n\t\t\t\t{\n\t\t\t\t\tGraphics()->TextureSet(pInfo->m_aTextures[2]);\n\t\t\t\t\tGraphics()->QuadsBegin();\n\t\t\t\t\tGraphics()->QuadsSetRotation(pAnim->GetBody()->m_Angle*pi*2);\n\t\t\t\t\tGraphics()->SetColor(pInfo->m_aColors[2].r, pInfo->m_aColors[2].g, pInfo->m_aColors[2].b, pInfo->m_aColors[2].a);\n\t\t\t\t\tSelectSprite(OutLine?SPRITE_TEE_DECORATION_OUTLINE:SPRITE_TEE_DECORATION, 0, 0, 0);\n\t\t\t\t\tItem = BodyItem;\n\t\t\t\t\tGraphics()->QuadsDraw(&Item, 1);\n\t\t\t\t\tGraphics()->QuadsEnd();\n\t\t\t\t}\n\n\t\t\t\t// draw body (behind tattoo)\n\t\t\t\tGraphics()->TextureSet(pInfo->m_aTextures[0]);\n\t\t\t\tGraphics()->QuadsBegin();\n\t\t\t\tGraphics()->QuadsSetRotation(pAnim->GetBody()->m_Angle*pi*2);\n\t\t\t\tif(OutLine)\n\t\t\t\t{\n\t\t\t\t\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\t\t\tSelectSprite(SPRITE_TEE_BODY_OUTLINE, 0, 0, 0);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tGraphics()->SetColor(pInfo->m_aColors[0].r, pInfo->m_aColors[0].g, pInfo->m_aColors[0].b, pInfo->m_aColors[0].a);\n\t\t\t\t\tSelectSprite(SPRITE_TEE_BODY, 0, 0, 0);\n\t\t\t\t}\n\t\t\t\tItem = BodyItem;\n\t\t\t\tGraphics()->QuadsDraw(&Item, 1);\n\t\t\t\tGraphics()->QuadsEnd();\n\n\t\t\t\t// draw tattoo\n\t\t\t\tif(pInfo->m_aTextures[1].IsValid() && !OutLine)\n\t\t\t\t{\n\t\t\t\t\tGraphics()->TextureSet(pInfo->m_aTextures[1]);\n\t\t\t\t\tGraphics()->QuadsBegin();\n\t\t\t\t\tGraphics()->QuadsSetRotation(pAnim->GetBody()->m_Angle*pi*2);\n\t\t\t\t\tGraphics()->SetColor(pInfo->m_aColors[1].r, pInfo->m_aColors[1].g, pInfo->m_aColors[1].b, pInfo->m_aColors[1].a);\n\t\t\t\t\tSelectSprite(SPRITE_TEE_TATTOO, 0, 0, 0);\n\t\t\t\t\tItem = BodyItem;\n\t\t\t\t\tGraphics()->QuadsDraw(&Item, 1);\n\t\t\t\t\tGraphics()->QuadsEnd();\n\t\t\t\t}\n\n\t\t\t\t// draw body (in front of tattoo)\n\t\t\t\tif(!OutLine)\n\t\t\t\t{\n\t\t\t\t\tGraphics()->TextureSet(pInfo->m_aTextures[0]);\n\t\t\t\t\tGraphics()->QuadsBegin();\n\t\t\t\t\tGraphics()->QuadsSetRotation(pAnim->GetBody()->m_Angle*pi*2);\n\t\t\t\t\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\t\t\tfor(int t = 0; t < 2; t++)\n\t\t\t\t\t{\n\t\t\t\t\t\tSelectSprite(t==0?SPRITE_TEE_BODY_SHADOW:SPRITE_TEE_BODY_UPPER_OUTLINE, 0, 0, 0);\n\t\t\t\t\t\tItem = BodyItem;\n\t\t\t\t\t\tGraphics()->QuadsDraw(&Item, 1);\n\t\t\t\t\t}\n\t\t\t\t\tGraphics()->QuadsEnd();\n\t\t\t\t}\n\n\t\t\t\t// draw eyes\n\t\t\t\tGraphics()->TextureSet(pInfo->m_aTextures[5]);\n\t\t\t\tGraphics()->QuadsBegin();\n\t\t\t\tGraphics()->QuadsSetRotation(pAnim->GetBody()->m_Angle*pi*2);\n\t\t\t\tGraphics()->SetColor(pInfo->m_aColors[5].r, pInfo->m_aColors[5].g, pInfo->m_aColors[5].b, pInfo->m_aColors[5].a);\n\t\t\t\tif(p == 1)\n\t\t\t\t{\n\t\t\t\t\tswitch (Emote)\n\t\t\t\t\t{\n\t\t\t\t\t\tcase EMOTE_PAIN:\n\t\t\t\t\t\t\tSelectSprite(SPRITE_TEE_EYES_PAIN, 0, 0, 0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase EMOTE_HAPPY:\n\t\t\t\t\t\t\tSelectSprite(SPRITE_TEE_EYES_HAPPY, 0, 0, 0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase EMOTE_SURPRISE:\n\t\t\t\t\t\t\tSelectSprite(SPRITE_TEE_EYES_SURPRISE, 0, 0, 0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase EMOTE_ANGRY:\n\t\t\t\t\t\t\tSelectSprite(SPRITE_TEE_EYES_ANGRY, 0, 0, 0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tSelectSprite(SPRITE_TEE_EYES_NORMAL, 0, 0, 0);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat EyeScale = BaseSize*0.60f;\n\t\t\t\t\tfloat h = Emote == EMOTE_BLINK ? BaseSize*0.15f/2.0f : EyeScale/2.0f;\n\t\t\t\t\tvec2 Offset = vec2(Direction.x*0.125f, -0.05f+Direction.y*0.10f)*BaseSize;\n\t\t\t\t\tIGraphics::CQuadItem QuadItem(BodyPos.x+Offset.x, BodyPos.y+Offset.y, EyeScale, h);\n\t\t\t\t\tGraphics()->QuadsDraw(&QuadItem, 1);\n\t\t\t\t}\n\t\t\t\tGraphics()->QuadsEnd();\n\t\t\t}\n\n\t\t\t// draw feet\n\t\t\tGraphics()->TextureSet(pInfo->m_aTextures[4]);\n\t\t\tGraphics()->QuadsBegin();\n\t\t\tCAnimKeyframe *pFoot = f ? pAnim->GetFrontFoot() : pAnim->GetBackFoot();\n\n\t\t\tfloat w = BaseSize/2.25f;\n\t\t\tfloat h = w;\n\n\t\t\tGraphics()->QuadsSetRotation(pFoot->m_Angle*pi*2);\n\n\t\t\tif(OutLine)\n\t\t\t{\n\t\t\t\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\t\tSelectSprite(SPRITE_TEE_FOOT_OUTLINE, 0, 0, 0);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbool Indicate = !pInfo->m_GotAirJump && g_Config.m_ClAirjumpindicator;\n\t\t\t\tfloat cs = 1.0f; // color scale\n\t\t\t\tif(Indicate)\n\t\t\t\t\tcs = 0.5f;\n\t\t\t\tGraphics()->SetColor(pInfo->m_aColors[4].r*cs, pInfo->m_aColors[4].g*cs, pInfo->m_aColors[4].b*cs, pInfo->m_aColors[4].a);\n\t\t\t\tSelectSprite(SPRITE_TEE_FOOT, 0, 0, 0);\n\t\t\t}\n\n\t\t\tIGraphics::CQuadItem QuadItem(Position.x+pFoot->m_X*AnimScale, Position.y+pFoot->m_Y*AnimScale, w, h);\n\t\t\tGraphics()->QuadsDraw(&QuadItem, 1);\n\t\t\tGraphics()->QuadsEnd();\n\t\t}\n\t}\n}\n\nstatic void CalcScreenParams(float Amount, float WMax, float HMax, float Aspect, float *w, float *h)\n{\n\tfloat f = sqrtf(Amount) / sqrtf(Aspect);\n\t*w = f*Aspect;\n\t*h = f;\n\n\t// limit the view\n\tif(*w > WMax)\n\t{\n\t\t*w = WMax;\n\t\t*h = *w/Aspect;\n\t}\n\n\tif(*h > HMax)\n\t{\n\t\t*h = HMax;\n\t\t*w = *h*Aspect;\n\t}\n}\n\nvoid CRenderTools::MapscreenToWorld(float CenterX, float CenterY, float ParallaxX, float ParallaxY,\n\tfloat OffsetX, float OffsetY, float Aspect, float Zoom, float *pPoints)\n{\n\tfloat Width, Height;\n\tCalcScreenParams(1150*1000, 1500, 1050, Aspect, &Width, &Height);\n\tCenterX *= ParallaxX;\n\tCenterY *= ParallaxY;\n\tWidth *= Zoom;\n\tHeight *= Zoom;\n\tpPoints[0] = OffsetX+CenterX-Width/2;\n\tpPoints[1] = OffsetY+CenterY-Height/2;\n\tpPoints[2] = pPoints[0]+Width;\n\tpPoints[3] = pPoints[1]+Height;\n}\n\nvoid CRenderTools::RenderTilemapGenerateSkip(class CLayers *pLayers)\n{\n\n\tfor(int g = 0; g < pLayers->NumGroups(); g++)\n\t{\n\t\tCMapItemGroup *pGroup = pLayers->GetGroup(g);\n\n\t\tfor(int l = 0; l < pGroup->m_NumLayers; l++)\n\t\t{\n\t\t\tCMapItemLayer *pLayer = pLayers->GetLayer(pGroup->m_StartLayer+l);\n\n\t\t\tif(pLayer->m_Type == LAYERTYPE_TILES)\n\t\t\t{\n\t\t\t\tCMapItemLayerTilemap *pTmap = (CMapItemLayerTilemap *)pLayer;\n\t\t\t\tCTile *pTiles = (CTile *)pLayers->Map()->GetData(pTmap->m_Data);\n\t\t\t\tfor(int y = 0; y < pTmap->m_Height; y++)\n\t\t\t\t{\n\t\t\t\t\tfor(int x = 1; x < pTmap->m_Width;)\n\t\t\t\t\t{\n\t\t\t\t\t\tint sx;\n\t\t\t\t\t\tfor(sx = 1; x+sx < pTmap->m_Width && sx < 255; sx++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(pTiles[y*pTmap->m_Width+x+sx].m_Index)\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tpTiles[y*pTmap->m_Width+x].m_Skip = sx-1;\n\t\t\t\t\t\tx += sx;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "src/game/client/render.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_RENDER_H\n#define GAME_CLIENT_RENDER_H\n\n#include <engine/graphics.h>\n#include <base/vmath.h>\n#include <game/mapitems.h>\n#include \"ui.h\"\n\nclass CTeeRenderInfo\n{\npublic:\n\tCTeeRenderInfo()\n\t{\n\t\tfor(int i = 0; i < 6; i++)\n\t\t\tm_aColors[i] = vec4(1,1,1,1);\n\t\tm_Size = 1.0f;\n\t\tm_GotAirJump = 1;\n\t};\n\n\tIGraphics::CTextureHandle m_aTextures[6];\n\tvec4 m_aColors[6];\n\tfloat m_Size;\n\tint m_GotAirJump;\n};\n\n// sprite renderings\nenum\n{\n\tSPRITE_FLAG_FLIP_Y=1,\n\tSPRITE_FLAG_FLIP_X=2,\n\n\tLAYERRENDERFLAG_OPAQUE=1,\n\tLAYERRENDERFLAG_TRANSPARENT=2,\n\n\tTILERENDERFLAG_EXTEND=4,\n};\n\ntypedef void (*ENVELOPE_EVAL)(float TimeOffset, int Env, float *pChannels, void *pUser);\n\nclass CRenderTools\n{\npublic:\n\tclass IGraphics *m_pGraphics;\n\tclass CUI *m_pUI;\n\n\tclass IGraphics *Graphics() const { return m_pGraphics; }\n\tclass CUI *UI() const { return m_pUI; }\n\n\t//typedef struct SPRITE;\n\n\tvoid SelectSprite(struct CDataSprite *pSprite, int Flags=0, int sx=0, int sy=0);\n\tvoid SelectSprite(int id, int Flags=0, int sx=0, int sy=0);\n\n\tvoid DrawSprite(float x, float y, float size);\n\n\t// rects\n\tvoid DrawRoundRect(float x, float y, float w, float h, float r);\n\tvoid DrawRoundRectExt(float x, float y, float w, float h, float r, int Corners);\n\tvoid DrawRoundRectExt4(float x, float y, float w, float h, vec4 ColorTopLeft, vec4 ColorTopRight, vec4 ColorBottomLeft, vec4 ColorBottomRight, float r, int Corners);\n\n\tvoid DrawUIRect(const CUIRect *pRect, vec4 Color, int Corners, float Rounding);\n\tvoid DrawUIRect4(const CUIRect *pRect, vec4 ColorTopLeft, vec4 ColorTopRight, vec4 ColorBottomLeft, vec4 ColorBottomRight, int Corners, float Rounding);\n\n\t// larger rendering methods\n\tvoid RenderTilemapGenerateSkip(class CLayers *pLayers);\n\n\t// object render methods (gc_render_obj.cpp)\n\tvoid RenderTee(class CAnimState *pAnim, CTeeRenderInfo *pInfo, int Emote, vec2 Dir, vec2 Pos);\n\n\t// map render methods (gc_render_map.cpp)\n\tstatic void RenderEvalEnvelope(CEnvPoint *pPoints, int NumPoints, int Channels, float Time, float *pResult);\n\tvoid RenderQuads(CQuad *pQuads, int NumQuads, int Flags, ENVELOPE_EVAL pfnEval, void *pUser);\n\tvoid RenderTilemap(CTile *pTiles, int w, int h, float Scale, vec4 Color, int RenderFlags, ENVELOPE_EVAL pfnEval, void *pUser, int ColorEnv, int ColorEnvOffset);\n\n\t// helpers\n\tvoid MapscreenToWorld(float CenterX, float CenterY, float ParallaxX, float ParallaxY,\n\t\tfloat OffsetX, float OffsetY, float Aspect, float Zoom, float *pPoints);\n\n};\n\n#endif\n"
  },
  {
    "path": "src/game/client/render_map.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <math.h>\n#include <base/math.h>\n#include <engine/graphics.h>\n\n#include \"render.h\"\n\nvoid CRenderTools::RenderEvalEnvelope(CEnvPoint *pPoints, int NumPoints, int Channels, float Time, float *pResult)\n{\n\tif(NumPoints == 0)\n\t{\n\t\tpResult[0] = 0;\n\t\tpResult[1] = 0;\n\t\tpResult[2] = 0;\n\t\tpResult[3] = 0;\n\t\treturn;\n\t}\n\n\tif(NumPoints == 1)\n\t{\n\t\tpResult[0] = fx2f(pPoints[0].m_aValues[0]);\n\t\tpResult[1] = fx2f(pPoints[0].m_aValues[1]);\n\t\tpResult[2] = fx2f(pPoints[0].m_aValues[2]);\n\t\tpResult[3] = fx2f(pPoints[0].m_aValues[3]);\n\t\treturn;\n\t}\n\n\tTime = fmod(Time, pPoints[NumPoints-1].m_Time/1000.0f)*1000.0f;\n\tfor(int i = 0; i < NumPoints-1; i++)\n\t{\n\t\tif(Time >= pPoints[i].m_Time && Time <= pPoints[i+1].m_Time)\n\t\t{\n\t\t\tfloat Delta = pPoints[i+1].m_Time-pPoints[i].m_Time;\n\t\t\tfloat a = (Time-pPoints[i].m_Time)/Delta;\n\n\n\t\t\tif(pPoints[i].m_Curvetype == CURVETYPE_SMOOTH)\n\t\t\t\ta = -2*a*a*a + 3*a*a; // second hermite basis\n\t\t\telse if(pPoints[i].m_Curvetype == CURVETYPE_SLOW)\n\t\t\t\ta = a*a*a;\n\t\t\telse if(pPoints[i].m_Curvetype == CURVETYPE_FAST)\n\t\t\t{\n\t\t\t\ta = 1-a;\n\t\t\t\ta = 1-a*a*a;\n\t\t\t}\n\t\t\telse if (pPoints[i].m_Curvetype == CURVETYPE_STEP)\n\t\t\t\ta = 0;\n\t\t\telse\n\t\t\t{\n\t\t\t\t// linear\n\t\t\t}\n\n\t\t\tfor(int c = 0; c < Channels; c++)\n\t\t\t{\n\t\t\t\tfloat v0 = fx2f(pPoints[i].m_aValues[c]);\n\t\t\t\tfloat v1 = fx2f(pPoints[i+1].m_aValues[c]);\n\t\t\t\tpResult[c] = v0 + (v1-v0) * a;\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\t}\n\n\tpResult[0] = fx2f(pPoints[NumPoints-1].m_aValues[0]);\n\tpResult[1] = fx2f(pPoints[NumPoints-1].m_aValues[1]);\n\tpResult[2] = fx2f(pPoints[NumPoints-1].m_aValues[2]);\n\tpResult[3] = fx2f(pPoints[NumPoints-1].m_aValues[3]);\n\treturn;\n}\n\n\nstatic void Rotate(CPoint *pCenter, CPoint *pPoint, float Rotation)\n{\n\tint x = pPoint->x - pCenter->x;\n\tint y = pPoint->y - pCenter->y;\n\tpPoint->x = (int)(x * cosf(Rotation) - y * sinf(Rotation) + pCenter->x);\n\tpPoint->y = (int)(x * sinf(Rotation) + y * cosf(Rotation) + pCenter->y);\n}\n\nvoid CRenderTools::RenderQuads(CQuad *pQuads, int NumQuads, int RenderFlags, ENVELOPE_EVAL pfnEval, void *pUser)\n{\n\tGraphics()->QuadsBegin();\n\tfloat Conv = 1/255.0f;\n\tfor(int i = 0; i < NumQuads; i++)\n\t{\n\t\tCQuad *q = &pQuads[i];\n\n\t\tfloat r=1, g=1, b=1, a=1;\n\n\t\tif(q->m_ColorEnv >= 0)\n\t\t{\n\t\t\tfloat aChannels[4];\n\t\t\tpfnEval(q->m_ColorEnvOffset/1000.0f, q->m_ColorEnv, aChannels, pUser);\n\t\t\tr = aChannels[0];\n\t\t\tg = aChannels[1];\n\t\t\tb = aChannels[2];\n\t\t\ta = aChannels[3];\n\t\t}\n\n\t\tbool Opaque = false;\n\t\t/* TODO: Analyze quadtexture\n\t\tif(a < 0.01f || (q->m_aColors[0].a < 0.01f && q->m_aColors[1].a < 0.01f && q->m_aColors[2].a < 0.01f && q->m_aColors[3].a < 0.01f))\n\t\t\tOpaque = true;\n\t\t*/\n\t\tif(Opaque && !(RenderFlags&LAYERRENDERFLAG_OPAQUE))\n\t\t\tcontinue;\n\t\tif(!Opaque && !(RenderFlags&LAYERRENDERFLAG_TRANSPARENT))\n\t\t\tcontinue;\n\n\t\tGraphics()->QuadsSetSubsetFree(\n\t\t\tfx2f(q->m_aTexcoords[0].x), fx2f(q->m_aTexcoords[0].y),\n\t\t\tfx2f(q->m_aTexcoords[1].x), fx2f(q->m_aTexcoords[1].y),\n\t\t\tfx2f(q->m_aTexcoords[2].x), fx2f(q->m_aTexcoords[2].y),\n\t\t\tfx2f(q->m_aTexcoords[3].x), fx2f(q->m_aTexcoords[3].y)\n\t\t);\n\n\t\tfloat OffsetX = 0;\n\t\tfloat OffsetY = 0;\n\t\tfloat Rot = 0;\n\n\t\t// TODO: fix this\n\t\tif(q->m_PosEnv >= 0)\n\t\t{\n\t\t\tfloat aChannels[4];\n\t\t\tpfnEval(q->m_PosEnvOffset/1000.0f, q->m_PosEnv, aChannels, pUser);\n\t\t\tOffsetX = aChannels[0];\n\t\t\tOffsetY = aChannels[1];\n\t\t\tRot = aChannels[2]/360.0f*pi*2;\n\t\t}\n\n\t\tIGraphics::CColorVertex Array[4] = {\n\t\t\tIGraphics::CColorVertex(0, q->m_aColors[0].r*Conv*r, q->m_aColors[0].g*Conv*g, q->m_aColors[0].b*Conv*b, q->m_aColors[0].a*Conv*a),\n\t\t\tIGraphics::CColorVertex(1, q->m_aColors[1].r*Conv*r, q->m_aColors[1].g*Conv*g, q->m_aColors[1].b*Conv*b, q->m_aColors[1].a*Conv*a),\n\t\t\tIGraphics::CColorVertex(2, q->m_aColors[2].r*Conv*r, q->m_aColors[2].g*Conv*g, q->m_aColors[2].b*Conv*b, q->m_aColors[2].a*Conv*a),\n\t\t\tIGraphics::CColorVertex(3, q->m_aColors[3].r*Conv*r, q->m_aColors[3].g*Conv*g, q->m_aColors[3].b*Conv*b, q->m_aColors[3].a*Conv*a)};\n\t\tGraphics()->SetColorVertex(Array, 4);\n\n\t\tCPoint *pPoints = q->m_aPoints;\n\n\t\tif(Rot != 0)\n\t\t{\n\t\t\tstatic CPoint aRotated[4];\n\t\t\taRotated[0] = q->m_aPoints[0];\n\t\t\taRotated[1] = q->m_aPoints[1];\n\t\t\taRotated[2] = q->m_aPoints[2];\n\t\t\taRotated[3] = q->m_aPoints[3];\n\t\t\tpPoints = aRotated;\n\n\t\t\tRotate(&q->m_aPoints[4], &aRotated[0], Rot);\n\t\t\tRotate(&q->m_aPoints[4], &aRotated[1], Rot);\n\t\t\tRotate(&q->m_aPoints[4], &aRotated[2], Rot);\n\t\t\tRotate(&q->m_aPoints[4], &aRotated[3], Rot);\n\t\t}\n\n\t\tIGraphics::CFreeformItem Freeform(\n\t\t\tfx2f(pPoints[0].x)+OffsetX, fx2f(pPoints[0].y)+OffsetY,\n\t\t\tfx2f(pPoints[1].x)+OffsetX, fx2f(pPoints[1].y)+OffsetY,\n\t\t\tfx2f(pPoints[2].x)+OffsetX, fx2f(pPoints[2].y)+OffsetY,\n\t\t\tfx2f(pPoints[3].x)+OffsetX, fx2f(pPoints[3].y)+OffsetY);\n\t\tGraphics()->QuadsDrawFreeform(&Freeform, 1);\n\t}\n\tGraphics()->QuadsEnd();\n}\n\nvoid CRenderTools::RenderTilemap(CTile *pTiles, int w, int h, float Scale, vec4 Color, int RenderFlags,\n\t\t\t\t\t\t\t\t\tENVELOPE_EVAL pfnEval, void *pUser, int ColorEnv, int ColorEnvOffset)\n{\n\t//Graphics()->TextureSet(img_get(tmap->image));\n\tfloat ScreenX0, ScreenY0, ScreenX1, ScreenY1;\n\tGraphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1);\n\t//Graphics()->MapScreen(screen_x0-50, screen_y0-50, screen_x1+50, screen_y1+50);\n\n\t// calculate the final pixelsize for the tiles\n\tfloat TilePixelSize = 1024/32.0f;\n\tfloat FinalTileSize = Scale/(ScreenX1-ScreenX0) * Graphics()->ScreenWidth();\n\tfloat FinalTilesetScale = FinalTileSize/TilePixelSize;\n\n\tfloat r=1, g=1, b=1, a=1;\n\tif(ColorEnv >= 0)\n\t{\n\t\tfloat aChannels[4];\n\t\tpfnEval(ColorEnvOffset/1000.0f, ColorEnv, aChannels, pUser);\n\t\tr = aChannels[0];\n\t\tg = aChannels[1];\n\t\tb = aChannels[2];\n\t\ta = aChannels[3];\n\t}\n\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(Color.r*r, Color.g*g, Color.b*b, Color.a*a);\n\n\tint StartY = (int)(ScreenY0/Scale)-1;\n\tint StartX = (int)(ScreenX0/Scale)-1;\n\tint EndY = (int)(ScreenY1/Scale)+1;\n\tint EndX = (int)(ScreenX1/Scale)+1;\n\n\t// adjust the texture shift according to mipmap level\n\tfloat TexSize = 1024.0f;\n\tfloat Frac = (1.25f/TexSize) * (1/FinalTilesetScale);\n\tfloat Nudge = (0.5f/TexSize) * (1/FinalTilesetScale);\n\n\tfor(int y = StartY; y < EndY; y++)\n\t\tfor(int x = StartX; x < EndX; x++)\n\t\t{\n\t\t\tint mx = x;\n\t\t\tint my = y;\n\n\t\t\tif(RenderFlags&TILERENDERFLAG_EXTEND)\n\t\t\t{\n\t\t\t\tif(mx<0)\n\t\t\t\t\tmx = 0;\n\t\t\t\tif(mx>=w)\n\t\t\t\t\tmx = w-1;\n\t\t\t\tif(my<0)\n\t\t\t\t\tmy = 0;\n\t\t\t\tif(my>=h)\n\t\t\t\t\tmy = h-1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(mx<0)\n\t\t\t\t\tcontinue; // mx = 0;\n\t\t\t\tif(mx>=w)\n\t\t\t\t\tcontinue; // mx = w-1;\n\t\t\t\tif(my<0)\n\t\t\t\t\tcontinue; // my = 0;\n\t\t\t\tif(my>=h)\n\t\t\t\t\tcontinue; // my = h-1;\n\t\t\t}\n\n\t\t\tint c = mx + my*w;\n\n\t\t\tunsigned char Index = pTiles[c].m_Index;\n\t\t\tif(Index)\n\t\t\t{\n\t\t\t\tunsigned char Flags = pTiles[c].m_Flags;\n\n\t\t\t\tbool Render = false;\n\t\t\t\tif(Flags&TILEFLAG_OPAQUE && Color.a*a > 254.0f/255.0f)\n\t\t\t\t{\n\t\t\t\t\tif(RenderFlags&LAYERRENDERFLAG_OPAQUE)\n\t\t\t\t\t\tRender = true;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif(RenderFlags&LAYERRENDERFLAG_TRANSPARENT)\n\t\t\t\t\t\tRender = true;\n\t\t\t\t}\n\n\t\t\t\tif(Render)\n\t\t\t\t{\n\n\t\t\t\t\tint tx = Index%16;\n\t\t\t\t\tint ty = Index/16;\n\t\t\t\t\tint Px0 = tx*(1024/16);\n\t\t\t\t\tint Py0 = ty*(1024/16);\n\t\t\t\t\tint Px1 = Px0+(1024/16)-1;\n\t\t\t\t\tint Py1 = Py0+(1024/16)-1;\n\n\t\t\t\t\tfloat x0 = Nudge + Px0/TexSize+Frac;\n\t\t\t\t\tfloat y0 = Nudge + Py0/TexSize+Frac;\n\t\t\t\t\tfloat x1 = Nudge + Px1/TexSize-Frac;\n\t\t\t\t\tfloat y1 = Nudge + Py0/TexSize+Frac;\n\t\t\t\t\tfloat x2 = Nudge + Px1/TexSize-Frac;\n\t\t\t\t\tfloat y2 = Nudge + Py1/TexSize-Frac;\n\t\t\t\t\tfloat x3 = Nudge + Px0/TexSize+Frac;\n\t\t\t\t\tfloat y3 = Nudge + Py1/TexSize-Frac;\n\n\t\t\t\t\tif(Flags&TILEFLAG_VFLIP)\n\t\t\t\t\t{\n\t\t\t\t\t\tx0 = x2;\n\t\t\t\t\t\tx1 = x3;\n\t\t\t\t\t\tx2 = x3;\n\t\t\t\t\t\tx3 = x0;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(Flags&TILEFLAG_HFLIP)\n\t\t\t\t\t{\n\t\t\t\t\t\ty0 = y3;\n\t\t\t\t\t\ty2 = y1;\n\t\t\t\t\t\ty3 = y1;\n\t\t\t\t\t\ty1 = y0;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(Flags&TILEFLAG_ROTATE)\n\t\t\t\t\t{\n\t\t\t\t\t\tfloat Tmp = x0;\n\t\t\t\t\t\tx0 = x3;\n\t\t\t\t\t\tx3 = x2;\n\t\t\t\t\t\tx2 = x1;\n\t\t\t\t\t\tx1 = Tmp;\n\t\t\t\t\t\tTmp = y0;\n\t\t\t\t\t\ty0 = y3;\n\t\t\t\t\t\ty3 = y2;\n\t\t\t\t\t\ty2 = y1;\n\t\t\t\t\t\ty1 = Tmp;\n \t\t\t\t\t}\n\n\t\t\t\t\tGraphics()->QuadsSetSubsetFree(x0, y0, x1, y1, x2, y2, x3, y3);\n\t\t\t\t\tIGraphics::CQuadItem QuadItem(x*Scale, y*Scale, Scale, Scale);\n\t\t\t\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tx += pTiles[c].m_Skip;\n\t\t}\n\n\tGraphics()->QuadsEnd();\n\tGraphics()->MapScreen(ScreenX0, ScreenY0, ScreenX1, ScreenY1);\n}\n"
  },
  {
    "path": "src/game/client/ui.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n\n#include <engine/shared/config.h>\n#include <engine/graphics.h>\n#include <engine/textrender.h>\n#include \"ui.h\"\n\n/********************************************************\n UI\n*********************************************************/\n\nCUI::CUI()\n{\n\tm_pHotItem = 0;\n\tm_pActiveItem = 0;\n\tm_pLastActiveItem = 0;\n\tm_pBecommingHotItem = 0;\n\n\tm_MouseX = 0;\n\tm_MouseY = 0;\n\tm_MouseWorldX = 0;\n\tm_MouseWorldY = 0;\n\tm_MouseButtons = 0;\n\tm_LastMouseButtons = 0;\n\n\tm_Screen.x = 0;\n\tm_Screen.y = 0;\n\tm_Screen.w = 848.0f;\n\tm_Screen.h = 480.0f;\n}\n\nint CUI::Update(float Mx, float My, float Mwx, float Mwy, int Buttons)\n{\n\tm_MouseX = Mx;\n\tm_MouseY = My;\n\tm_MouseWorldX = Mwx;\n\tm_MouseWorldY = Mwy;\n\tm_LastMouseButtons = m_MouseButtons;\n\tm_MouseButtons = Buttons;\n\tm_pHotItem = m_pBecommingHotItem;\n\tif(m_pActiveItem)\n\t\tm_pHotItem = m_pActiveItem;\n\tm_pBecommingHotItem = 0;\n\treturn 0;\n}\n\nint CUI::MouseInside(const CUIRect *r)\n{\n\tif(m_MouseX >= r->x && m_MouseX < r->x+r->w && m_MouseY >= r->y && m_MouseY < r->y+r->h)\n\t\treturn 1;\n\treturn 0;\n}\n\nvoid CUI::ConvertMouseMove(float *x, float *y)\n{\n\tfloat Fac = (float)(g_Config.m_UiMousesens)/g_Config.m_InpMousesens;\n\t*x = *x*Fac;\n\t*y = *y*Fac;\n}\n\nCUIRect *CUI::Screen()\n{\n\tfloat Aspect = Graphics()->ScreenAspect();\n\tfloat w, h;\n\n\th = 600;\n\tw = Aspect*h;\n\n\tm_Screen.w = w;\n\tm_Screen.h = h;\n\n\treturn &m_Screen;\n}\n\nfloat CUI::PixelSize()\n{\n\treturn Screen()->w/Graphics()->ScreenWidth();\n}\n\nfloat CUI::Scale()\n{\n\treturn 1.0f;\n}\n\nfloat CUIRect::Scale() const\n{\n\treturn 1.0f;\n}\n\nvoid CUI::ClipEnable(const CUIRect *r)\n{\n\tfloat XScale = Graphics()->ScreenWidth()/Screen()->w;\n\tfloat YScale = Graphics()->ScreenHeight()/Screen()->h;\n\tGraphics()->ClipEnable((int)(r->x*XScale), (int)(r->y*YScale), (int)(r->w*XScale), (int)(r->h*YScale));\n}\n\nvoid CUI::ClipDisable()\n{\n\tGraphics()->ClipDisable();\n}\n\nvoid CUIRect::HSplitMid(CUIRect *pTop, CUIRect *pBottom) const\n{\n\tCUIRect r = *this;\n\tfloat Cut = r.h/2;\n\n\tif(pTop)\n\t{\n\t\tpTop->x = r.x;\n\t\tpTop->y = r.y;\n\t\tpTop->w = r.w;\n\t\tpTop->h = Cut;\n\t}\n\n\tif(pBottom)\n\t{\n\t\tpBottom->x = r.x;\n\t\tpBottom->y = r.y + Cut;\n\t\tpBottom->w = r.w;\n\t\tpBottom->h = r.h - Cut;\n\t}\n}\n\nvoid CUIRect::HSplitTop(float Cut, CUIRect *pTop, CUIRect *pBottom) const\n{\n\tCUIRect r = *this;\n\tCut *= Scale();\n\n\tif (pTop)\n\t{\n\t\tpTop->x = r.x;\n\t\tpTop->y = r.y;\n\t\tpTop->w = r.w;\n\t\tpTop->h = Cut;\n\t}\n\n\tif (pBottom)\n\t{\n\t\tpBottom->x = r.x;\n\t\tpBottom->y = r.y + Cut;\n\t\tpBottom->w = r.w;\n\t\tpBottom->h = r.h - Cut;\n\t}\n}\n\nvoid CUIRect::HSplitBottom(float Cut, CUIRect *pTop, CUIRect *pBottom) const\n{\n\tCUIRect r = *this;\n\tCut *= Scale();\n\n\tif (pTop)\n\t{\n\t\tpTop->x = r.x;\n\t\tpTop->y = r.y;\n\t\tpTop->w = r.w;\n\t\tpTop->h = r.h - Cut;\n\t}\n\n\tif (pBottom)\n\t{\n\t\tpBottom->x = r.x;\n\t\tpBottom->y = r.y + r.h - Cut;\n\t\tpBottom->w = r.w;\n\t\tpBottom->h = Cut;\n\t}\n}\n\n\nvoid CUIRect::VSplitMid(CUIRect *pLeft, CUIRect *pRight) const\n{\n\tCUIRect r = *this;\n\tfloat Cut = r.w/2;\n//\tCut *= Scale();\n\n\tif (pLeft)\n\t{\n\t\tpLeft->x = r.x;\n\t\tpLeft->y = r.y;\n\t\tpLeft->w = Cut;\n\t\tpLeft->h = r.h;\n\t}\n\n\tif (pRight)\n\t{\n\t\tpRight->x = r.x + Cut;\n\t\tpRight->y = r.y;\n\t\tpRight->w = r.w - Cut;\n\t\tpRight->h = r.h;\n\t}\n}\n\nvoid CUIRect::VSplitLeft(float Cut, CUIRect *pLeft, CUIRect *pRight) const\n{\n\tCUIRect r = *this;\n\tCut *= Scale();\n\n\tif (pLeft)\n\t{\n\t\tpLeft->x = r.x;\n\t\tpLeft->y = r.y;\n\t\tpLeft->w = Cut;\n\t\tpLeft->h = r.h;\n\t}\n\n\tif (pRight)\n\t{\n\t\tpRight->x = r.x + Cut;\n\t\tpRight->y = r.y;\n\t\tpRight->w = r.w - Cut;\n\t\tpRight->h = r.h;\n\t}\n}\n\nvoid CUIRect::VSplitRight(float Cut, CUIRect *pLeft, CUIRect *pRight) const\n{\n\tCUIRect r = *this;\n\tCut *= Scale();\n\n\tif (pLeft)\n\t{\n\t\tpLeft->x = r.x;\n\t\tpLeft->y = r.y;\n\t\tpLeft->w = r.w - Cut;\n\t\tpLeft->h = r.h;\n\t}\n\n\tif (pRight)\n\t{\n\t\tpRight->x = r.x + r.w - Cut;\n\t\tpRight->y = r.y;\n\t\tpRight->w = Cut;\n\t\tpRight->h = r.h;\n\t}\n}\n\nvoid CUIRect::Margin(float Cut, CUIRect *pOtherRect) const\n{\n\tCUIRect r = *this;\n\tCut *= Scale();\n\n\tpOtherRect->x = r.x + Cut;\n\tpOtherRect->y = r.y + Cut;\n\tpOtherRect->w = r.w - 2*Cut;\n\tpOtherRect->h = r.h - 2*Cut;\n}\n\nvoid CUIRect::VMargin(float Cut, CUIRect *pOtherRect) const\n{\n\tCUIRect r = *this;\n\tCut *= Scale();\n\n\tpOtherRect->x = r.x + Cut;\n\tpOtherRect->y = r.y;\n\tpOtherRect->w = r.w - 2*Cut;\n\tpOtherRect->h = r.h;\n}\n\nvoid CUIRect::HMargin(float Cut, CUIRect *pOtherRect) const\n{\n\tCUIRect r = *this;\n\tCut *= Scale();\n\n\tpOtherRect->x = r.x;\n\tpOtherRect->y = r.y + Cut;\n\tpOtherRect->w = r.w;\n\tpOtherRect->h = r.h - 2*Cut;\n}\n\nint CUI::DoButtonLogic(const void *pID, const char *pText, int Checked, const CUIRect *pRect)\n{\n\t// logic\n\tint ReturnValue = 0;\n\tint Inside = MouseInside(pRect);\n\tstatic int ButtonUsed = 0;\n\n\tif(ActiveItem() == pID)\n\t{\n\t\tif(!MouseButton(ButtonUsed))\n\t\t{\n\t\t\tif(Inside && Checked >= 0)\n\t\t\t\tReturnValue = 1+ButtonUsed;\n\t\t\tSetActiveItem(0);\n\t\t}\n\t}\n\telse if(HotItem() == pID)\n\t{\n\t\tif(MouseButton(0))\n\t\t{\n\t\t\tSetActiveItem(pID);\n\t\t\tButtonUsed = 0;\n\t\t}\n\n\t\tif(MouseButton(1))\n\t\t{\n\t\t\tSetActiveItem(pID);\n\t\t\tButtonUsed = 1;\n\t\t}\n\t}\n\n\tif(Inside)\n\t\tSetHotItem(pID);\n\n\treturn ReturnValue;\n}\n\nint CUI::DoPickerLogic(const void *pID, const CUIRect *pRect, float *pX, float *pY)\n{\n\tint Inside = MouseInside(pRect);\n\n\tif(ActiveItem() == pID)\n\t{\n\t\tif(!MouseButton(0))\n\t\t\tSetActiveItem(0);\n\t}\n\telse if(HotItem() == pID)\n\t{\n\t\tif(MouseButton(0))\n\t\t\tSetActiveItem(pID);\n\t}\n\telse if(Inside)\n\t\tSetHotItem(pID);\n\n\tif(ActiveItem() != pID)\n\t\treturn 0;\n\n\tif(pX)\n\t\t*pX = clamp(m_MouseX - pRect->x, 0.0f, pRect->w) / Scale();\n\tif(pY)\n\t\t*pY = clamp(m_MouseY - pRect->y, 0.0f, pRect->h) / Scale();\n\n\treturn 1;\n}\n\nint CUI::DoColorSelectionLogic(const CUIRect *pRect, const CUIRect *pButton) // it's counter logic! FIXME\n{\n\tif(MouseButtonClicked(0) && MouseInside(pRect) && !MouseInside(pButton))\n\t\treturn 1;\n\telse\n\t\treturn 0;\n}\n\n/*\nint CUI::DoButton(const void *id, const char *text, int checked, const CUIRect *r, ui_draw_button_func draw_func, const void *extra)\n{\n\t// logic\n\tint ret = 0;\n\tint inside = ui_MouseInside(r);\n\tstatic int button_used = 0;\n\n\tif(ui_ActiveItem() == id)\n\t{\n\t\tif(!ui_MouseButton(button_used))\n\t\t{\n\t\t\tif(inside && checked >= 0)\n\t\t\t\tret = 1+button_used;\n\t\t\tui_SetActiveItem(0);\n\t\t}\n\t}\n\telse if(ui_HotItem() == id)\n\t{\n\t\tif(ui_MouseButton(0))\n\t\t{\n\t\t\tui_SetActiveItem(id);\n\t\t\tbutton_used = 0;\n\t\t}\n\n\t\tif(ui_MouseButton(1))\n\t\t{\n\t\t\tui_SetActiveItem(id);\n\t\t\tbutton_used = 1;\n\t\t}\n\t}\n\n\tif(inside)\n\t\tui_SetHotItem(id);\n\n\tif(draw_func)\n\t\tdraw_func(id, text, checked, r, extra);\n\treturn ret;\n}*/\n\nvoid CUI::DoLabel(const CUIRect *r, const char *pText, float Size, int Align, int MaxWidth)\n{\n\t// TODO: FIX ME!!!!\n\t//Graphics()->BlendNormal();\n\tif(Align == 0)\n\t{\n\t\tfloat tw = TextRender()->TextWidth(0, Size, pText, MaxWidth);\n\t\tTextRender()->Text(0, r->x + r->w/2-tw/2, r->y - Size/10, Size, pText, MaxWidth);\n\t}\n\telse if(Align < 0)\n\t\tTextRender()->Text(0, r->x, r->y - Size/10, Size, pText, MaxWidth);\n\telse if(Align > 0)\n\t{\n\t\tfloat tw = TextRender()->TextWidth(0, Size, pText, MaxWidth);\n\t\tTextRender()->Text(0, r->x + r->w-tw, r->y - Size/10, Size, pText, MaxWidth);\n\t}\n}\n\nvoid CUI::DoLabelScaled(const CUIRect *r, const char *pText, float Size, int Align, int MaxWidth)\n{\n\tDoLabel(r, pText, Size*Scale(), Align, MaxWidth);\n}"
  },
  {
    "path": "src/game/client/ui.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_CLIENT_UI_H\n#define GAME_CLIENT_UI_H\n\nclass CUIRect\n{\n\t// TODO: Refactor: Redo UI scaling\n\tfloat Scale() const;\npublic:\n\tfloat x, y, w, h;\n\n\tvoid HSplitMid(CUIRect *pTop, CUIRect *pBottom) const;\n\tvoid HSplitTop(float Cut, CUIRect *pTop, CUIRect *pBottom) const;\n\tvoid HSplitBottom(float Cut, CUIRect *pTop, CUIRect *pBottom) const;\n\tvoid VSplitMid(CUIRect *pLeft, CUIRect *pRight) const;\n\tvoid VSplitLeft(float Cut, CUIRect *pLeft, CUIRect *pRight) const;\n\tvoid VSplitRight(float Cut, CUIRect *pLeft, CUIRect *pRight) const;\n\n\tvoid Margin(float Cut, CUIRect *pOtherRect) const;\n\tvoid VMargin(float Cut, CUIRect *pOtherRect) const;\n\tvoid HMargin(float Cut, CUIRect *pOtherRect) const;\n\n};\n\nclass CUI\n{\n\tconst void *m_pHotItem;\n\tconst void *m_pActiveItem;\n\tconst void *m_pLastActiveItem;\n\tconst void *m_pBecommingHotItem;\n\tfloat m_MouseX, m_MouseY; // in gui space\n\tfloat m_MouseWorldX, m_MouseWorldY; // in world space\n\tunsigned m_MouseButtons;\n\tunsigned m_LastMouseButtons;\n\n\tCUIRect m_Screen;\n\tclass IGraphics *m_pGraphics;\n\tclass ITextRender *m_pTextRender;\n\npublic:\n\t// TODO: Refactor: Fill this in\n\tvoid SetGraphics(class IGraphics *pGraphics, class ITextRender *pTextRender) { m_pGraphics = pGraphics; m_pTextRender = pTextRender;}\n\tclass IGraphics *Graphics() { return m_pGraphics; }\n\tclass ITextRender *TextRender() { return m_pTextRender; }\n\n\tCUI();\n\n\tenum\n\t{\n\t\tCORNER_TL=1,\n\t\tCORNER_TR=2,\n\t\tCORNER_BL=4,\n\t\tCORNER_BR=8,\n\t\tCORNER_ITL=16,\n\t\tCORNER_ITR=32,\n\t\tCORNER_IBL=64,\n\t\tCORNER_IBR=128,\n\n\t\tCORNER_T=CORNER_TL|CORNER_TR,\n\t\tCORNER_B=CORNER_BL|CORNER_BR,\n\t\tCORNER_R=CORNER_TR|CORNER_BR,\n\t\tCORNER_L=CORNER_TL|CORNER_BL,\n\n\t\tCORNER_IT=CORNER_ITL|CORNER_ITR,\n\t\tCORNER_IB=CORNER_IBL|CORNER_IBR,\n\t\tCORNER_IR=CORNER_ITR|CORNER_IBR,\n\t\tCORNER_IL=CORNER_ITL|CORNER_IBL,\n\n\t\tCORNER_ALL=CORNER_T|CORNER_B,\n\t\tCORNER_INV_ALL=CORNER_IT|CORNER_IB\n\t};\n\n\tint Update(float mx, float my, float Mwx, float Mwy, int m_Buttons);\n\n\tfloat MouseX() const { return m_MouseX; }\n\tfloat MouseY() const { return m_MouseY; }\n\tfloat MouseWorldX() const { return m_MouseWorldX; }\n\tfloat MouseWorldY() const { return m_MouseWorldY; }\n\tint MouseButton(int Index) const { return (m_MouseButtons>>Index)&1; }\n\tint MouseButtonClicked(int Index) { return MouseButton(Index) && !((m_LastMouseButtons>>Index)&1) ; }\n\n\tvoid SetHotItem(const void *pID) { m_pBecommingHotItem = pID; }\n\tvoid SetActiveItem(const void *pID) { m_pActiveItem = pID; if (pID) m_pLastActiveItem = pID; }\n\tvoid ClearLastActiveItem() { m_pLastActiveItem = 0; }\n\tconst void *HotItem() const { return m_pHotItem; }\n\tconst void *NextHotItem() const { return m_pBecommingHotItem; }\n\tconst void *ActiveItem() const { return m_pActiveItem; }\n\tconst void *LastActiveItem() const { return m_pLastActiveItem; }\n\n\tint MouseInside(const CUIRect *pRect);\n\tvoid ConvertMouseMove(float *x, float *y);\n\n\tCUIRect *Screen();\n\tfloat PixelSize();\n\tvoid ClipEnable(const CUIRect *pRect);\n\tvoid ClipDisable();\n\n\t// TODO: Refactor: Redo UI scaling\n\tfloat Scale();\n\n\tint DoButtonLogic(const void *pID, const char *pText /* TODO: Refactor: Remove */, int Checked, const CUIRect *pRect);\n\tint DoPickerLogic(const void *pID, const CUIRect *pRect, float *pX, float *pY);\n\tint DoColorSelectionLogic(const CUIRect *pRect, const CUIRect *pButton);\n\n\t// TODO: Refactor: Remove this?\n\tvoid DoLabel(const CUIRect *pRect, const char *pText, float Size, int Align, int MaxWidth = -1);\n\tvoid DoLabelScaled(const CUIRect *pRect, const char *pText, float Size, int Align, int MaxWidth = -1);\n};\n\n\n#endif\n"
  },
  {
    "path": "src/game/collision.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n#include <base/math.h>\n#include <base/vmath.h>\n\n#include <math.h>\n#include <engine/map.h>\n#include <engine/kernel.h>\n\n#include <game/mapitems.h>\n#include <game/layers.h>\n#include <game/collision.h>\n\nCCollision::CCollision()\n{\n\tm_pTiles = 0;\n\tm_Width = 0;\n\tm_Height = 0;\n\tm_pLayers = 0;\n}\n\nvoid CCollision::Init(class CLayers *pLayers)\n{\n\tm_pLayers = pLayers;\n\tm_Width = m_pLayers->GameLayer()->m_Width;\n\tm_Height = m_pLayers->GameLayer()->m_Height;\n\tm_pTiles = static_cast<CTile *>(m_pLayers->Map()->GetData(m_pLayers->GameLayer()->m_Data));\n\n\tfor(int i = 0; i < m_Width*m_Height; i++)\n\t{\n\t\tint Index = m_pTiles[i].m_Index;\n\n\t\tif(Index > 128)\n\t\t\tcontinue;\n\n\t\tswitch(Index)\n\t\t{\n\t\tcase TILE_DEATH:\n\t\t\tm_pTiles[i].m_Index = COLFLAG_DEATH;\n\t\t\tbreak;\n\t\tcase TILE_SOLID:\n\t\t\tm_pTiles[i].m_Index = COLFLAG_SOLID;\n\t\t\tbreak;\n\t\tcase TILE_NOHOOK:\n\t\t\tm_pTiles[i].m_Index = COLFLAG_SOLID|COLFLAG_NOHOOK;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tm_pTiles[i].m_Index = 0;\n\t\t}\n\t}\n}\n\nint CCollision::GetTile(int x, int y)\n{\n\tint Nx = clamp(x/32, 0, m_Width-1);\n\tint Ny = clamp(y/32, 0, m_Height-1);\n\n\treturn m_pTiles[Ny*m_Width+Nx].m_Index > 128 ? 0 : m_pTiles[Ny*m_Width+Nx].m_Index;\n}\n\nbool CCollision::IsTileSolid(int x, int y)\n{\n\treturn GetTile(x, y)&COLFLAG_SOLID;\n}\n\n// TODO: rewrite this smarter!\nint CCollision::IntersectLine(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pOutBeforeCollision)\n{\n\tfloat Distance = distance(Pos0, Pos1);\n\tint End(Distance+1);\n\tvec2 Last = Pos0;\n\n\tfor(int i = 0; i < End; i++)\n\t{\n\t\tfloat a = i/Distance;\n\t\tvec2 Pos = mix(Pos0, Pos1, a);\n\t\tif(CheckPoint(Pos.x, Pos.y))\n\t\t{\n\t\t\tif(pOutCollision)\n\t\t\t\t*pOutCollision = Pos;\n\t\t\tif(pOutBeforeCollision)\n\t\t\t\t*pOutBeforeCollision = Last;\n\t\t\treturn GetCollisionAt(Pos.x, Pos.y);\n\t\t}\n\t\tLast = Pos;\n\t}\n\tif(pOutCollision)\n\t\t*pOutCollision = Pos1;\n\tif(pOutBeforeCollision)\n\t\t*pOutBeforeCollision = Pos1;\n\treturn 0;\n}\n\n// TODO: OPT: rewrite this smarter!\nvoid CCollision::MovePoint(vec2 *pInoutPos, vec2 *pInoutVel, float Elasticity, int *pBounces)\n{\n\tif(pBounces)\n\t\t*pBounces = 0;\n\n\tvec2 Pos = *pInoutPos;\n\tvec2 Vel = *pInoutVel;\n\tif(CheckPoint(Pos + Vel))\n\t{\n\t\tint Affected = 0;\n\t\tif(CheckPoint(Pos.x + Vel.x, Pos.y))\n\t\t{\n\t\t\tpInoutVel->x *= -Elasticity;\n\t\t\tif(pBounces)\n\t\t\t\t(*pBounces)++;\n\t\t\tAffected++;\n\t\t}\n\n\t\tif(CheckPoint(Pos.x, Pos.y + Vel.y))\n\t\t{\n\t\t\tpInoutVel->y *= -Elasticity;\n\t\t\tif(pBounces)\n\t\t\t\t(*pBounces)++;\n\t\t\tAffected++;\n\t\t}\n\n\t\tif(Affected == 0)\n\t\t{\n\t\t\tpInoutVel->x *= -Elasticity;\n\t\t\tpInoutVel->y *= -Elasticity;\n\t\t}\n\t}\n\telse\n\t{\n\t\t*pInoutPos = Pos + Vel;\n\t}\n}\n\nbool CCollision::TestBox(vec2 Pos, vec2 Size)\n{\n\tSize *= 0.5f;\n\tif(CheckPoint(Pos.x-Size.x, Pos.y-Size.y))\n\t\treturn true;\n\tif(CheckPoint(Pos.x+Size.x, Pos.y-Size.y))\n\t\treturn true;\n\tif(CheckPoint(Pos.x-Size.x, Pos.y+Size.y))\n\t\treturn true;\n\tif(CheckPoint(Pos.x+Size.x, Pos.y+Size.y))\n\t\treturn true;\n\treturn false;\n}\n\nvoid CCollision::MoveBox(vec2 *pInoutPos, vec2 *pInoutVel, vec2 Size, float Elasticity)\n{\n\t// do the move\n\tvec2 Pos = *pInoutPos;\n\tvec2 Vel = *pInoutVel;\n\n\tfloat Distance = length(Vel);\n\tint Max = (int)Distance;\n\n\tif(Distance > 0.00001f)\n\t{\n\t\t//vec2 old_pos = pos;\n\t\tfloat Fraction = 1.0f/(float)(Max+1);\n\t\tfor(int i = 0; i <= Max; i++)\n\t\t{\n\t\t\t//float amount = i/(float)max;\n\t\t\t//if(max == 0)\n\t\t\t\t//amount = 0;\n\n\t\t\tvec2 NewPos = Pos + Vel*Fraction; // TODO: this row is not nice\n\n\t\t\tif(TestBox(vec2(NewPos.x, NewPos.y), Size))\n\t\t\t{\n\t\t\t\tint Hits = 0;\n\n\t\t\t\tif(TestBox(vec2(Pos.x, NewPos.y), Size))\n\t\t\t\t{\n\t\t\t\t\tNewPos.y = Pos.y;\n\t\t\t\t\tVel.y *= -Elasticity;\n\t\t\t\t\tHits++;\n\t\t\t\t}\n\n\t\t\t\tif(TestBox(vec2(NewPos.x, Pos.y), Size))\n\t\t\t\t{\n\t\t\t\t\tNewPos.x = Pos.x;\n\t\t\t\t\tVel.x *= -Elasticity;\n\t\t\t\t\tHits++;\n\t\t\t\t}\n\n\t\t\t\t// neither of the tests got a collision.\n\t\t\t\t// this is a real _corner case_!\n\t\t\t\tif(Hits == 0)\n\t\t\t\t{\n\t\t\t\t\tNewPos.y = Pos.y;\n\t\t\t\t\tVel.y *= -Elasticity;\n\t\t\t\t\tNewPos.x = Pos.x;\n\t\t\t\t\tVel.x *= -Elasticity;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tPos = NewPos;\n\t\t}\n\t}\n\n\t*pInoutPos = Pos;\n\t*pInoutVel = Vel;\n}\n"
  },
  {
    "path": "src/game/collision.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_COLLISION_H\n#define GAME_COLLISION_H\n\n#include <base/vmath.h>\n\nclass CCollision\n{\n\tclass CTile *m_pTiles;\n\tint m_Width;\n\tint m_Height;\n\tclass CLayers *m_pLayers;\n\n\tbool IsTileSolid(int x, int y);\n\tint GetTile(int x, int y);\n\npublic:\n\tenum\n\t{\n\t\tCOLFLAG_SOLID=1,\n\t\tCOLFLAG_DEATH=2,\n\t\tCOLFLAG_NOHOOK=4,\n\t};\n\n\tCCollision();\n\tvoid Init(class CLayers *pLayers);\n\tbool CheckPoint(float x, float y) { return IsTileSolid(round(x), round(y)); }\n\tbool CheckPoint(vec2 Pos) { return CheckPoint(Pos.x, Pos.y); }\n\tint GetCollisionAt(float x, float y) { return GetTile(round(x), round(y)); }\n\tint GetWidth() { return m_Width; };\n\tint GetHeight() { return m_Height; };\n\tint IntersectLine(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pOutBeforeCollision);\n\tvoid MovePoint(vec2 *pInoutPos, vec2 *pInoutVel, float Elasticity, int *pBounces);\n\tvoid MoveBox(vec2 *pInoutPos, vec2 *pInoutVel, vec2 Size, float Elasticity);\n\tbool TestBox(vec2 Pos, vec2 Size);\n};\n\n#endif\n"
  },
  {
    "path": "src/game/editor/auto_map.cpp",
    "content": "#include <engine/console.h>\n#include <engine/storage.h>\n\n#include \"auto_map.h\"\n#include \"editor.h\"\n\n\nvoid CTilesetMapper::Load(const json_value &rElement)\n{\n\tfor(unsigned i = 0; i < rElement.u.array.length; ++i)\n\t{\n\t\tif(rElement[i].u.object.length != 1)\n\t\t\tcontinue;\n\n\t\t// new rule set\n\t\tCRuleSet NewRuleSet;\n\t\tconst char* pConfName = rElement[i].u.object.values[0].name;\n\t\tstr_copy(NewRuleSet.m_aName, pConfName, sizeof(NewRuleSet.m_aName));\n\t\tconst json_value &rStart = *(rElement[i].u.object.values[0].value);\n\n\t\t// get basetile\n\t\tconst json_value &rBasetile = rStart[\"basetile\"];\n\t\tif(rBasetile.type == json_integer)\n\t\t\tNewRuleSet.m_BaseTile = clamp((int)rBasetile.u.integer, 0, 255);\n\t\telse\n\t\t\tNewRuleSet.m_BaseTile = 1;\n\n\t\t// get rules\n\t\tconst json_value &rRuleNode = rStart[\"rules\"];\n\t\tfor(unsigned j = 0; j < rRuleNode.u.array.length && j < MAX_RULES; j++)\n\t\t{\n\t\t\t// create a new rule\n\t\t\tCRule NewRule;\n\n\t\t\t// index\n\t\t\tconst json_value &rIndex = rRuleNode[j][\"index\"];\n\t\t\tif(rIndex.type == json_integer)\n\t\t\t\tNewRule.m_Index = clamp((int)rIndex.u.integer, 0, 255);\n\t\t\telse\n\t\t\t\tNewRule.m_Index = 1;\n\n\t\t\t// random\n\t\t\tconst json_value &rRandom = rRuleNode[j][\"random\"];\n\t\t\tif(rRandom.type == json_integer)\n\t\t\t\tNewRule.m_Random = clamp((int)rRandom.u.integer, 0, 99999);\n\t\t\telse\n\t\t\t\tNewRule.m_Random = 0;\n\n\t\t\t// rotate\n\t\t\tconst json_value &rRotate = rRuleNode[j][\"rotate\"];\n\t\t\tif(rRotate.type == json_integer && (rRotate.u.integer == 90 || rRotate.u.integer == 180 || rRotate.u.integer == 270))\n\t\t\t\tNewRule.m_Rotation = rRotate.u.integer;\n\t\t\telse\n\t\t\t\tNewRule.m_Rotation = 0;\n\n\t\t\t// hflip\n\t\t\tconst json_value &rHFlip = rRuleNode[j][\"hflip\"];\n\t\t\tif(rHFlip.type == json_integer)\n\t\t\t\tNewRule.m_HFlip = clamp((int)rHFlip.u.integer, 0, 1);\n\t\t\telse\n\t\t\t\tNewRule.m_HFlip = 0;\n\n\t\t\t// vflip\n\t\t\tconst json_value &rVFlip = rRuleNode[j][\"vflip\"];\n\t\t\tif(rVFlip.type == json_integer)\n\t\t\t\tNewRule.m_VFlip = clamp((int)rVFlip.u.integer, 0, 1);\n\t\t\telse\n\t\t\t\tNewRule.m_VFlip = 0;\n\n\t\t\t// get rule's content\n\t\t\tconst json_value &rCondition = rRuleNode[j][\"condition\"];\n\t\t\tif(rCondition.type == json_array)\n\t\t\t{\n\t\t\t\tfor(unsigned k = 0; k < rCondition.u.array.length; k++)\n\t\t\t\t{\n\t\t\t\t\tCRuleCondition Condition;\n\n\t\t\t\t\tCondition.m_X = rCondition[k][\"x\"].u.integer;\n\t\t\t\t\tCondition.m_Y = rCondition[k][\"y\"].u.integer;\n\t\t\t\t\tconst json_value &rValue = rCondition[k][\"value\"];\n\t\t\t\t\tif(rValue.type == json_string)\n\t\t\t\t\t{\n\t\t\t\t\t\t// the value is not an index, check if it's full or empty\n\t\t\t\t\t\tif(str_comp((const char *)rValue, \"full\") == 0)\n\t\t\t\t\t\t\tCondition.m_Value = CRuleCondition::FULL;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tCondition.m_Value = CRuleCondition::EMPTY;\n\t\t\t\t\t}\n\t\t\t\t\telse if(rValue.type == json_integer)\n\t\t\t\t\t\tCondition.m_Value = clamp((int)rValue.u.integer, (int)CRuleCondition::EMPTY, 255);\n\t\t\t\t\telse\n\t\t\t\t\t\tCondition.m_Value = CRuleCondition::EMPTY;\n\n\t\t\t\t\tNewRule.m_aConditions.add(Condition);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tNewRuleSet.m_aRules.add(NewRule);\n\t\t}\n\n\t\tm_aRuleSets.add(NewRuleSet);\n\t}\n}\n\nconst char* CTilesetMapper::GetRuleSetName(int Index)\n{\n\tif(Index < 0 || Index >= m_aRuleSets.size())\n\t\treturn \"\";\n\n\treturn m_aRuleSets[Index].m_aName;\n}\n\nvoid CTilesetMapper::Proceed(CLayerTiles *pLayer, int ConfigID)\n{\n\tif(pLayer->m_Readonly || ConfigID < 0 || ConfigID >= m_aRuleSets.size())\n\t\treturn;\n\n\tCRuleSet *pConf = &m_aRuleSets[ConfigID];\n\n\tif(!pConf->m_aRules.size())\n\t\treturn;\n\n\tint BaseTile = pConf->m_BaseTile;\n\n\t// auto map !\n\tint MaxIndex = pLayer->m_Width*pLayer->m_Height;\n\tfor(int y = 0; y < pLayer->m_Height; y++)\n\t\tfor(int x = 0; x < pLayer->m_Width; x++)\n\t\t{\n\t\t\tCTile *pTile = &(pLayer->m_pTiles[y*pLayer->m_Width+x]);\n\t\t\tif(pTile->m_Index == 0)\n\t\t\t\tcontinue;\n\n\t\t\tpTile->m_Index = BaseTile;\n\n\t\t\tif(y == 0 || y == pLayer->m_Height-1 || x == 0 || x == pLayer->m_Width-1)\n\t\t\t\tcontinue;\n\n\t\t\tfor(int i = 0; i < pConf->m_aRules.size(); ++i)\n\t\t\t{\n\t\t\t\tbool RespectRules = true;\n\t\t\t\tfor(int j = 0; j < pConf->m_aRules[i].m_aConditions.size() && RespectRules; ++j)\n\t\t\t\t{\n\t\t\t\t\tCRuleCondition *pCondition = &pConf->m_aRules[i].m_aConditions[j];\n\t\t\t\t\tint CheckIndex = (y+pCondition->m_Y)*pLayer->m_Width+(x+pCondition->m_X);\n\n\t\t\t\t\tif(CheckIndex < 0 || CheckIndex >= MaxIndex)\n\t\t\t\t\t\tRespectRules = false;\n\t\t\t\t\telse\n\t\t\t\t\t{\n \t\t\t\t\t\tif(pCondition->m_Value == CRuleCondition::EMPTY || pCondition->m_Value == CRuleCondition::FULL)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(pLayer->m_pTiles[CheckIndex].m_Index > 0 && pCondition->m_Value == CRuleCondition::EMPTY)\n\t\t\t\t\t\t\t\tRespectRules = false;\n\n\t\t\t\t\t\t\tif(pLayer->m_pTiles[CheckIndex].m_Index == 0 && pCondition->m_Value == CRuleCondition::FULL)\n\t\t\t\t\t\t\t\tRespectRules = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(pLayer->m_pTiles[CheckIndex].m_Index != pCondition->m_Value)\n\t\t\t\t\t\t\t\tRespectRules = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(RespectRules && (pConf->m_aRules[i].m_Random <= 1 || (int)((float)rand() / ((float)RAND_MAX + 1) * pConf->m_aRules[i].m_Random) == 1))\n\t\t\t\t{\n\t\t\t\t\tpTile->m_Index = pConf->m_aRules[i].m_Index;\n\n\t\t\t\t\t// rotate\n\t\t\t\t\tif(pConf->m_aRules[i].m_Rotation == 90)\n\t\t\t\t\t\tpTile->m_Flags ^= TILEFLAG_ROTATE;\n\t\t\t\t\telse if(pConf->m_aRules[i].m_Rotation == 180)\n\t\t\t\t\t\tpTile->m_Flags ^= (TILEFLAG_HFLIP|TILEFLAG_VFLIP);\n\t\t\t\t\telse if(pConf->m_aRules[i].m_Rotation == 270)\n\t\t\t\t\t\tpTile->m_Flags ^= (TILEFLAG_HFLIP|TILEFLAG_VFLIP|TILEFLAG_ROTATE);\n\n\t\t\t\t\t// flip\n\t\t\t\t\tif(pConf->m_aRules[i].m_HFlip)\n\t\t\t\t\t\tpTile->m_Flags ^= pTile->m_Flags&TILEFLAG_ROTATE ? TILEFLAG_HFLIP : TILEFLAG_VFLIP;\n\t\t\t\t\tif(pConf->m_aRules[i].m_VFlip)\n\t\t\t\t\t\tpTile->m_Flags ^= pTile->m_Flags&TILEFLAG_ROTATE ? TILEFLAG_VFLIP : TILEFLAG_HFLIP;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tm_pEditor->m_Map.m_Modified = true;\n}\n\nint CompareRules(const void *a, const void *b)\n{\n\tCDoodadsMapper::CRule *ra = (CDoodadsMapper::CRule*)a;\n\tCDoodadsMapper::CRule *rb = (CDoodadsMapper::CRule*)b;\n\n\tif((ra->m_Location == CDoodadsMapper::CRule::FLOOR && rb->m_Location == CDoodadsMapper::CRule::FLOOR)\n\t\t|| (ra->m_Location == CDoodadsMapper::CRule::CEILING && rb->m_Location  == CDoodadsMapper::CRule::CEILING))\n\t{\n\t\tif(ra->m_Size.x < rb->m_Size.x)\n\t\t\treturn +1;\n\t\tif(rb->m_Size.x < ra->m_Size.x)\n\t\t\treturn -1;\n\t}\n\telse if(ra->m_Location == CDoodadsMapper::CRule::WALLS && rb->m_Location == CDoodadsMapper::CRule::WALLS)\n\t{\n\t\tif(ra->m_Size.y < rb->m_Size.y)\n\t\t\treturn +1;\n\t\tif(rb->m_Size.y < ra->m_Size.y)\n\t\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n\nvoid CDoodadsMapper::Load(const json_value &rElement)\n{\n\tfor(unsigned i = 0; i < rElement.u.array.length; ++i)\n\t{\n\t\tif(rElement[i].u.object.length != 1)\n\t\t\tcontinue;\n\n\t\t// new rule set\n\t\tCRuleSet NewRuleSet;\n\t\tconst char* pConfName = rElement[i].u.object.values[0].name;\n\t\tstr_copy(NewRuleSet.m_aName, pConfName, sizeof(NewRuleSet.m_aName));\n\t\tconst json_value &rStart = *(rElement[i].u.object.values[0].value);\n\n\t\t// get rules\n\t\tconst json_value &rRuleNode = rStart[\"rules\"];\n\t\tfor(unsigned j = 0; j < rRuleNode.u.array.length && j < MAX_RULES; j++)\n\t\t{\n\t\t\t// create a new rule\n\t\t\tCRule NewRule;\n\n\t\t\t// startid\n\t\t\tconst json_value &rStartid = rRuleNode[j][\"startid\"];\n\t\t\tif(rStartid.type == json_integer)\n\t\t\t\tNewRule.m_Rect.x = clamp((int)rStartid.u.integer, 0, 255);\n\t\t\telse\n\t\t\t\tNewRule.m_Rect.x = 1;\n\n\t\t\t// endid\n\t\t\tconst json_value &rEndid = rRuleNode[j][\"endid\"];\n\t\t\tif(rEndid.type == json_integer)\n\t\t\t\tNewRule.m_Rect.y = clamp((int)rEndid.u.integer, 0, 255);\n\t\t\telse\n\t\t\t\tNewRule.m_Rect.y = 1;\n\n\t\t\t// broken, skip\n\t\t\tif(NewRule.m_Rect.x > NewRule.m_Rect.y)\n\t\t\t\tcontinue;\n\n\t\t\t// rx\n\t\t\tconst json_value &rRx = rRuleNode[j][\"rx\"];\n\t\t\tif(rRx.type == json_integer)\n\t\t\t\tNewRule.m_RelativePos.x = rRx.u.integer;\n\t\t\telse\n\t\t\t\tNewRule.m_RelativePos.x = 0;\n\n\t\t\t// ry\n\t\t\tconst json_value &rRy = rRuleNode[j][\"ry\"];\n\t\t\tif(rRy.type == json_integer)\n\t\t\t\tNewRule.m_RelativePos.y = rRy.u.integer;\n\t\t\telse\n\t\t\t\tNewRule.m_RelativePos.y = 0;\n\n\t\t\t// width\n\t\t\tNewRule.m_Size.x = absolute(NewRule.m_Rect.x-NewRule.m_Rect.y)%16+1;\n\t\t\t// height\n\t\t\tNewRule.m_Size.y = floor((float)absolute(NewRule.m_Rect.x-NewRule.m_Rect.y)/16)+1;\n\n\t\t\t// random\n\t\t\tconst json_value &rRandom = rRuleNode[j][\"random\"];\n\t\t\tif(rRandom.type == json_integer)\n\t\t\t\tNewRule.m_Random = clamp((int)rRandom.u.integer, 1, 99999);\n\t\t\telse\n\t\t\t\tNewRule.m_Random = 1;\n\n\t\t\t// hflip\n\t\t\tconst json_value &rHFlip = rRuleNode[j][\"hflip\"];\n\t\t\tif(rHFlip.type == json_integer)\n\t\t\t\tNewRule.m_HFlip = clamp((int)rHFlip.u.integer, 0, 1);\n\t\t\telse\n\t\t\t\tNewRule.m_HFlip = 0;\n\n\t\t\t// vflip\n\t\t\tconst json_value &rVFlip = rRuleNode[j][\"vflip\"];\n\t\t\tif(rVFlip.type == json_integer)\n\t\t\t\tNewRule.m_VFlip = clamp((int)rVFlip.u.integer, 0, 1);\n\t\t\telse\n\t\t\t\tNewRule.m_VFlip = 0;\n\n\t\t\t// location\n\t\t\tNewRule.m_Location = CRule::FLOOR;\n\t\t\tconst json_value &rLocation = rRuleNode[j][\"location\"];\n\t\t\tif(rLocation.type == json_string)\n\t\t\t{\n\t\t\t\tif(str_comp((const char *)rLocation, \"ceiling\") == 0)\n\t\t\t\t\tNewRule.m_Location = CRule::CEILING;\n\t\t\t\telse if(str_comp((const char *)rLocation, \"walls\") == 0)\n\t\t\t\t\tNewRule.m_Location = CRule::WALLS;\n\t\t\t}\n\n\t\t\tNewRuleSet.m_aRules.add(NewRule);\n\t\t}\n\n\t\tm_aRuleSets.add(NewRuleSet);\n\t}\n\n\t// sort\n\tfor(int i = 0; i < m_aRuleSets.size(); i++)\n\t\tqsort(m_aRuleSets[i].m_aRules.base_ptr(), m_aRuleSets[i].m_aRules.size(), sizeof(m_aRuleSets[i].m_aRules[0]), CompareRules);\n}\n\nconst char* CDoodadsMapper::GetRuleSetName(int Index)\n{\n\tif(Index < 0 || Index >= m_aRuleSets.size())\n\t\treturn \"\";\n\n\treturn m_aRuleSets[Index].m_aName;\n}\n\nvoid CDoodadsMapper::AnalyzeGameLayer()\n{\n\t// the purpose of this is to detect game layer collision's edges to place doodads according to them\n\n\t// clear existing edges\n\tm_FloorIDs.clear();\n\tm_CeilingIDs.clear();\n\tm_RightWallIDs.clear();\n\tm_LeftWallIDs.clear();\n\n\tCLayerGame *pLayer = m_pEditor->m_Map.m_pGameLayer;\n\n\tbool FloorKeepChaining = false;\n\tbool CeilingKeepChaining = false;\n\tint FloorChainID = 0;\n\tint CeilingChainID = 0;\n\n\t// floors and ceilings\n\t// browse up to down\n\tfor(int y = 1; y < pLayer->m_Height-1; y++)\n\t{\n\t\tFloorKeepChaining = false;\n\t\tCeilingKeepChaining = false;\n\n\t\tfor(int x = 1; x < pLayer->m_Width-1; x++)\n\t\t{\n\t\t\tCTile *pTile = &(pLayer->m_pTiles[y*pLayer->m_Width+x]);\n\n\t\t\t// empty, skip\n\t\t\tif(pTile->m_Index == 0)\n\t\t\t{\n\t\t\t\tFloorKeepChaining = false;\n\t\t\t\tCeilingKeepChaining = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// check up\n\t\t\tint CheckIndex = (y-1)*pLayer->m_Width+x;\n\n\t\t\t// add a floor part\n\t\t\tif(pTile->m_Index == 1 && (pLayer->m_pTiles[CheckIndex].m_Index == 0 || pLayer->m_pTiles[CheckIndex].m_Index > ENTITY_OFFSET))\n\t\t\t{\n\t\t\t\t// create an new chain\n\t\t\t\tif(!FloorKeepChaining)\n\t\t\t\t{\n\t\t\t\t\tarray<int> aChain;\n\t\t\t\t\taChain.add(y*pLayer->m_Width+x);\n\t\t\t\t\tFloorChainID = m_FloorIDs.add(aChain);\n\t\t\t\t\tFloorKeepChaining = true;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// keep chaining\n\t\t\t\t\tm_FloorIDs[FloorChainID].add(y*pLayer->m_Width+x);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\tFloorKeepChaining = false;\n\n\t\t\t// check down\n\t\t\tCheckIndex = (y+1)*pLayer->m_Width+x;\n\n\t\t\t// add a ceiling part\n\t\t\tif(pTile->m_Index == 1 && (pLayer->m_pTiles[CheckIndex].m_Index == 0 || pLayer->m_pTiles[CheckIndex].m_Index > ENTITY_OFFSET))\n\t\t\t{\n\t\t\t\t// create an new chain\n\t\t\t\tif(!CeilingKeepChaining)\n\t\t\t\t{\n\t\t\t\t\tarray<int> aChain;\n\t\t\t\t\taChain.add(y*pLayer->m_Width+x);\n\t\t\t\t\tCeilingChainID = m_CeilingIDs.add(aChain);\n\t\t\t\t\tCeilingKeepChaining = true;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// keep chaining\n\t\t\t\t\tm_CeilingIDs[CeilingChainID].add(y*pLayer->m_Width+x);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\tCeilingKeepChaining = false;\n\t\t}\n\t}\n\n\tbool RWallKeepChaining = false;\n\tbool LWallKeepChaining = false;\n\tint RWallChainID = 0;\n\tint LWallChainID = 0;\n\n\t// walls\n\t// browse left to right\n\tfor(int x = 1; x < pLayer->m_Width-1; x++)\n\t{\n\t\tRWallKeepChaining = false;\n\t\tLWallKeepChaining = false;\n\n\t\tfor(int y = 1; y < pLayer->m_Height-1; y++)\n\t\t{\n\t\t\tCTile *pTile = &(pLayer->m_pTiles[y*pLayer->m_Width+x]);\n\n\t\t\tif(pTile->m_Index == 0)\n\t\t\t{\n\t\t\t\tRWallKeepChaining = false;\n\t\t\t\tLWallKeepChaining = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// check right\n\t\t\tint CheckIndex = y*pLayer->m_Width+(x+1);\n\n\t\t\t// add a right wall part\n\t\t\tif(pTile->m_Index == 1 && (pLayer->m_pTiles[CheckIndex].m_Index == 0 || pLayer->m_pTiles[CheckIndex].m_Index > ENTITY_OFFSET))\n\t\t\t{\n\t\t\t\t// create an new chain\n\t\t\t\tif(!RWallKeepChaining)\n\t\t\t\t{\n\t\t\t\t\tarray<int> aChain;\n\t\t\t\t\taChain.add(y*pLayer->m_Width+x);\n\t\t\t\t\tRWallChainID = m_RightWallIDs.add(aChain);\n\t\t\t\t\tRWallKeepChaining = true;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// keep chaining\n\t\t\t\t\tm_RightWallIDs[RWallChainID].add(y*pLayer->m_Width+x);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\tRWallKeepChaining = false;\n\n\t\t\t// check left\n\t\t\tCheckIndex = y*pLayer->m_Width+(x-1);\n\n\t\t\t// add a left wall part\n\t\t\tif(pTile->m_Index == 1 && (pLayer->m_pTiles[CheckIndex].m_Index == 0 || pLayer->m_pTiles[CheckIndex].m_Index > ENTITY_OFFSET))\n\t\t\t{\n\t\t\t\t// create an new chain\n\t\t\t\tif(!LWallKeepChaining)\n\t\t\t\t{\n\t\t\t\t\tarray<int> aChain;\n\t\t\t\t\taChain.add(y*pLayer->m_Width+x);\n\t\t\t\t\tLWallChainID = m_LeftWallIDs.add(aChain);\n\t\t\t\t\tLWallKeepChaining = true;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// keep chaining\n\t\t\t\t\tm_LeftWallIDs[LWallChainID].add(y*pLayer->m_Width+x);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\tLWallKeepChaining = false;\n\t\t}\n\t}\n\n\t// clean up too small chains\n\tfor(int i = 0; i < m_FloorIDs.size(); i++)\n\t{\n\t\tif(m_FloorIDs[i].size() < 3)\n\t\t{\n\t\t\tm_FloorIDs.remove_index_fast(i);\n\t\t\ti--;\n\t\t}\n\t}\n\n\tfor(int i = 0; i < m_CeilingIDs.size(); i++)\n\t{\n\t\tif(m_CeilingIDs[i].size() < 3)\n\t\t{\n\t\t\tm_CeilingIDs.remove_index_fast(i);\n\t\t\ti--;\n\t\t}\n\t}\n\n\tfor(int i = 0; i < m_RightWallIDs.size(); i++)\n\t{\n\t\tif(m_RightWallIDs[i].size() < 3)\n\t\t{\n\t\t\tm_RightWallIDs.remove_index_fast(i);\n\t\t\ti--;\n\t\t}\n\t}\n\n\tfor(int i = 0; i < m_LeftWallIDs.size(); i++)\n\t{\n\t\tif(m_LeftWallIDs[i].size() < 3)\n\t\t{\n\t\t\tm_LeftWallIDs.remove_index_fast(i);\n\t\t\ti--;\n\t\t}\n\t}\n}\n\nvoid CDoodadsMapper::PlaceDoodads(CLayerTiles *pLayer, CRule *pRule, array<array<int> > *pPositions, int Amount, int LeftWall)\n{\n\tif(pRule->m_Location == CRule::CEILING)\n\t\tpRule->m_RelativePos.y++;\n\telse if(pRule->m_Location == CRule::WALLS)\n\t\tpRule->m_RelativePos.x++;\n\n\t// left walls\n\tif(LeftWall)\n\t{\n\t\tpRule->m_HFlip ^= LeftWall;\n\t\tpRule->m_RelativePos.x--;\n\t\tpRule->m_RelativePos.x = -pRule->m_RelativePos.x;\n\t\tpRule->m_RelativePos.x -= pRule->m_Size.x-1;\n\t}\n\n\tint MaxIndex = pLayer->m_Width*pLayer->m_Height;\n\tint RandomValue = pRule->m_Random*((101.f-Amount)/100.0f);\n\n\tif(pRule->m_Random == 1)\n\t\tRandomValue = 1;\n\n\t// allow diversity with high Amount\n\tif(pRule->m_Random > 1 && RandomValue <= 1)\n\t\tRandomValue = 2;\n\n\tfor(int f = 0; f < pPositions->size(); f++)\n\t\tfor(int c = 0; c < (*pPositions)[f].size(); c += pRule->m_Size.x)\n\t\t{\n\t\t\tif((pRule->m_Location == CRule::FLOOR || pRule->m_Location == CRule::CEILING)\n\t\t\t\t&& (*pPositions)[f].size()-c < pRule->m_Size.x)\n\t\t\tbreak;\n\n\t\t\tif(pRule->m_Location == CRule::WALLS && (*pPositions)[f].size()-c < pRule->m_Size.y)\n\t\t\t\tbreak;\n\n\t\t\tif(RandomValue > 1 && !IAutoMapper::Random(RandomValue))\n\t\t\t\tcontinue;\n\n\t\t\t// where to put it\n\t\t\tint ID = (*pPositions)[f][c];\n\n\t\t\t// relative position\n\t\t\tID += pRule->m_RelativePos.x;\n\t\t\tID += pRule->m_RelativePos.y*pLayer->m_Width;\n\n\t\t\tfor(int y = 0; y < pRule->m_Size.y; y++)\n\t\t\t\tfor(int x = 0; x < pRule->m_Size.x; x++)\n\t\t\t\t{\n\t\t\t\t\tint Index = y*pLayer->m_Width+x+ID;\n\t\t\t\t\tif(Index <= 0 || Index >= MaxIndex)\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tpLayer->m_pTiles[Index].m_Index = pRule->m_Rect.x+y*16+x;\n\t\t\t\t}\n\n\t\t\t// hflip\n\t\t\tif(pRule->m_HFlip)\n\t\t\t{\n\t\t\t\tfor(int y = 0; y < pRule->m_Size.y; y++)\n\t\t\t\t\tfor(int x = 0; x < pRule->m_Size.x/2; x++)\n\t\t\t\t\t{\n\t\t\t\t\t\tint Index = y*pLayer->m_Width+x+ID;\n\t\t\t\t\t\tif(Index <= 0 || Index >= MaxIndex)\n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\tint CheckIndex = Index+pRule->m_Size.x-1-x*2;\n\n\t\t\t\t\t\tif(CheckIndex <= 0 || CheckIndex >= MaxIndex)\n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\tCTile Tmp = pLayer->m_pTiles[Index];\n\t\t\t\t\t\tpLayer->m_pTiles[Index] = pLayer->m_pTiles[CheckIndex];\n\t\t\t\t\t\tpLayer->m_pTiles[CheckIndex] = Tmp;\n\t\t\t\t\t}\n\n\t\t\t\tfor(int y = 0; y < pRule->m_Size.y; y++)\n\t\t\t\t\tfor(int x = 0; x < pRule->m_Size.x; x++)\n\t\t\t\t\t{\n\t\t\t\t\t\tint Index = y*pLayer->m_Width+x+ID;\n\t\t\t\t\t\tif(Index <= 0 || Index >= MaxIndex)\n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\tpLayer->m_pTiles[Index].m_Flags ^= TILEFLAG_VFLIP;\n\t\t\t\t\t}\n\t\t\t}\n\n\t\t\t// vflip\n\t\t\tif(pRule->m_VFlip)\n\t\t\t{\n\t\t\t\tfor(int y = 0; y < pRule->m_Size.y/2; y++)\n\t\t\t\t\tfor(int x = 0; x < pRule->m_Size.x; x++)\n\t\t\t\t\t{\n\t\t\t\t\t\tint Index = y*pLayer->m_Width+x+ID;\n\t\t\t\t\t\tif(Index <= 0 || Index >= MaxIndex)\n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\tint CheckIndex = Index+(pRule->m_Size.y-1-y*2)*pLayer->m_Width;\n\n\t\t\t\t\t\tif(CheckIndex <= 0 || CheckIndex >= MaxIndex)\n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\tCTile Tmp = pLayer->m_pTiles[Index];\n\t\t\t\t\t\tpLayer->m_pTiles[Index] = pLayer->m_pTiles[CheckIndex];\n\t\t\t\t\t\tpLayer->m_pTiles[CheckIndex] = Tmp;\n\t\t\t\t\t}\n\n\t\t\t\tfor(int y = 0; y < pRule->m_Size.y; y++)\n\t\t\t\t\tfor(int x = 0; x < pRule->m_Size.x; x++)\n\t\t\t\t\t{\n\t\t\t\t\t\tint Index = y*pLayer->m_Width+x+ID;\n\t\t\t\t\t\tif(Index <= 0 || Index >= MaxIndex)\n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\tpLayer->m_pTiles[Index].m_Flags ^= TILEFLAG_HFLIP;\n\t\t\t\t\t}\n\t\t\t}\n\n\t\t\t// make the place occupied\n\t\t\tif(RandomValue > 1)\n\t\t\t{\n\t\t\t\tarray<int> aChainBefore;\n\t\t\t\tarray<int> aChainAfter;\n\n\t\t\t\tfor(int j = 0; j < c; j++)\n\t\t\t\t\taChainBefore.add((*pPositions)[f][j]);\n\n\t\t\t\tint Size = pRule->m_Size.x;\n\t\t\t\tif(pRule->m_Location == CRule::WALLS)\n\t\t\t\t\tSize = pRule->m_Size.y;\n\n\t\t\t\tfor(int j = c+Size; j < (*pPositions)[f].size(); j++)\n\t\t\t\t\taChainAfter.add((*pPositions)[f][j]);\n\n\t\t\t\tpPositions->remove_index(f);\n\n\t\t\t\t// f changes, reset c\n\t\t\t\tc = -1;\n\n\t\t\t\tif(aChainBefore.size() > 1)\n\t\t\t\t\tpPositions->add(aChainBefore);\n\t\t\t\tif(aChainAfter.size() > 1)\n\t\t\t\t\tpPositions->add(aChainAfter);\n\t\t\t}\n\t\t}\n}\n\nvoid CDoodadsMapper::Proceed(CLayerTiles *pLayer, int ConfigID, int Amount)\n{\n\tif(pLayer->m_Readonly || ConfigID < 0 || ConfigID >= m_aRuleSets.size())\n\t\treturn;\n\n\tAnalyzeGameLayer();\n\n\tCRuleSet *pConf = &m_aRuleSets[ConfigID];\n\n\tif(!pConf->m_aRules.size())\n\t\treturn;\n\n\tint MaxIndex = pLayer->m_Width*pLayer->m_Height;\n\n\t// clear tiles\n\tfor(int i = 0 ; i < MaxIndex; i++)\n\t{\n\t\tpLayer->m_pTiles[i].m_Index = 0;\n\t\tpLayer->m_pTiles[i].m_Flags = 0;\n\t}\n\n\t// place doodads\n\tfor(int i = 0 ; i < pConf->m_aRules.size(); i++)\n\t{\n\t\tCRule *pRule = &pConf->m_aRules[i];\n\n\t\t// floors\n\t\tif(pRule->m_Location == CRule::FLOOR && m_FloorIDs.size() > 0)\n\t\t{\n\t\t\tPlaceDoodads(pLayer, pRule, &m_FloorIDs, Amount);\n\t\t}\n\n\t\t// ceilings\n\t\tif(pRule->m_Location == CRule::CEILING && m_CeilingIDs.size() > 0)\n\t\t{\n\t\t\tPlaceDoodads(pLayer, pRule, &m_CeilingIDs, Amount);\n\t\t}\n\n\t\t// right walls\n\t\tif(pRule->m_Location == CRule::WALLS && m_RightWallIDs.size() > 0)\n\t\t{\n\t\t\tPlaceDoodads(pLayer, pRule, &m_RightWallIDs, Amount);\n\t\t}\n\n\t\t// left walls\n\t\tif(pRule->m_Location == CRule::WALLS && m_LeftWallIDs.size() > 0)\n\t\t{\n\t\t\tPlaceDoodads(pLayer, pRule, &m_LeftWallIDs, Amount, 1);\n\t\t}\n\t}\n\n\tm_pEditor->m_Map.m_Modified = true;\n}\n"
  },
  {
    "path": "src/game/editor/auto_map.h",
    "content": "#ifndef GAME_EDITOR_AUTO_MAP_H\n#define GAME_EDITOR_AUTO_MAP_H\n\n#include <stdlib.h> // rand\n\n#include <base/tl/array.h>\n#include <base/vmath.h>\n\n#include <engine/external/json-parser/json.h>\n\n\nclass IAutoMapper\n{\nprotected:\n\tclass CEditor *m_pEditor;\n\tint m_Type;\n\npublic:\n\tenum\n\t{\n\t\tTYPE_TILESET,\n\t\tTYPE_DOODADS,\n\n\t\tMAX_RULES=256\n\t};\n\n\t//\n\tIAutoMapper(class CEditor *pEditor, int Type) : m_pEditor(pEditor), m_Type(Type) {}\n\tvirtual ~IAutoMapper() {};\n\tvirtual void Load(const json_value &rElement) = 0;\n\tvirtual void Proceed(class CLayerTiles *pLayer, int ConfigID) {}\n\tvirtual void Proceed(class CLayerTiles *pLayer, int ConfigID, int Ammount) {} // for convenience purposes\n\n\tvirtual int RuleSetNum() = 0;\n\tvirtual const char* GetRuleSetName(int Index) = 0;\n\n\t//\n\tint GetType() { return m_Type; }\n\n\tstatic bool Random(int Value)\n\t{\n\t\treturn ((int)((float)rand() / ((float)RAND_MAX + 1) * Value) == 1);\n\t}\n\n\tstatic const char *GetTypeName(int Type)\n\t{\n\t\tif(Type == TYPE_TILESET)\n\t\t\treturn \"tileset\";\n\t\telse if(Type == TYPE_DOODADS)\n\t\t\treturn \"doodads\";\n\t\telse\n\t\t\treturn \"\";\n\t}\n};\n\nclass CTilesetMapper: public IAutoMapper\n{\n\tstruct CRuleCondition\n\t{\n\t\tint m_X;\n\t\tint m_Y;\n\t\tint m_Value;\n\n\t\tenum\n\t\t{\n\t\t\tEMPTY=-2,\n\t\t\tFULL=-1\n\t\t};\n\t};\n\n\tstruct CRule\n\t{\n\t\tint m_Index;\n\t\tint m_HFlip;\n\t\tint m_VFlip;\n\t\tint m_Random;\n\t\tint m_Rotation;\n\n\t\tarray<CRuleCondition> m_aConditions;\n\t};\n\n\tstruct CRuleSet\n\t{\n\t\tchar m_aName[128];\n\t\tint m_BaseTile;\n\n\t\tarray<CRule> m_aRules;\n\t};\n\n\tarray<CRuleSet> m_aRuleSets;\n\npublic:\n\tCTilesetMapper(class CEditor *pEditor) : IAutoMapper(pEditor, TYPE_TILESET) { m_aRuleSets.clear(); }\n\n\tvirtual void Load(const json_value &rElement);\n\tvirtual void Proceed(class CLayerTiles *pLayer, int ConfigID);\n\n\tvirtual int RuleSetNum() { return m_aRuleSets.size(); }\n\tvirtual const char* GetRuleSetName(int Index);\n};\n\nclass CDoodadsMapper: public IAutoMapper\n{\npublic:\n\tstruct CRule\n\t{\n\t\tivec2 m_Rect;\n\t\tivec2 m_Size;\n\t\tivec2 m_RelativePos;\n\n\t\tint m_Location;\n\t\tint m_Random;\n\n\t\tint m_HFlip;\n\t\tint m_VFlip;\n\n\t\tenum\n\t\t{\n\t\t\tFLOOR=0,\n\t\t\tCEILING,\n\t\t\tWALLS\n\t\t};\n\t};\n\n\tstruct CRuleSet\n\t{\n\t\tchar m_aName[128];\n\n\t\tarray<CRule> m_aRules;\n\t};\n\n\tCDoodadsMapper(class CEditor *pEditor) :  IAutoMapper(pEditor, TYPE_DOODADS) { m_aRuleSets.clear(); }\n\n\tvirtual void Load(const json_value &rElement);\n\tvirtual void Proceed(class CLayerTiles *pLayer, int ConfigID, int Amount);\n\tvoid AnalyzeGameLayer();\n\n\tvirtual int RuleSetNum() { return m_aRuleSets.size(); }\n\tvirtual const char* GetRuleSetName(int Index);\n\nprivate:\n\tvoid PlaceDoodads(CLayerTiles *pLayer, CRule *pRule, array<array<int> > *pPositions, int Amount, int LeftWall = 0);\n\n\tarray<CRuleSet> m_aRuleSets;\n\n\tarray<array<int> > m_FloorIDs;\n\tarray<array<int> > m_CeilingIDs;\n\tarray<array<int> > m_RightWallIDs;\n\tarray<array<int> > m_LeftWallIDs;\n};\n\n#endif\n"
  },
  {
    "path": "src/game/editor/editor.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n\n#include <base/system.h>\n\n#include <engine/shared/datafile.h>\n#include <engine/shared/config.h>\n#include <engine/client.h>\n#include <engine/console.h>\n#include <engine/graphics.h>\n#include <engine/input.h>\n#include <engine/keys.h>\n#include <engine/storage.h>\n#include <engine/textrender.h>\n\n#include <game/gamecore.h>\n#include <game/client/lineinput.h>\n#include <game/client/localization.h>\n#include <game/client/render.h>\n#include <game/client/ui.h>\n#include <game/generated/client_data.h>\n\n#include \"auto_map.h\"\n#include \"editor.h\"\n\nconst void* CEditor::ms_pUiGotContext;\n\nenum\n{\n\tBUTTON_CONTEXT=1,\n};\n\nCEditorImage::~CEditorImage()\n{\n\tm_pEditor->Graphics()->UnloadTexture(m_Texture);\n\tif(m_pData)\n\t{\n\t\tmem_free(m_pData);\n\t\tm_pData = 0;\n\t}\n\tif(m_pAutoMapper)\n\t{\n\t\tdelete m_pAutoMapper;\n\t\tm_pAutoMapper = 0;\n\t}\n}\n\nCLayerGroup::CLayerGroup()\n{\n\tm_aName[0] = 0;\n\tm_Visible = true;\n\tm_SaveToMap = true;\n\tm_Collapse = false;\n\tm_GameGroup = false;\n\tm_OffsetX = 0;\n\tm_OffsetY = 0;\n\tm_ParallaxX = 100;\n\tm_ParallaxY = 100;\n\n\tm_UseClipping = 0;\n\tm_ClipX = 0;\n\tm_ClipY = 0;\n\tm_ClipW = 0;\n\tm_ClipH = 0;\n}\n\nCLayerGroup::~CLayerGroup()\n{\n\tClear();\n}\n\nvoid CLayerGroup::Convert(CUIRect *pRect)\n{\n\tpRect->x += m_OffsetX;\n\tpRect->y += m_OffsetY;\n}\n\nvoid CLayerGroup::Mapping(float *pPoints)\n{\n\tm_pMap->m_pEditor->RenderTools()->MapscreenToWorld(\n\t\tm_pMap->m_pEditor->m_WorldOffsetX, m_pMap->m_pEditor->m_WorldOffsetY,\n\t\tm_ParallaxX/100.0f, m_ParallaxY/100.0f,\n\t\tm_OffsetX, m_OffsetY,\n\t\tm_pMap->m_pEditor->Graphics()->ScreenAspect(), m_pMap->m_pEditor->m_WorldZoom, pPoints);\n\n\tpPoints[0] += m_pMap->m_pEditor->m_EditorOffsetX;\n\tpPoints[1] += m_pMap->m_pEditor->m_EditorOffsetY;\n\tpPoints[2] += m_pMap->m_pEditor->m_EditorOffsetX;\n\tpPoints[3] += m_pMap->m_pEditor->m_EditorOffsetY;\n}\n\nvoid CLayerGroup::MapScreen()\n{\n\tfloat aPoints[4];\n\tMapping(aPoints);\n\tm_pMap->m_pEditor->Graphics()->MapScreen(aPoints[0], aPoints[1], aPoints[2], aPoints[3]);\n}\n\nvoid CLayerGroup::Render()\n{\n\tMapScreen();\n\tIGraphics *pGraphics = m_pMap->m_pEditor->Graphics();\n\n\tif(m_UseClipping)\n\t{\n\t\tfloat aPoints[4];\n\t\tm_pMap->m_pGameGroup->Mapping(aPoints);\n\t\tfloat x0 = (m_ClipX - aPoints[0]) / (aPoints[2]-aPoints[0]);\n\t\tfloat y0 = (m_ClipY - aPoints[1]) / (aPoints[3]-aPoints[1]);\n\t\tfloat x1 = ((m_ClipX+m_ClipW) - aPoints[0]) / (aPoints[2]-aPoints[0]);\n\t\tfloat y1 = ((m_ClipY+m_ClipH) - aPoints[1]) / (aPoints[3]-aPoints[1]);\n\n\t\tpGraphics->ClipEnable((int)(x0*pGraphics->ScreenWidth()), (int)(y0*pGraphics->ScreenHeight()),\n\t\t\t(int)((x1-x0)*pGraphics->ScreenWidth()), (int)((y1-y0)*pGraphics->ScreenHeight()));\n\t}\n\n\tfor(int i = 0; i < m_lLayers.size(); i++)\n\t{\n\t\tif(m_lLayers[i]->m_Visible && m_lLayers[i] != m_pMap->m_pGameLayer)\n\t\t{\n\t\t\tif(m_pMap->m_pEditor->m_ShowDetail || !(m_lLayers[i]->m_Flags&LAYERFLAG_DETAIL))\n\t\t\t\tm_lLayers[i]->Render();\n\t\t}\n\t}\n\n\tpGraphics->ClipDisable();\n}\n\nvoid CLayerGroup::AddLayer(CLayer *l)\n{\n\tm_pMap->m_Modified = true;\n\tm_lLayers.add(l);\n}\n\nvoid CLayerGroup::DeleteLayer(int Index)\n{\n\tif(Index < 0 || Index >= m_lLayers.size()) return;\n\tdelete m_lLayers[Index];\n\tm_lLayers.remove_index(Index);\n\tm_pMap->m_Modified = true;\n}\n\nvoid CLayerGroup::GetSize(float *w, float *h)\n{\n\t*w = 0; *h = 0;\n\tfor(int i = 0; i < m_lLayers.size(); i++)\n\t{\n\t\tfloat lw, lh;\n\t\tm_lLayers[i]->GetSize(&lw, &lh);\n\t\t*w = max(*w, lw);\n\t\t*h = max(*h, lh);\n\t}\n}\n\n\nint CLayerGroup::SwapLayers(int Index0, int Index1)\n{\n\tif(Index0 < 0 || Index0 >= m_lLayers.size()) return Index0;\n\tif(Index1 < 0 || Index1 >= m_lLayers.size()) return Index0;\n\tif(Index0 == Index1) return Index0;\n\tm_pMap->m_Modified = true;\n\tswap(m_lLayers[Index0], m_lLayers[Index1]);\n\treturn Index1;\n}\n\nvoid CEditorImage::AnalyseTileFlags()\n{\n\tif(m_Format == CImageInfo::FORMAT_RGB)\n\t{\n\t\tfor(int i = 0; i < 256; ++i)\n\t\t\tm_aTileFlags[i] = TILEFLAG_OPAQUE;\n\t}\n\telse\n\t{\n\t\tmem_zero(m_aTileFlags, sizeof(m_aTileFlags));\n\n\t\tint tw = m_Width/16; // tilesizes\n\t\tint th = m_Height/16;\n\t\tif(tw == th)\n\t\t{\n\t\t\tunsigned char *pPixelData = (unsigned char *)m_pData;\n\n\t\t\tint TileID = 0;\n\t\t\tfor(int ty = 0; ty < 16; ty++)\n\t\t\t\tfor(int tx = 0; tx < 16; tx++, TileID++)\n\t\t\t\t{\n\t\t\t\t\tbool Opaque = true;\n\t\t\t\t\tfor(int x = 0; x < tw; x++)\n\t\t\t\t\t\tfor(int y = 0; y < th; y++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint p = (ty*tw+y)*m_Width + tx*tw+x;\n\t\t\t\t\t\t\tif(pPixelData[p*4+3] < 250)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tOpaque = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\tif(Opaque)\n\t\t\t\t\t\tm_aTileFlags[TileID] |= TILEFLAG_OPAQUE;\n\t\t\t\t}\n\t\t}\n\t}\n}\n\nvoid CEditorImage::LoadAutoMapper()\n{\n\tif(m_pAutoMapper)\n\t\treturn;\n\n\t// read file data into buffer\n\tchar aBuf[256];\n\tstr_format(aBuf, sizeof(aBuf), \"editor/automap/%s.json\", m_aName);\n\tIOHANDLE File = m_pEditor->Storage()->OpenFile(aBuf, IOFLAG_READ, IStorage::TYPE_ALL);\n\tif(!File)\n\t\treturn;\n\tint FileSize = (int)io_length(File);\n\tchar *pFileData = (char *)mem_alloc(FileSize+1, 1);\n\tio_read(File, pFileData, FileSize);\n\tpFileData[FileSize] = 0;\n\tio_close(File);\n\n\t// parse json data\n\tjson_settings JsonSettings;\n\tmem_zero(&JsonSettings, sizeof(JsonSettings));\n\tchar aError[256];\n\tjson_value *pJsonData = json_parse_ex(&JsonSettings, pFileData, aError);\n\tif(pJsonData == 0)\n\t{\n\t\tm_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, aBuf, aError);\n\t\tmem_free(pFileData);\n\t\treturn;\n\t}\n\n\t// generate configurations\n\tconst json_value &rTileset = (*pJsonData)[(const char *)IAutoMapper::GetTypeName(IAutoMapper::TYPE_TILESET)];\n\tif(rTileset.type == json_array)\n\t{\n\t\tm_pAutoMapper = new CTilesetMapper(m_pEditor);\n\t\tm_pAutoMapper->Load(rTileset);\n\t}\n\telse\n\t{\n\t\tconst json_value &rDoodads = (*pJsonData)[(const char *)IAutoMapper::GetTypeName(IAutoMapper::TYPE_DOODADS)];\n\t\tif(rDoodads.type == json_array)\n\t\t{\n\t\t\tm_pAutoMapper = new CDoodadsMapper(m_pEditor);\n\t\t\tm_pAutoMapper->Load(rDoodads);\n\t\t}\n\t}\n\n\t// clean up\n\tjson_value_free(pJsonData);\n\tmem_free(pFileData);\n\tif(m_pAutoMapper && g_Config.m_Debug)\n\t{\n\t\tstr_format(aBuf, sizeof(aBuf),\"loaded %s.json (%s)\", m_aName, IAutoMapper::GetTypeName(m_pAutoMapper->GetType()));\n\t\tm_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"editor\", aBuf);\n\t}\n}\n\nvoid CEditor::EnvelopeEval(float TimeOffset, int Env, float *pChannels, void *pUser)\n{\n\tCEditor *pThis = (CEditor *)pUser;\n\tif(Env < 0 || Env >= pThis->m_Map.m_lEnvelopes.size())\n\t{\n\t\tpChannels[0] = 0;\n\t\tpChannels[1] = 0;\n\t\tpChannels[2] = 0;\n\t\tpChannels[3] = 0;\n\t\treturn;\n\t}\n\n\tCEnvelope *e = pThis->m_Map.m_lEnvelopes[Env];\n\tfloat t = pThis->m_AnimateTime+TimeOffset;\n\tt *= pThis->m_AnimateSpeed;\n\te->Eval(t, pChannels);\n}\n\n/********************************************************\n OTHER\n*********************************************************/\n\n// copied from gc_menu.cpp, should be more generalized\n//extern int ui_do_edit_box(void *id, const CUIRect *rect, char *str, int str_size, float font_size, bool hidden=false);\nint CEditor::DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned StrSize, float FontSize, float *Offset, bool Hidden, int Corners)\n{\n\tint Inside = UI()->MouseInside(pRect);\n\tbool ReturnValue = false;\n\tbool UpdateOffset = false;\n\tstatic int s_AtIndex = 0;\n\tstatic bool s_DoScroll = false;\n\tstatic float s_ScrollStart = 0.0f;\n\n\tFontSize *= UI()->Scale();\n\n\tif(UI()->LastActiveItem() == pID)\n\t{\n\t\tm_EditBoxActive = 2;\n\t\tint Len = str_length(pStr);\n\t\tif(Len == 0)\n\t\t\ts_AtIndex = 0;\n\n\t\tif(Inside && UI()->MouseButton(0))\n\t\t{\n\t\t\ts_DoScroll = true;\n\t\t\ts_ScrollStart = UI()->MouseX();\n\t\t\tint MxRel = (int)(UI()->MouseX() - pRect->x);\n\n\t\t\tfor(int i = 1; i <= Len; i++)\n\t\t\t{\n\t\t\t\tif(TextRender()->TextWidth(0, FontSize, pStr, i) - *Offset > MxRel)\n\t\t\t\t{\n\t\t\t\t\ts_AtIndex = i - 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif(i == Len)\n\t\t\t\t\ts_AtIndex = Len;\n\t\t\t}\n\t\t}\n\t\telse if(!UI()->MouseButton(0))\n\t\t\ts_DoScroll = false;\n\t\telse if(s_DoScroll)\n\t\t{\n\t\t\t// do scrolling\n\t\t\tif(UI()->MouseX() < pRect->x && s_ScrollStart-UI()->MouseX() > 10.0f)\n\t\t\t{\n\t\t\t\ts_AtIndex = max(0, s_AtIndex-1);\n\t\t\t\ts_ScrollStart = UI()->MouseX();\n\t\t\t\tUpdateOffset = true;\n\t\t\t}\n\t\t\telse if(UI()->MouseX() > pRect->x+pRect->w && UI()->MouseX()-s_ScrollStart > 10.0f)\n\t\t\t{\n\t\t\t\ts_AtIndex = min(Len, s_AtIndex+1);\n\t\t\t\ts_ScrollStart = UI()->MouseX();\n\t\t\t\tUpdateOffset = true;\n\t\t\t}\n\t\t}\n\n\t\tfor(int i = 0; i < Input()->NumEvents(); i++)\n\t\t{\n\t\t\tLen = str_length(pStr);\n\t\t\tReturnValue |= CLineInput::Manipulate(Input()->GetEvent(i), pStr, StrSize, &Len, &s_AtIndex);\n\t\t}\n\t}\n\n\tbool JustGotActive = false;\n\n\tif(UI()->ActiveItem() == pID)\n\t{\n\t\tif(!UI()->MouseButton(0))\n\t\t{\n\t\t\ts_AtIndex = min(s_AtIndex, str_length(pStr));\n\t\t\ts_DoScroll = false;\n\t\t\tUI()->SetActiveItem(0);\n\t\t}\n\t}\n\telse if(UI()->HotItem() == pID)\n\t{\n\t\tif(UI()->MouseButton(0))\n\t\t{\n\t\t\tif (UI()->LastActiveItem() != pID)\n\t\t\t\tJustGotActive = true;\n\t\t\tUI()->SetActiveItem(pID);\n\t\t}\n\t}\n\n\tif(Inside)\n\t\tUI()->SetHotItem(pID);\n\n\tCUIRect Textbox = *pRect;\n\tRenderTools()->DrawUIRect(&Textbox, vec4(1, 1, 1, 0.5f), Corners, 3.0f);\n\tTextbox.VMargin(2.0f, &Textbox);\n\n\tconst char *pDisplayStr = pStr;\n\tchar aStars[128];\n\n\tif(Hidden)\n\t{\n\t\tunsigned s = str_length(pStr);\n\t\tif(s >= sizeof(aStars))\n\t\t\ts = sizeof(aStars)-1;\n\t\tfor(unsigned int i = 0; i < s; ++i)\n\t\t\taStars[i] = '*';\n\t\taStars[s] = 0;\n\t\tpDisplayStr = aStars;\n\t}\n\n\t// check if the text has to be moved\n\tif(UI()->LastActiveItem() == pID && !JustGotActive && (UpdateOffset || Input()->NumEvents()))\n\t{\n\t\tfloat w = TextRender()->TextWidth(0, FontSize, pDisplayStr, s_AtIndex);\n\t\tif(w-*Offset > Textbox.w)\n\t\t{\n\t\t\t// move to the left\n\t\t\tfloat wt = TextRender()->TextWidth(0, FontSize, pDisplayStr, -1);\n\t\t\tdo\n\t\t\t{\n\t\t\t\t*Offset += min(wt-*Offset-Textbox.w, Textbox.w/3);\n\t\t\t}\n\t\t\twhile(w-*Offset > Textbox.w);\n\t\t}\n\t\telse if(w-*Offset < 0.0f)\n\t\t{\n\t\t\t// move to the right\n\t\t\tdo\n\t\t\t{\n\t\t\t\t*Offset = max(0.0f, *Offset-Textbox.w/3);\n\t\t\t}\n\t\t\twhile(w-*Offset < 0.0f);\n\t\t}\n\t}\n\tUI()->ClipEnable(pRect);\n\tTextbox.x -= *Offset;\n\n\tUI()->DoLabel(&Textbox, pDisplayStr, FontSize, -1);\n\n\t// render the cursor\n\tif(UI()->LastActiveItem() == pID && !JustGotActive)\n\t{\n\t\tfloat w = TextRender()->TextWidth(0, FontSize, pDisplayStr, s_AtIndex);\n\t\tTextbox = *pRect;\n\t\tTextbox.VSplitLeft(2.0f, 0, &Textbox);\n\t\tTextbox.x += (w-*Offset-TextRender()->TextWidth(0, FontSize, \"|\", -1)/2);\n\n\t\tif((2*time_get()/time_freq()) % 2)\t// make it blink\n\t\t\tUI()->DoLabel(&Textbox, \"|\", FontSize, -1);\n\t}\n\tUI()->ClipDisable();\n\n\treturn ReturnValue;\n}\n\nvec4 CEditor::ButtonColorMul(const void *pID)\n{\n\tif(UI()->ActiveItem() == pID)\n\t\treturn vec4(1,1,1,0.5f);\n\telse if(UI()->HotItem() == pID)\n\t\treturn vec4(1,1,1,1.5f);\n\treturn vec4(1,1,1,1);\n}\n\nfloat CEditor::UiDoScrollbarV(const void *pID, const CUIRect *pRect, float Current)\n{\n\tCUIRect Handle;\n\tstatic float s_OffsetY;\n\tpRect->HSplitTop(33, &Handle, 0);\n\n\tHandle.y += (pRect->h-Handle.h)*Current;\n\n\t// logic\n\tfloat Ret = Current;\n\tint Inside = UI()->MouseInside(&Handle);\n\n\tif(UI()->ActiveItem() == pID)\n\t{\n\t\tif(!UI()->MouseButton(0))\n\t\t\tUI()->SetActiveItem(0);\n\n\t\tfloat Min = pRect->y;\n\t\tfloat Max = pRect->h-Handle.h;\n\t\tfloat Cur = UI()->MouseY()-s_OffsetY;\n\t\tRet = (Cur-Min)/Max;\n\t\tif(Ret < 0.0f) Ret = 0.0f;\n\t\tif(Ret > 1.0f) Ret = 1.0f;\n\t}\n\telse if(UI()->HotItem() == pID)\n\t{\n\t\tif(UI()->MouseButton(0))\n\t\t{\n\t\t\tUI()->SetActiveItem(pID);\n\t\t\ts_OffsetY = UI()->MouseY()-Handle.y;\n\t\t}\n\t}\n\n\tif(Inside)\n\t\tUI()->SetHotItem(pID);\n\n\t// render\n\tCUIRect Rail;\n\tpRect->VMargin(5.0f, &Rail);\n\tRenderTools()->DrawUIRect(&Rail, vec4(1,1,1,0.25f), 0, 0.0f);\n\n\tCUIRect Slider = Handle;\n\tSlider.w = Rail.x-Slider.x;\n\tRenderTools()->DrawUIRect(&Slider, vec4(1,1,1,0.25f), CUI::CORNER_L, 2.5f);\n\tSlider.x = Rail.x+Rail.w;\n\tRenderTools()->DrawUIRect(&Slider, vec4(1,1,1,0.25f), CUI::CORNER_R, 2.5f);\n\n\tSlider = Handle;\n\tSlider.Margin(5.0f, &Slider);\n\tRenderTools()->DrawUIRect(&Slider, vec4(1,1,1,0.25f)*ButtonColorMul(pID), CUI::CORNER_ALL, 2.5f);\n\n\treturn Ret;\n}\n\nvec4 CEditor::GetButtonColor(const void *pID, int Checked)\n{\n\tif(Checked < 0)\n\t\treturn vec4(0,0,0,0.5f);\n\n\tif(Checked > 0)\n\t{\n\t\tif(UI()->HotItem() == pID)\n\t\t\treturn vec4(1,0,0,0.75f);\n\t\treturn vec4(1,0,0,0.5f);\n\t}\n\n\tif(UI()->HotItem() == pID)\n\t\treturn vec4(1,1,1,0.75f);\n\treturn vec4(1,1,1,0.5f);\n}\n\nint CEditor::DoButton_Editor_Common(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip)\n{\n\tif(UI()->MouseInside(pRect))\n\t{\n\t\tif(Flags&BUTTON_CONTEXT)\n\t\t\tms_pUiGotContext = pID;\n\t\tif(m_pTooltip)\n\t\t\tm_pTooltip = pToolTip;\n\t}\n\n\tif(UI()->HotItem() == pID && pToolTip)\n\t\tm_pTooltip = (const char *)pToolTip;\n\n\treturn UI()->DoButtonLogic(pID, pText, Checked, pRect);\n\n\t// Draw here\n\t//return UI()->DoButton(id, text, checked, r, draw_func, 0);\n}\n\n\nint CEditor::DoButton_Editor(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip)\n{\n\tRenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), CUI::CORNER_ALL, 3.0f);\n\tCUIRect NewRect = *pRect;\n\tNewRect.y += NewRect.h/2.0f-7.0f;\n\tfloat tw = min(TextRender()->TextWidth(0, 10.0f, pText, -1), NewRect.w);\n\tCTextCursor Cursor;\n\tTextRender()->SetCursor(&Cursor, NewRect.x + NewRect.w/2-tw/2, NewRect.y - 1.0f, 10.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\tCursor.m_LineWidth = NewRect.w;\n\tTextRender()->TextEx(&Cursor, pText, -1);\n\treturn DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip);\n}\n\nint CEditor::DoButton_File(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip)\n{\n\tif(Checked)\n\t\tRenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), CUI::CORNER_ALL, 3.0f);\n\n\tCUIRect t = *pRect;\n\tt.VMargin(5.0f, &t);\n\tUI()->DoLabel(&t, pText, 10, -1, -1);\n\treturn DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip);\n}\n\nint CEditor::DoButton_Menu(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip)\n{\n\tCUIRect r = *pRect;\n\tRenderTools()->DrawUIRect(&r, vec4(0.5f, 0.5f, 0.5f, 1.0f), CUI::CORNER_T, 3.0f);\n\n\tr = *pRect;\n\tr.VMargin(5.0f, &r);\n\tUI()->DoLabel(&r, pText, 10, -1, -1);\n\treturn DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip);\n}\n\nint CEditor::DoButton_MenuItem(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip)\n{\n\tif(UI()->HotItem() == pID || Checked)\n\t\tRenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), CUI::CORNER_ALL, 3.0f);\n\n\tCUIRect t = *pRect;\n\tt.VMargin(5.0f, &t);\n\tCTextCursor Cursor;\n\tTextRender()->SetCursor(&Cursor, t.x, t.y - 1.0f, 10.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);\n\tCursor.m_LineWidth = t.w;\n\tTextRender()->TextEx(&Cursor, pText, -1);\n\treturn DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip);\n}\n\nint CEditor::DoButton_Tab(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip)\n{\n\tRenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), CUI::CORNER_T, 5.0f);\n\tCUIRect NewRect = *pRect;\n\tNewRect.y += NewRect.h/2.0f-7.0f;\n\tUI()->DoLabel(&NewRect, pText, 10, 0, -1);\n\treturn DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip);\n}\n\nint CEditor::DoButton_Ex(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip, int Corners, float FontSize)\n{\n\tRenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), Corners, 3.0f);\n\tCUIRect NewRect = *pRect;\n\tNewRect.HMargin(NewRect.h/2.0f-FontSize/2.0f-1.0f, &NewRect);\n\tUI()->DoLabel(&NewRect, pText, FontSize, 0, -1);\n\treturn DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip);\n}\n\nint CEditor::DoButton_ButtonInc(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip)\n{\n\tRenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), CUI::CORNER_R, 3.0f);\n\tUI()->DoLabel(pRect, pText?pText:\"+\", 10, 0, -1);\n\treturn DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip);\n}\n\nint CEditor::DoButton_ButtonDec(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip)\n{\n\tRenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), CUI::CORNER_L, 3.0f);\n\tUI()->DoLabel(pRect, pText?pText:\"-\", 10, 0, -1);\n\treturn DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip);\n}\n\nvoid CEditor::RenderGrid(CLayerGroup *pGroup)\n{\n\tif(!m_GridActive)\n\t\treturn;\n\n\tfloat aGroupPoints[4];\n\tpGroup->Mapping(aGroupPoints);\n\n\tfloat w = UI()->Screen()->w;\n\tfloat h = UI()->Screen()->h;\n\n\tint LineDistance = GetLineDistance();\n\n\tint XOffset = aGroupPoints[0]/LineDistance;\n\tint YOffset = aGroupPoints[1]/LineDistance;\n\tint XGridOffset = XOffset % m_GridFactor;\n\tint YGridOffset = YOffset % m_GridFactor;\n\n\tGraphics()->TextureClear();\n\tGraphics()->LinesBegin();\n\n\tfor(int i = 0; i < (int)w; i++)\n\t{\n\t\tif((i+YGridOffset) % m_GridFactor == 0)\n\t\t\tGraphics()->SetColor(1.0f, 0.3f, 0.3f, 0.3f);\n\t\telse\n\t\t\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 0.15f);\n\n\t\tIGraphics::CLineItem Line = IGraphics::CLineItem(LineDistance*XOffset, LineDistance*i+LineDistance*YOffset, w+aGroupPoints[2], LineDistance*i+LineDistance*YOffset);\n\t\tGraphics()->LinesDraw(&Line, 1);\n\n\t\tif((i+XGridOffset) % m_GridFactor == 0)\n\t\t\tGraphics()->SetColor(1.0f, 0.3f, 0.3f, 0.3f);\n\t\telse\n\t\t\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 0.15f);\n\n\t\tLine = IGraphics::CLineItem(LineDistance*i+LineDistance*XOffset, LineDistance*YOffset, LineDistance*i+LineDistance*XOffset, h+aGroupPoints[3]);\n\t\tGraphics()->LinesDraw(&Line, 1);\n\t}\n\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);\n\tGraphics()->LinesEnd();\n}\n\nvoid CEditor::RenderBackground(CUIRect View, IGraphics::CTextureHandle Texture, float Size, float Brightness)\n{\n\tGraphics()->TextureSet(Texture);\n\tGraphics()->BlendNormal();\n\tGraphics()->QuadsBegin();\n\tGraphics()->SetColor(Brightness, Brightness, Brightness, 1.0f);\n\tGraphics()->QuadsSetSubset(0,0, View.w/Size, View.h/Size);\n\tIGraphics::CQuadItem QuadItem(View.x, View.y, View.w, View.h);\n\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n}\n\nint CEditor::UiDoValueSelector(void *pID, CUIRect *pRect, const char *pLabel, int Current, int Min, int Max, int Step, float Scale, const char *pToolTip)\n{\n\t// logic\n\tstatic float s_Value;\n\tint Inside = UI()->MouseInside(pRect);\n\n\tif(UI()->ActiveItem() == pID)\n\t{\n\t\tif(!UI()->MouseButton(0))\n\t\t{\n\t\t\tm_LockMouse = false;\n\t\t\tUI()->SetActiveItem(0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT))\n\t\t\t\ts_Value += m_MouseDeltaX*0.05f;\n\t\t\telse\n\t\t\t\ts_Value += m_MouseDeltaX;\n\n\t\t\tif(absolute(s_Value) > Scale)\n\t\t\t{\n\t\t\t\tint Count = (int)(s_Value/Scale);\n\t\t\t\ts_Value = fmod(s_Value, Scale);\n\t\t\t\tCurrent += Step*Count;\n\t\t\t\tif(Current < Min)\n\t\t\t\t\tCurrent = Min;\n\t\t\t\tif(Current > Max)\n\t\t\t\t\tCurrent = Max;\n\t\t\t}\n\t\t}\n\t\tif(pToolTip)\n\t\t\tm_pTooltip = pToolTip;\n\t}\n\telse if(UI()->HotItem() == pID)\n\t{\n\t\tif(UI()->MouseButton(0))\n\t\t{\n\t\t\tm_LockMouse = true;\n\t\t\ts_Value = 0;\n\t\t\tUI()->SetActiveItem(pID);\n\t\t}\n\t\tif(pToolTip)\n\t\t\tm_pTooltip = pToolTip;\n\t}\n\n\tif(Inside)\n\t\tUI()->SetHotItem(pID);\n\n\t// render\n\tchar aBuf[128];\n\tstr_format(aBuf, sizeof(aBuf),\"%s %d\", pLabel, Current);\n\tRenderTools()->DrawUIRect(pRect, GetButtonColor(pID, 0), CUI::CORNER_ALL, 5.0f);\n\tpRect->y += pRect->h/2.0f-7.0f;\n\tUI()->DoLabel(pRect, aBuf, 10, 0, -1);\n\n\treturn Current;\n}\n\nCLayerGroup *CEditor::GetSelectedGroup()\n{\n\tif(m_SelectedGroup >= 0 && m_SelectedGroup < m_Map.m_lGroups.size())\n\t\treturn m_Map.m_lGroups[m_SelectedGroup];\n\treturn 0x0;\n}\n\nCLayer *CEditor::GetSelectedLayer(int Index)\n{\n\tCLayerGroup *pGroup = GetSelectedGroup();\n\tif(!pGroup)\n\t\treturn 0x0;\n\n\tif(m_SelectedLayer >= 0 && m_SelectedLayer < m_Map.m_lGroups[m_SelectedGroup]->m_lLayers.size())\n\t\treturn pGroup->m_lLayers[m_SelectedLayer];\n\treturn 0x0;\n}\n\nCLayer *CEditor::GetSelectedLayerType(int Index, int Type)\n{\n\tCLayer *p = GetSelectedLayer(Index);\n\tif(p && p->m_Type == Type)\n\t\treturn p;\n\treturn 0x0;\n}\n\nCQuad *CEditor::GetSelectedQuad()\n{\n\tCLayerQuads *ql = (CLayerQuads *)GetSelectedLayerType(0, LAYERTYPE_QUADS);\n\tif(!ql)\n\t\treturn 0;\n\tif(m_SelectedQuad >= 0 && m_SelectedQuad < ql->m_lQuads.size())\n\t\treturn &ql->m_lQuads[m_SelectedQuad];\n\treturn 0;\n}\n\nvoid CEditor::CallbackOpenMap(const char *pFileName, int StorageType, void *pUser)\n{\n\tCEditor *pEditor = (CEditor*)pUser;\n\tif(pEditor->Load(pFileName, StorageType))\n\t{\n\t\tstr_copy(pEditor->m_aFileName, pFileName, 512);\n\t\tpEditor->m_ValidSaveFilename = StorageType == IStorage::TYPE_SAVE && pEditor->m_pFileDialogPath == pEditor->m_aFileDialogCurrentFolder;\n\t\tpEditor->SortImages();\n\t\tpEditor->m_Dialog = DIALOG_NONE;\n\t\tpEditor->m_Map.m_Modified = false;\n\t}\n\telse\n\t{\n\t\tpEditor->Reset();\n\t\tpEditor->m_aFileName[0] = 0;\n\t}\n}\nvoid CEditor::CallbackAppendMap(const char *pFileName, int StorageType, void *pUser)\n{\n\tCEditor *pEditor = (CEditor*)pUser;\n\tif(pEditor->Append(pFileName, StorageType))\n\t\tpEditor->m_aFileName[0] = 0;\n\telse\n\t\tpEditor->SortImages();\n\n\tpEditor->m_Dialog = DIALOG_NONE;\n}\nvoid CEditor::CallbackSaveMap(const char *pFileName, int StorageType, void *pUser)\n{\n\tCEditor *pEditor = static_cast<CEditor*>(pUser);\n\tchar aBuf[1024];\n\tconst int Length = str_length(pFileName);\n\t// add map extension\n\tif(Length <= 4 || pFileName[Length-4] != '.' || str_comp_nocase(pFileName+Length-3, \"map\"))\n\t{\n\t\tstr_format(aBuf, sizeof(aBuf), \"%s.map\", pFileName);\n\t\tpFileName = aBuf;\n\t}\n\n\tif(pEditor->Save(pFileName))\n\t{\n\t\tstr_copy(pEditor->m_aFileName, pFileName, sizeof(pEditor->m_aFileName));\n\t\tpEditor->m_ValidSaveFilename = StorageType == IStorage::TYPE_SAVE && pEditor->m_pFileDialogPath == pEditor->m_aFileDialogCurrentFolder;\n\t\tpEditor->m_Map.m_Modified = false;\n\t}\n\n\tpEditor->m_Dialog = DIALOG_NONE;\n}\n\nvoid CEditor::DoToolbar(CUIRect ToolBar)\n{\n\tCUIRect TB_Top, TB_Bottom;\n\tCUIRect Button;\n\n\tToolBar.HSplitTop(ToolBar.h/2.0f, &TB_Top, &TB_Bottom);\n\n\tTB_Top.HSplitBottom(2.5f, &TB_Top, 0);\n\tTB_Bottom.HSplitTop(2.5f, 0, &TB_Bottom);\n\n\t// ctrl+o to open\n\tif(Input()->KeyDown('o') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)) && m_Dialog == DIALOG_NONE)\n\t{\n\t\tif(HasUnsavedData())\n\t\t{\n\t\t\tif(!m_PopupEventWasActivated)\n\t\t\t{\n\t\t\t\tm_PopupEventType = POPEVENT_LOAD;\n\t\t\t\tm_PopupEventActivated = true;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tInvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_MAP, \"Load map\", \"Load\", \"maps\", \"\", CallbackOpenMap, this);\n\t}\n\n\t// ctrl+s to save\n\tif(Input()->KeyDown('s') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)) && m_Dialog == DIALOG_NONE)\n\t{\n\t\tif(m_aFileName[0] && m_ValidSaveFilename)\n\t\t{\n\t\t\tif(!m_PopupEventWasActivated)\n\t\t\t{\n\t\t\t\tstr_copy(m_aFileSaveName, m_aFileName, sizeof(m_aFileSaveName));\n\t\t\t\tm_PopupEventType = POPEVENT_SAVE;\n\t\t\t\tm_PopupEventActivated = true;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tInvokeFileDialog(IStorage::TYPE_SAVE, FILETYPE_MAP, \"Save map\", \"Save\", \"maps\", \"\", CallbackSaveMap, this);\n\t}\n\n\t// detail button\n\tTB_Top.VSplitLeft(30.0f, &Button, &TB_Top);\n\tstatic int s_HqButton = 0;\n\tif(DoButton_Editor(&s_HqButton, \"HD\", m_ShowDetail, &Button, 0, \"[ctrl+h] Toggle High Detail\") ||\n\t\t(Input()->KeyDown('h') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL))))\n\t{\n\t\tm_ShowDetail = !m_ShowDetail;\n\t}\n\n\tTB_Top.VSplitLeft(5.0f, 0, &TB_Top);\n\n\t// animation button\n\tTB_Top.VSplitLeft(40.0f, &Button, &TB_Top);\n\tstatic int s_AnimateButton = 0;\n\tif(DoButton_Editor(&s_AnimateButton, \"Anim\", m_Animate, &Button, 0, \"[ctrl+m] Toggle animation\") ||\n\t\t(Input()->KeyDown('m') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL))))\n\t{\n\t\tm_AnimateStart = time_get();\n\t\tm_Animate = !m_Animate;\n\t}\n\n\tTB_Top.VSplitLeft(5.0f, 0, &TB_Top);\n\n\t// proof button\n\tTB_Top.VSplitLeft(40.0f, &Button, &TB_Top);\n\tstatic int s_ProofButton = 0;\n\tif(DoButton_Editor(&s_ProofButton, \"Proof\", m_ProofBorders, &Button, 0, \"[ctrl+p] Toggles proof borders. These borders represent what a player maximum can see.\") ||\n\t\t(Input()->KeyDown('p') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL))))\n\t{\n\t\tm_ProofBorders = !m_ProofBorders;\n\t}\n\n\tTB_Top.VSplitLeft(5.0f, 0, &TB_Top);\n\n\t// tile info button\n\tTB_Top.VSplitLeft(40.0f, &Button, &TB_Top);\n\tstatic int s_TileInfoButton = 0;\n\tif(DoButton_Editor(&s_TileInfoButton, \"Info\", m_ShowTileInfo, &Button, 0, \"[ctrl+i] Show tile informations\") ||\n\t\t(Input()->KeyDown('i') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL))))\n\t{\n\t\tm_ShowTileInfo = !m_ShowTileInfo;\n\t\tm_ShowEnvelopePreview = 0;\n\t}\n\n\tTB_Top.VSplitLeft(15.0f, 0, &TB_Top);\n\n\t// zoom group\n\tTB_Top.VSplitLeft(30.0f, &Button, &TB_Top);\n\tstatic int s_ZoomOutButton = 0;\n\tif(DoButton_Ex(&s_ZoomOutButton, \"ZO\", 0, &Button, 0, \"[NumPad-] Zoom out\", CUI::CORNER_L))\n\t\tm_ZoomLevel += 50;\n\n\tTB_Top.VSplitLeft(30.0f, &Button, &TB_Top);\n\tstatic int s_ZoomNormalButton = 0;\n\tif(DoButton_Ex(&s_ZoomNormalButton, \"1:1\", 0, &Button, 0, \"[NumPad*] Zoom to normal and remove editor offset\", 0))\n\t{\n\t\tm_EditorOffsetX = 0;\n\t\tm_EditorOffsetY = 0;\n\t\tm_ZoomLevel = 100;\n\t}\n\n\tTB_Top.VSplitLeft(30.0f, &Button, &TB_Top);\n\tstatic int s_ZoomInButton = 0;\n\tif(DoButton_Ex(&s_ZoomInButton, \"ZI\", 0, &Button, 0, \"[NumPad+] Zoom in\", CUI::CORNER_R))\n\t\tm_ZoomLevel -= 50;\n\n\tTB_Top.VSplitLeft(10.0f, 0, &TB_Top);\n\n\t// animation speed\n\tTB_Top.VSplitLeft(30.0f, &Button, &TB_Top);\n\tstatic int s_AnimFasterButton = 0;\n\tif(DoButton_Ex(&s_AnimFasterButton, \"A+\", 0, &Button, 0, \"Increase animation speed\", CUI::CORNER_L))\n\t\tm_AnimateSpeed += 0.5f;\n\n\tTB_Top.VSplitLeft(30.0f, &Button, &TB_Top);\n\tstatic int s_AnimNormalButton = 0;\n\tif(DoButton_Ex(&s_AnimNormalButton, \"1\", 0, &Button, 0, \"Normal animation speed\", 0))\n\t\tm_AnimateSpeed = 1.0f;\n\n\tTB_Top.VSplitLeft(30.0f, &Button, &TB_Top);\n\tstatic int s_AnimSlowerButton = 0;\n\tif(DoButton_Ex(&s_AnimSlowerButton, \"A-\", 0, &Button, 0, \"Decrease animation speed\", CUI::CORNER_R))\n\t{\n\t\tif(m_AnimateSpeed > 0.5f)\n\t\t\tm_AnimateSpeed -= 0.5f;\n\t}\n\n\tTB_Top.VSplitLeft(10.0f, &Button, &TB_Top);\n\n\n\t// brush manipulation\n\t{\n\t\tint Enabled = m_Brush.IsEmpty()?-1:0;\n\n\t\t// flip buttons\n\t\tTB_Top.VSplitLeft(30.0f, &Button, &TB_Top);\n\t\tstatic int s_FlipXButton = 0;\n\t\tif(DoButton_Ex(&s_FlipXButton, \"X/X\", Enabled, &Button, 0, \"[N] Flip brush horizontal\", CUI::CORNER_L) || Input()->KeyDown('n'))\n\t\t{\n\t\t\tfor(int i = 0; i < m_Brush.m_lLayers.size(); i++)\n\t\t\t\tm_Brush.m_lLayers[i]->BrushFlipX();\n\t\t}\n\n\t\tTB_Top.VSplitLeft(30.0f, &Button, &TB_Top);\n\t\tstatic int s_FlipyButton = 0;\n\t\tif(DoButton_Ex(&s_FlipyButton, \"Y/Y\", Enabled, &Button, 0, \"[M] Flip brush vertical\", CUI::CORNER_R) || Input()->KeyDown('m'))\n\t\t{\n\t\t\tfor(int i = 0; i < m_Brush.m_lLayers.size(); i++)\n\t\t\t\tm_Brush.m_lLayers[i]->BrushFlipY();\n\t\t}\n\n\t\t// rotate buttons\n\t\tTB_Top.VSplitLeft(15.0f, &Button, &TB_Top);\n\n\t\tTB_Top.VSplitLeft(30.0f, &Button, &TB_Top);\n\t\tstatic int s_RotationAmount = 90;\n\t\tbool TileLayer = false;\n\t\t// check for tile layers in brush selection\n\t\tfor(int i = 0; i < m_Brush.m_lLayers.size(); i++)\n\t\t\tif(m_Brush.m_lLayers[i]->m_Type == LAYERTYPE_TILES)\n\t\t\t{\n\t\t\t\tTileLayer = true;\n\t\t\t\ts_RotationAmount = max(90, (s_RotationAmount/90)*90);\n\t\t\t\tbreak;\n\t\t\t}\n\t\ts_RotationAmount = UiDoValueSelector(&s_RotationAmount, &Button, \"\", s_RotationAmount, TileLayer?90:1, 359, TileLayer?90:1, TileLayer?10.0f:2.0f, \"Rotation of the brush in degrees. Use left mouse button to drag and change the value. Hold shift to be more precise.\");\n\n\t\tTB_Top.VSplitLeft(5.0f, &Button, &TB_Top);\n\t\tTB_Top.VSplitLeft(30.0f, &Button, &TB_Top);\n\t\tstatic int s_CcwButton = 0;\n\t\tif(DoButton_Ex(&s_CcwButton, \"CCW\", Enabled, &Button, 0, \"[R] Rotates the brush counter clockwise\", CUI::CORNER_L) || Input()->KeyDown('r'))\n\t\t{\n\t\t\tfor(int i = 0; i < m_Brush.m_lLayers.size(); i++)\n\t\t\t\tm_Brush.m_lLayers[i]->BrushRotate(-s_RotationAmount/360.0f*pi*2);\n\t\t}\n\n\t\tTB_Top.VSplitLeft(30.0f, &Button, &TB_Top);\n\t\tstatic int s_CwButton = 0;\n\t\tif(DoButton_Ex(&s_CwButton, \"CW\", Enabled, &Button, 0, \"[T] Rotates the brush clockwise\", CUI::CORNER_R) || Input()->KeyDown('t'))\n\t\t{\n\t\t\tfor(int i = 0; i < m_Brush.m_lLayers.size(); i++)\n\t\t\t\tm_Brush.m_lLayers[i]->BrushRotate(s_RotationAmount/360.0f*pi*2);\n\t\t}\n\t}\n\n\t// quad manipulation\n\t{\n\t\t// do add button\n\t\tTB_Top.VSplitLeft(10.0f, &Button, &TB_Top);\n\t\tTB_Top.VSplitLeft(60.0f, &Button, &TB_Top);\n\t\tstatic int s_NewButton = 0;\n\n\t\tCLayerQuads *pQLayer = (CLayerQuads *)GetSelectedLayerType(0, LAYERTYPE_QUADS);\n\t\t//CLayerTiles *tlayer = (CLayerTiles *)get_selected_layer_type(0, LAYERTYPE_TILES);\n\t\tif(DoButton_Editor(&s_NewButton, \"Add Quad\", pQLayer?0:-1, &Button, 0, \"Adds a new quad\"))\n\t\t{\n\t\t\tif(pQLayer)\n\t\t\t{\n\t\t\t\tfloat Mapping[4];\n\t\t\t\tCLayerGroup *g = GetSelectedGroup();\n\t\t\t\tg->Mapping(Mapping);\n\t\t\t\tint AddX = f2fx(Mapping[0] + (Mapping[2]-Mapping[0])/2);\n\t\t\t\tint AddY = f2fx(Mapping[1] + (Mapping[3]-Mapping[1])/2);\n\n\t\t\t\tCQuad *q = pQLayer->NewQuad();\n\t\t\t\tfor(int i = 0; i < 5; i++)\n\t\t\t\t{\n\t\t\t\t\tq->m_aPoints[i].x += AddX;\n\t\t\t\t\tq->m_aPoints[i].y += AddY;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// tile manipulation\n\t{\n\t\tTB_Bottom.VSplitLeft(40.0f, &Button, &TB_Bottom);\n\t\tstatic int s_BorderBut = 0;\n\t\tCLayerTiles *pT = (CLayerTiles *)GetSelectedLayerType(0, LAYERTYPE_TILES);\n\n\t\tif(DoButton_Editor(&s_BorderBut, \"Border\", pT?0:-1, &Button, 0, \"Adds border tiles\"))\n\t\t{\n\t\t\tif(pT)\n\t\t\t\tDoMapBorder();\n\t\t}\n\t}\n\n\tTB_Bottom.VSplitLeft(5.0f, 0, &TB_Bottom);\n\n\t// refocus button\n\tTB_Bottom.VSplitLeft(50.0f, &Button, &TB_Bottom);\n\tstatic int s_RefocusButton = 0;\n\tif(DoButton_Editor(&s_RefocusButton, \"Refocus\", m_WorldOffsetX&&m_WorldOffsetY?0:-1, &Button, 0, \"[HOME] Restore map focus\") || (m_EditBoxActive == 0 && Input()->KeyDown(KEY_HOME)))\n\t{\n\t\tm_WorldOffsetX = 0;\n\t\tm_WorldOffsetY = 0;\n\t}\n\n\tTB_Bottom.VSplitLeft(5.0f, 0, &TB_Bottom);\n\n\t// grid button\n\tTB_Bottom.VSplitLeft(50.0f, &Button, &TB_Bottom);\n\tstatic int s_GridButton = 0;\n\tif(DoButton_Editor(&s_GridButton, \"Grid\", m_GridActive, &Button, 0, \"Toggle Grid\"))\n\t{\n\t\tm_GridActive = !m_GridActive;\n\t}\n\n\tTB_Bottom.VSplitLeft(30.0f, 0, &TB_Bottom);\n\n\t// grid zoom\n\tTB_Bottom.VSplitLeft(30.0f, &Button, &TB_Bottom);\n\tstatic int s_GridIncreaseButton = 0;\n\tif(DoButton_Ex(&s_GridIncreaseButton, \"G-\", 0, &Button, 0, \"Decrease grid\", CUI::CORNER_L))\n\t{\n\t\tif(m_GridFactor > 1)\n\t\t\tm_GridFactor--;\n\t}\n\n\tTB_Bottom.VSplitLeft(30.0f, &Button, &TB_Bottom);\n\tstatic int s_GridNormalButton = 0;\n\tif(DoButton_Ex(&s_GridNormalButton, \"1\", 0, &Button, 0, \"Normal grid\", 0))\n\t\tm_GridFactor = 1;\n\n\tTB_Bottom.VSplitLeft(30.0f, &Button, &TB_Bottom);\n\n\tstatic int s_GridDecreaseButton = 0;\n\tif(DoButton_Ex(&s_GridDecreaseButton, \"G+\", 0, &Button, 0, \"Increase grid\", CUI::CORNER_R))\n\t{\n\t\tif(m_GridFactor < 15)\n\t\t\tm_GridFactor++;\n\t}\n}\n\nstatic void Rotate(const CPoint *pCenter, CPoint *pPoint, float Rotation)\n{\n\tint x = pPoint->x - pCenter->x;\n\tint y = pPoint->y - pCenter->y;\n\tpPoint->x = (int)(x * cosf(Rotation) - y * sinf(Rotation) + pCenter->x);\n\tpPoint->y = (int)(x * sinf(Rotation) + y * cosf(Rotation) + pCenter->y);\n}\n\nvoid CEditor::DoQuad(CQuad *q, int Index)\n{\n\tenum\n\t{\n\t\tOP_NONE=0,\n\t\tOP_MOVE_ALL,\n\t\tOP_MOVE_PIVOT,\n\t\tOP_ROTATE,\n\t\tOP_CONTEXT_MENU,\n\t};\n\n\t// some basic values\n\tvoid *pID = &q->m_aPoints[4]; // use pivot addr as id\n\tstatic CPoint s_RotatePoints[4];\n\tstatic float s_LastWx;\n\tstatic float s_LastWy;\n\tstatic int s_Operation = OP_NONE;\n\tstatic float s_RotateAngle = 0;\n\tfloat wx = UI()->MouseWorldX();\n\tfloat wy = UI()->MouseWorldY();\n\n\t// get pivot\n\tfloat CenterX = fx2f(q->m_aPoints[4].x);\n\tfloat CenterY = fx2f(q->m_aPoints[4].y);\n\n\tfloat dx = (CenterX - wx)/m_WorldZoom;\n\tfloat dy = (CenterY - wy)/m_WorldZoom;\n\tif(dx*dx+dy*dy < 50)\n\t\tUI()->SetHotItem(pID);\n\n\tbool IgnoreGrid;\n\tif(Input()->KeyPressed(KEY_LALT) || Input()->KeyPressed(KEY_RALT))\n\t\tIgnoreGrid = true;\n\telse\n\t\tIgnoreGrid = false;\n\n\t// draw selection background\n\tif(m_SelectedQuad == Index)\n\t{\n\t\tGraphics()->SetColor(0,0,0,1);\n\t\tIGraphics::CQuadItem QuadItem(CenterX, CenterY, 7.0f, 7.0f);\n\t\tGraphics()->QuadsDraw(&QuadItem, 1);\n\t}\n\n\tif(UI()->ActiveItem() == pID)\n\t{\n\t\tif(m_MouseDeltaWx*m_MouseDeltaWx+m_MouseDeltaWy*m_MouseDeltaWy > 0.5f)\n\t\t{\n\t\t\t// check if we only should move pivot\n\t\t\tif(s_Operation == OP_MOVE_PIVOT)\n\t\t\t{\n\t\t\t\tif(m_GridActive && !IgnoreGrid)\n\t\t\t\t{\n\t\t\t\t\tint LineDistance = GetLineDistance();\n\n\t\t\t\t\tfloat x = 0.0f;\n\t\t\t\t\tfloat y = 0.0f;\n\t\t\t\t\tif(wx >= 0)\n\t\t\t\t\t\tx = (int)((wx+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);\n\t\t\t\t\telse\n\t\t\t\t\t\tx = (int)((wx-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);\n\t\t\t\t\tif(wy >= 0)\n\t\t\t\t\t\ty = (int)((wy+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);\n\t\t\t\t\telse\n\t\t\t\t\t\ty = (int)((wy-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);\n\n\t\t\t\t\tq->m_aPoints[4].x = f2fx(x);\n\t\t\t\t\tq->m_aPoints[4].y = f2fx(y);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tq->m_aPoints[4].x += f2fx(wx-s_LastWx);\n\t\t\t\t\tq->m_aPoints[4].y += f2fx(wy-s_LastWy);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(s_Operation == OP_MOVE_ALL)\n\t\t\t{\n\t\t\t\t// move all points including pivot\n\t\t\t\tif(m_GridActive && !IgnoreGrid)\n\t\t\t\t{\n\t\t\t\t\tint LineDistance = GetLineDistance();\n\n\t\t\t\t\tfloat x = 0.0f;\n\t\t\t\t\tfloat y = 0.0f;\n\t\t\t\t\tif(wx >= 0)\n\t\t\t\t\t\tx = (int)((wx+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);\n\t\t\t\t\telse\n\t\t\t\t\t\tx = (int)((wx-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);\n\t\t\t\t\tif(wy >= 0)\n\t\t\t\t\t\ty = (int)((wy+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);\n\t\t\t\t\telse\n\t\t\t\t\t\ty = (int)((wy-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);\n\n\t\t\t\t\tint OldX = q->m_aPoints[4].x;\n\t\t\t\t\tint OldY = q->m_aPoints[4].y;\n\t\t\t\t\tq->m_aPoints[4].x = f2fx(x);\n\t\t\t\t\tq->m_aPoints[4].y = f2fx(y);\n\t\t\t\t\tint DiffX = q->m_aPoints[4].x - OldX;\n\t\t\t\t\tint DiffY = q->m_aPoints[4].y - OldY;\n\n\t\t\t\t\tfor(int v = 0; v < 4; v++)\n\t\t\t\t\t{\n\t\t\t\t\t\tq->m_aPoints[v].x += DiffX;\n\t\t\t\t\t\tq->m_aPoints[v].y += DiffY;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tfor(int v = 0; v < 5; v++)\n\t\t\t\t\t{\n\t\t\t\t\t\t\tq->m_aPoints[v].x += f2fx(wx-s_LastWx);\n\t\t\t\t\t\t\tq->m_aPoints[v].y += f2fx(wy-s_LastWy);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(s_Operation == OP_ROTATE)\n\t\t\t{\n\t\t\t\tfor(int v = 0; v < 4; v++)\n\t\t\t\t{\n\t\t\t\t\tq->m_aPoints[v] = s_RotatePoints[v];\n\t\t\t\t\tRotate(&q->m_aPoints[4], &q->m_aPoints[v], s_RotateAngle);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ts_RotateAngle += (m_MouseDeltaX) * 0.002f;\n\t\ts_LastWx = wx;\n\t\ts_LastWy = wy;\n\n\t\tif(s_Operation == OP_CONTEXT_MENU)\n\t\t{\n\t\t\tif(!UI()->MouseButton(1))\n\t\t\t{\n\t\t\t\tstatic int s_QuadPopupID = 0;\n\t\t\t\tUiInvokePopupMenu(&s_QuadPopupID, 0, UI()->MouseX(), UI()->MouseY(), 120, 180, PopupQuad);\n\t\t\t\tm_LockMouse = false;\n\t\t\t\ts_Operation = OP_NONE;\n\t\t\t\tUI()->SetActiveItem(0);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(!UI()->MouseButton(0))\n\t\t\t{\n\t\t\t\tm_LockMouse = false;\n\t\t\t\ts_Operation = OP_NONE;\n\t\t\t\tUI()->SetActiveItem(0);\n\t\t\t}\n\t\t}\n\n\t\tGraphics()->SetColor(1,1,1,1);\n\t}\n\telse if(UI()->HotItem() == pID)\n\t{\n\t\tms_pUiGotContext = pID;\n\n\t\tGraphics()->SetColor(1,1,1,1);\n\t\tm_pTooltip = \"Left mouse button to move. Hold shift to move pivot. Hold ctrl to rotate. Hold alt to ignore grid.\";\n\n\t\tif(UI()->MouseButton(0))\n\t\t{\n\t\t\tif(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT))\n\t\t\t\ts_Operation = OP_MOVE_PIVOT;\n\t\t\telse if(Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL))\n\t\t\t{\n\t\t\t\tm_LockMouse = true;\n\t\t\t\ts_Operation = OP_ROTATE;\n\t\t\t\ts_RotateAngle = 0;\n\t\t\t\ts_RotatePoints[0] = q->m_aPoints[0];\n\t\t\t\ts_RotatePoints[1] = q->m_aPoints[1];\n\t\t\t\ts_RotatePoints[2] = q->m_aPoints[2];\n\t\t\t\ts_RotatePoints[3] = q->m_aPoints[3];\n\t\t\t}\n\t\t\telse\n\t\t\t\ts_Operation = OP_MOVE_ALL;\n\n\t\t\tUI()->SetActiveItem(pID);\n\t\t\tif(m_SelectedQuad != Index)\n\t\t\t\tm_SelectedPoints = 0;\n\t\t\tm_SelectedQuad = Index;\n\t\t\ts_LastWx = wx;\n\t\t\ts_LastWy = wy;\n\t\t}\n\n\t\tif(UI()->MouseButton(1))\n\t\t{\n\t\t\tif(m_SelectedQuad != Index)\n\t\t\t\tm_SelectedPoints = 0;\n\t\t\tm_SelectedQuad = Index;\n\t\t\ts_Operation = OP_CONTEXT_MENU;\n\t\t\tUI()->SetActiveItem(pID);\n\t\t}\n\t}\n\telse\n\t\tGraphics()->SetColor(0,1,0,1);\n\n\tIGraphics::CQuadItem QuadItem(CenterX, CenterY, 5.0f*m_WorldZoom, 5.0f*m_WorldZoom);\n\tGraphics()->QuadsDraw(&QuadItem, 1);\n}\n\nvoid CEditor::DoQuadPoint(CQuad *pQuad, int QuadIndex, int V)\n{\n\tvoid *pID = &pQuad->m_aPoints[V];\n\n\tfloat wx = UI()->MouseWorldX();\n\tfloat wy = UI()->MouseWorldY();\n\n\tfloat px = fx2f(pQuad->m_aPoints[V].x);\n\tfloat py = fx2f(pQuad->m_aPoints[V].y);\n\n\tfloat dx = (px - wx)/m_WorldZoom;\n\tfloat dy = (py - wy)/m_WorldZoom;\n\tif(dx*dx+dy*dy < 50)\n\t\tUI()->SetHotItem(pID);\n\n\t// draw selection background\n\tif(m_SelectedQuad == QuadIndex && m_SelectedPoints&(1<<V))\n\t{\n\t\tGraphics()->SetColor(0,0,0,1);\n\t\tIGraphics::CQuadItem QuadItem(px, py, 7.0f, 7.0f);\n\t\tGraphics()->QuadsDraw(&QuadItem, 1);\n\t}\n\n\tenum\n\t{\n\t\tOP_NONE=0,\n\t\tOP_MOVEPOINT,\n\t\tOP_MOVEUV,\n\t\tOP_CONTEXT_MENU\n\t};\n\n\tstatic bool s_Moved;\n\tstatic int s_Operation = OP_NONE;\n\n\tbool IgnoreGrid;\n\tif(Input()->KeyPressed(KEY_LALT) || Input()->KeyPressed(KEY_RALT))\n\t\tIgnoreGrid = true;\n\telse\n\t\tIgnoreGrid = false;\n\n\tif(UI()->ActiveItem() == pID)\n\t{\n\t\tfloat dx = m_MouseDeltaWx;\n\t\tfloat dy = m_MouseDeltaWy;\n\t\tif(!s_Moved)\n\t\t{\n\t\t\tif(dx*dx+dy*dy > 0.5f)\n\t\t\t\ts_Moved = true;\n\t\t}\n\n\t\tif(s_Moved)\n\t\t{\n\t\t\tif(s_Operation == OP_MOVEPOINT)\n\t\t\t{\n\t\t\t\tif(m_GridActive && !IgnoreGrid)\n\t\t\t\t{\n\t\t\t\t\tfor(int m = 0; m < 4; m++)\n\t\t\t\t\t\tif(m_SelectedPoints&(1<<m))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint LineDistance = GetLineDistance();\n\n\t\t\t\t\t\t\tfloat x = 0.0f;\n\t\t\t\t\t\t\tfloat y = 0.0f;\n\t\t\t\t\t\t\tif(wx >= 0)\n\t\t\t\t\t\t\t\tx = (int)((wx+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tx = (int)((wx-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);\n\t\t\t\t\t\t\tif(wy >= 0)\n\t\t\t\t\t\t\t\ty = (int)((wy+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\ty = (int)((wy-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);\n\n\t\t\t\t\t\t\tpQuad->m_aPoints[m].x = f2fx(x);\n\t\t\t\t\t\t\tpQuad->m_aPoints[m].y = f2fx(y);\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tfor(int m = 0; m < 4; m++)\n\t\t\t\t\t\tif(m_SelectedPoints&(1<<m))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpQuad->m_aPoints[m].x += f2fx(dx);\n\t\t\t\t\t\t\tpQuad->m_aPoints[m].y += f2fx(dy);\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(s_Operation == OP_MOVEUV)\n\t\t\t{\n\t\t\t\tfor(int m = 0; m < 4; m++)\n\t\t\t\t\tif(m_SelectedPoints&(1<<m))\n\t\t\t\t\t{\n\t\t\t\t\t\t// 0,2;1,3 - line x\n\t\t\t\t\t\t// 0,1;2,3 - line y\n\n\t\t\t\t\t\tpQuad->m_aTexcoords[m].x += f2fx(dx*0.001f);\n\t\t\t\t\t\tpQuad->m_aTexcoords[(m+2)%4].x += f2fx(dx*0.001f);\n\n\t\t\t\t\t\tpQuad->m_aTexcoords[m].y += f2fx(dy*0.001f);\n\t\t\t\t\t\tpQuad->m_aTexcoords[m^1].y += f2fx(dy*0.001f);\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif(s_Operation == OP_CONTEXT_MENU)\n\t\t{\n\t\t\tif(!UI()->MouseButton(1))\n\t\t\t{\n\t\t\t\tstatic int s_PointPopupID = 0;\n\t\t\t\tUiInvokePopupMenu(&s_PointPopupID, 0, UI()->MouseX(), UI()->MouseY(), 120, 150, PopupPoint);\n\t\t\t\tUI()->SetActiveItem(0);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(!UI()->MouseButton(0))\n\t\t\t{\n\t\t\t\tif(!s_Moved)\n\t\t\t\t{\n\t\t\t\t\tif(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT))\n\t\t\t\t\t\tm_SelectedPoints ^= 1<<V;\n\t\t\t\t\telse\n\t\t\t\t\t\tm_SelectedPoints = 1<<V;\n\t\t\t\t}\n\t\t\t\tm_LockMouse = false;\n\t\t\t\tUI()->SetActiveItem(0);\n\t\t\t}\n\t\t}\n\n\t\tGraphics()->SetColor(1,1,1,1);\n\t}\n\telse if(UI()->HotItem() == pID)\n\t{\n\t\tms_pUiGotContext = pID;\n\n\t\tGraphics()->SetColor(1,1,1,1);\n\t\tm_pTooltip = \"Left mouse button to move. Hold shift to move the texture. Hold alt to ignore grid.\";\n\n\t\tif(UI()->MouseButton(0))\n\t\t{\n\t\t\tUI()->SetActiveItem(pID);\n\t\t\ts_Moved = false;\n\t\t\tif(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT))\n\t\t\t{\n\t\t\t\ts_Operation = OP_MOVEUV;\n\t\t\t\tm_LockMouse = true;\n\t\t\t}\n\t\t\telse\n\t\t\t\ts_Operation = OP_MOVEPOINT;\n\n\t\t\tif(!(m_SelectedPoints&(1<<V)))\n\t\t\t{\n\t\t\t\tif(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT))\n\t\t\t\t\tm_SelectedPoints |= 1<<V;\n\t\t\t\telse\n\t\t\t\t\tm_SelectedPoints = 1<<V;\n\t\t\t\ts_Moved = true;\n\t\t\t}\n\n\t\t\tm_SelectedQuad = QuadIndex;\n\t\t}\n\t\telse if(UI()->MouseButton(1))\n\t\t{\n\t\t\ts_Operation = OP_CONTEXT_MENU;\n\t\t\tm_SelectedQuad = QuadIndex;\n\t\t\tUI()->SetActiveItem(pID);\n\t\t\tif(!(m_SelectedPoints&(1<<V)))\n\t\t\t{\n\t\t\t\tif(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT))\n\t\t\t\t\tm_SelectedPoints |= 1<<V;\n\t\t\t\telse\n\t\t\t\t\tm_SelectedPoints = 1<<V;\n\t\t\t\ts_Moved = true;\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t\tGraphics()->SetColor(1,0,0,1);\n\n\tIGraphics::CQuadItem QuadItem(px, py, 5.0f*m_WorldZoom, 5.0f*m_WorldZoom);\n\tGraphics()->QuadsDraw(&QuadItem, 1);\n}\n\nvoid CEditor::DoQuadEnvelopes(const array<CQuad> &lQuads, IGraphics::CTextureHandle Texture)\n{\n\tint Num = lQuads.size();\n\tCEnvelope **apEnvelope = new CEnvelope*[Num];\n\tmem_zero(apEnvelope, sizeof(CEnvelope*)*Num);\n\tfor(int i = 0; i < Num; i++)\n\t{\n\t\tif((m_ShowEnvelopePreview == 1 && lQuads[i].m_PosEnv == m_SelectedEnvelope) || m_ShowEnvelopePreview == 2)\n\t\t\tif(lQuads[i].m_PosEnv >= 0 && lQuads[i].m_PosEnv < m_Map.m_lEnvelopes.size())\n\t\t\t\tapEnvelope[i] = m_Map.m_lEnvelopes[lQuads[i].m_PosEnv];\n\t}\n\n\t//Draw Lines\n\tGraphics()->TextureClear();\n\tGraphics()->LinesBegin();\n\tGraphics()->SetColor(80.0f/255, 150.0f/255, 230.f/255, 0.5f);\n\tfor(int j = 0; j < Num; j++)\n\t{\n\t\tif(!apEnvelope[j])\n\t\t\tcontinue;\n\n\t\t//QuadParams\n\t\tconst CPoint *pPoints = lQuads[j].m_aPoints;\n\t\tfor(int i = 0; i < apEnvelope[j]->m_lPoints.size()-1; i++)\n\t\t{\n\t\t\tfloat OffsetX = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[0]);\n\t\t\tfloat OffsetY = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[1]);\n\t\t\tvec2 Pos0 = vec2(fx2f(pPoints[4].x)+OffsetX, fx2f(pPoints[4].y)+OffsetY);\n\n\t\t\tOffsetX = fx2f(apEnvelope[j]->m_lPoints[i+1].m_aValues[0]);\n\t\t\tOffsetY = fx2f(apEnvelope[j]->m_lPoints[i+1].m_aValues[1]);\n\t\t\tvec2 Pos1 = vec2(fx2f(pPoints[4].x)+OffsetX, fx2f(pPoints[4].y)+OffsetY);\n\n\t\t\tIGraphics::CLineItem Line = IGraphics::CLineItem(Pos0.x, Pos0.y, Pos1.x, Pos1.y);\n\t\t\tGraphics()->LinesDraw(&Line, 1);\n\t\t}\n\t}\n\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);\n\tGraphics()->LinesEnd();\n\n\t//Draw Quads\n\tGraphics()->TextureSet(Texture);\n\tGraphics()->QuadsBegin();\n\t\n\tfor(int j = 0; j < Num; j++)\n\t{\n\t\tif(!apEnvelope[j])\n\t\t\tcontinue;\n\n\t\t//QuadParams\n\t\tconst CPoint *pPoints = lQuads[j].m_aPoints;\n\n\t\tfor(int i = 0; i < apEnvelope[j]->m_lPoints.size(); i++)\n\t\t{\n\t\t\t//Calc Env Position\n\t\t\tfloat OffsetX = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[0]);\n\t\t\tfloat OffsetY = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[1]);\n\t\t\tfloat Rot = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[2])/360.0f*pi*2;\n\n\t\t\t//Set Colours\n\t\t\tfloat Alpha = (m_SelectedQuadEnvelope == lQuads[j].m_PosEnv && m_SelectedEnvelopePoint == i) ? 0.65f : 0.35f;\n\t\t\tIGraphics::CColorVertex aArray[4] = {\n\t\t\t\tIGraphics::CColorVertex(0, lQuads[j].m_aColors[0].r, lQuads[j].m_aColors[0].g, lQuads[j].m_aColors[0].b, Alpha),\n\t\t\t\tIGraphics::CColorVertex(1, lQuads[j].m_aColors[1].r, lQuads[j].m_aColors[1].g, lQuads[j].m_aColors[1].b, Alpha),\n\t\t\t\tIGraphics::CColorVertex(2, lQuads[j].m_aColors[2].r, lQuads[j].m_aColors[2].g, lQuads[j].m_aColors[2].b, Alpha),\n\t\t\t\tIGraphics::CColorVertex(3, lQuads[j].m_aColors[3].r, lQuads[j].m_aColors[3].g, lQuads[j].m_aColors[3].b, Alpha)};\n\t\t\tGraphics()->SetColorVertex(aArray, 4);\n\n\t\t\t//Rotation\n\t\t\tif(Rot != 0)\n\t\t\t{\n\t\t\t\tstatic CPoint aRotated[4];\n\t\t\t\taRotated[0] = lQuads[j].m_aPoints[0];\n\t\t\t\taRotated[1] = lQuads[j].m_aPoints[1];\n\t\t\t\taRotated[2] = lQuads[j].m_aPoints[2];\n\t\t\t\taRotated[3] = lQuads[j].m_aPoints[3];\n\t\t\t\tpPoints = aRotated;\n\n\t\t\t\tRotate(&lQuads[j].m_aPoints[4], &aRotated[0], Rot);\n\t\t\t\tRotate(&lQuads[j].m_aPoints[4], &aRotated[1], Rot);\n\t\t\t\tRotate(&lQuads[j].m_aPoints[4], &aRotated[2], Rot);\n\t\t\t\tRotate(&lQuads[j].m_aPoints[4], &aRotated[3], Rot);\n\t\t\t}\n\n\t\t\t//Set Texture Coords\n\t\t\tGraphics()->QuadsSetSubsetFree(\n\t\t\t\tfx2f(lQuads[j].m_aTexcoords[0].x), fx2f(lQuads[j].m_aTexcoords[0].y),\n\t\t\t\tfx2f(lQuads[j].m_aTexcoords[1].x), fx2f(lQuads[j].m_aTexcoords[1].y),\n\t\t\t\tfx2f(lQuads[j].m_aTexcoords[2].x), fx2f(lQuads[j].m_aTexcoords[2].y),\n\t\t\t\tfx2f(lQuads[j].m_aTexcoords[3].x), fx2f(lQuads[j].m_aTexcoords[3].y)\n\t\t\t);\n\n\t\t\t//Set Quad Coords & Draw\n\t\t\tIGraphics::CFreeformItem Freeform(\n\t\t\t\tfx2f(pPoints[0].x)+OffsetX, fx2f(pPoints[0].y)+OffsetY,\n\t\t\t\tfx2f(pPoints[1].x)+OffsetX, fx2f(pPoints[1].y)+OffsetY,\n\t\t\t\tfx2f(pPoints[2].x)+OffsetX, fx2f(pPoints[2].y)+OffsetY,\n\t\t\t\tfx2f(pPoints[3].x)+OffsetX, fx2f(pPoints[3].y)+OffsetY);\n\t\t\tGraphics()->QuadsDrawFreeform(&Freeform, 1);\n\t\t}\n\t}\n\tGraphics()->QuadsEnd();\n\tGraphics()->TextureClear();\n\tGraphics()->QuadsBegin();\n\n\t// Draw QuadPoints\n\tfor(int j = 0; j < Num; j++)\n\t{\n\t\tif(!apEnvelope[j])\n\t\t\tcontinue;\n\n\t\tfor(int i = 0; i < apEnvelope[j]->m_lPoints.size(); i++)\n\t\t\tDoQuadEnvPoint(&lQuads[j], j, i);\n\t}\n\tGraphics()->QuadsEnd();\n\tdelete[] apEnvelope;\n}\n\nvoid CEditor::DoQuadEnvPoint(const CQuad *pQuad, int QIndex, int PIndex)\n{\n\tenum\n\t{\n\t\tOP_NONE=0,\n\t\tOP_MOVE,\n\t\tOP_ROTATE,\n\t};\n\n\t// some basic values\n\tstatic float s_LastWx;\n\tstatic float s_LastWy;\n\tstatic int s_Operation = OP_NONE;\n\tfloat wx = UI()->MouseWorldX();\n\tfloat wy = UI()->MouseWorldY();\n\tCEnvelope *pEnvelope = m_Map.m_lEnvelopes[pQuad->m_PosEnv];\n\tvoid *pID = &pEnvelope->m_lPoints[PIndex];\n\tstatic int s_ActQIndex = -1;\n\n\t// get pivot\n\tfloat CenterX = fx2f(pQuad->m_aPoints[4].x)+fx2f(pEnvelope->m_lPoints[PIndex].m_aValues[0]);\n\tfloat CenterY = fx2f(pQuad->m_aPoints[4].y)+fx2f(pEnvelope->m_lPoints[PIndex].m_aValues[1]);\n\n\tfloat dx = (CenterX - wx)/m_WorldZoom;\n\tfloat dy = (CenterY - wy)/m_WorldZoom;\n\tif(dx*dx+dy*dy < 50.0f && UI()->ActiveItem() == 0)\n\t{\n\t\tUI()->SetHotItem(pID);\n\t\ts_ActQIndex = QIndex;\n\t}\n\n\tbool IgnoreGrid;\n\tif(Input()->KeyPressed(KEY_LALT) || Input()->KeyPressed(KEY_RALT))\n\t\tIgnoreGrid = true;\n\telse\n\t\tIgnoreGrid = false;\n\n\tif(UI()->ActiveItem() == pID && s_ActQIndex == QIndex)\n\t{\n\t\tif(s_Operation == OP_MOVE)\n\t\t{\n\t\t\tif(m_GridActive && !IgnoreGrid)\n\t\t\t{\n\t\t\t\tint LineDistance = GetLineDistance();\n\n\t\t\t\tfloat x = 0.0f;\n\t\t\t\tfloat y = 0.0f;\n\t\t\t\tif(wx >= 0)\n\t\t\t\t\tx = (int)((wx+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);\n\t\t\t\telse\n\t\t\t\t\tx = (int)((wx-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);\n\t\t\t\tif(wy >= 0)\n\t\t\t\t\ty = (int)((wy+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);\n\t\t\t\telse\n\t\t\t\t\ty = (int)((wy-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);\n\n\t\t\t\tpEnvelope->m_lPoints[PIndex].m_aValues[0] = f2fx(x);\n\t\t\t\tpEnvelope->m_lPoints[PIndex].m_aValues[1] = f2fx(y);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tpEnvelope->m_lPoints[PIndex].m_aValues[0] += f2fx(wx-s_LastWx);\n\t\t\t\tpEnvelope->m_lPoints[PIndex].m_aValues[1] += f2fx(wy-s_LastWy);\n\t\t\t}\n\t\t}\n\t\telse if(s_Operation == OP_ROTATE)\n\t\t\tpEnvelope->m_lPoints[PIndex].m_aValues[2] += 10*m_MouseDeltaX;\n\n\t\ts_LastWx = wx;\n\t\ts_LastWy = wy;\n\n\t\tif(!UI()->MouseButton(0))\n\t\t{\n\t\t\tm_LockMouse = false;\n\t\t\ts_Operation = OP_NONE;\n\t\t\tUI()->SetActiveItem(0);\n\t\t}\n\n\t\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t}\n\telse if(UI()->HotItem() == pID && s_ActQIndex == QIndex)\n\t{\n\t\tms_pUiGotContext = pID;\n\n\t\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\tm_pTooltip = \"Left mouse button to move. Hold ctrl to rotate. Hold alt to ignore grid.\";\n\n\t\tif(UI()->MouseButton(0))\n\t\t{\n\t\t\tif(Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL))\n\t\t\t{\n\t\t\t\tm_LockMouse = true;\n\t\t\t\ts_Operation = OP_ROTATE;\n\t\t\t}\n\t\t\telse\n\t\t\t\ts_Operation = OP_MOVE;\n\n\t\t\tm_SelectedEnvelopePoint = PIndex;\n\t\t\tm_SelectedQuadEnvelope = pQuad->m_PosEnv;\n\n\t\t\tUI()->SetActiveItem(pID);\n\t\t\tif(m_SelectedQuad != QIndex)\n\t\t\t\tm_SelectedPoints = 0;\n\t\t\tm_SelectedQuad = QIndex;\n\t\t\ts_LastWx = wx;\n\t\t\ts_LastWy = wy;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_SelectedEnvelopePoint = -1;\n\t\t\tm_SelectedQuadEnvelope = -1;\n\t\t}\n\t}\n\telse\n\t\tGraphics()->SetColor(0.0f, 1.0f, 0.0f, 1.0f);\n\n\tIGraphics::CQuadItem QuadItem(CenterX, CenterY, 5.0f*m_WorldZoom, 5.0f*m_WorldZoom);\n\tGraphics()->QuadsDraw(&QuadItem, 1);\n}\n\nvoid CEditor::DoMapEditor(CUIRect View, CUIRect ToolBar)\n{\n\t// render all good stuff\n\tif(!m_ShowPicker)\n\t{\n\t\tfor(int g = 0; g < m_Map.m_lGroups.size(); g++)\n\t\t{\n\t\t\tif(m_Map.m_lGroups[g]->m_Visible)\n\t\t\t\tm_Map.m_lGroups[g]->Render();\n\t\t\t//UI()->ClipEnable(&view);\n\t\t}\n\n\t\t// render the game above everything else\n\t\tif(m_Map.m_pGameGroup->m_Visible && m_Map.m_pGameLayer->m_Visible)\n\t\t{\n\t\t\tm_Map.m_pGameGroup->MapScreen();\n\t\t\tm_Map.m_pGameLayer->Render();\n\t\t}\n\n\t\tCLayerTiles *pT = static_cast<CLayerTiles *>(GetSelectedLayerType(0, LAYERTYPE_TILES));\n\t\tif(m_ShowTileInfo && pT && pT->m_Visible && m_ZoomLevel <= 300)\n\t\t{\n\t\t\tGetSelectedGroup()->MapScreen();\n\t\t\tpT->ShowInfo();\n\t\t}\n\t}\n\telse\n\t{\n\t\t// fix aspect ratio of the image in the picker\n\t\tfloat Max = min(View.w, View.h);\n\t\tView.w = View.h = Max;\n\t}\n\n\tstatic void *s_pEditorID = (void *)&s_pEditorID;\n\tint Inside = UI()->MouseInside(&View);\n\n\t// fetch mouse position\n\tfloat wx = UI()->MouseWorldX();\n\tfloat wy = UI()->MouseWorldY();\n\tfloat mx = UI()->MouseX();\n\tfloat my = UI()->MouseY();\n\n\tstatic float s_StartWx = 0;\n\tstatic float s_StartWy = 0;\n\n\tenum\n\t{\n\t\tOP_NONE=0,\n\t\tOP_BRUSH_GRAB,\n\t\tOP_BRUSH_DRAW,\n\t\tOP_BRUSH_PAINT,\n\t\tOP_PAN_WORLD,\n\t\tOP_PAN_EDITOR,\n\t};\n\n\t// remap the screen so it can display the whole tileset\n\tif(m_ShowPicker)\n\t{\n\t\tCUIRect Screen = *UI()->Screen();\n\t\tfloat Size = 32.0*16.0f;\n\t\tfloat w = Size*(Screen.w/View.w);\n\t\tfloat h = Size*(Screen.h/View.h);\n\t\tfloat x = -(View.x/Screen.w)*w;\n\t\tfloat y = -(View.y/Screen.h)*h;\n\t\twx = x+w*mx/Screen.w;\n\t\twy = y+h*my/Screen.h;\n\t\tGraphics()->MapScreen(x, y, x+w, y+h);\n\t\tCLayerTiles *t = (CLayerTiles *)GetSelectedLayerType(0, LAYERTYPE_TILES);\n\t\tif(t)\n\t\t{\n\t\t\tm_TilesetPicker.m_Image = t->m_Image;\n\t\t\tm_TilesetPicker.m_Texture = t->m_Texture;\n\t\t\tm_TilesetPicker.Render();\n\t\t\tif(m_ShowTileInfo)\n\t\t\t\tm_TilesetPicker.ShowInfo();\n\t\t}\n\t}\n\n\tstatic int s_Operation = OP_NONE;\n\n\t// draw layer borders\n\tCLayer *pEditLayers[16];\n\tint NumEditLayers = 0;\n\tNumEditLayers = 0;\n\n\tif(m_ShowPicker)\n\t{\n\t\tpEditLayers[0] = &m_TilesetPicker;\n\t\tNumEditLayers++;\n\t}\n\telse\n\t{\n\t\tpEditLayers[0] = GetSelectedLayer(0);\n\t\tif(pEditLayers[0])\n\t\t\tNumEditLayers++;\n\n\t\tCLayerGroup *g = GetSelectedGroup();\n\t\tif(g)\n\t\t{\n\t\t\tg->MapScreen();\n\n\t\t\tRenderGrid(g);\n\n\t\t\tfor(int i = 0; i < NumEditLayers; i++)\n\t\t\t{\n\t\t\t\tif(pEditLayers[i]->m_Type != LAYERTYPE_TILES)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tfloat w, h;\n\t\t\t\tpEditLayers[i]->GetSize(&w, &h);\n\n\t\t\t\tIGraphics::CLineItem Array[4] = {\n\t\t\t\t\tIGraphics::CLineItem(0, 0, w, 0),\n\t\t\t\t\tIGraphics::CLineItem(w, 0, w, h),\n\t\t\t\t\tIGraphics::CLineItem(w, h, 0, h),\n\t\t\t\t\tIGraphics::CLineItem(0, h, 0, 0)};\n\t\t\t\tGraphics()->TextureClear();\n\t\t\t\tGraphics()->LinesBegin();\n\t\t\t\tGraphics()->LinesDraw(Array, 4);\n\t\t\t\tGraphics()->LinesEnd();\n\t\t\t}\n\t\t}\n\t}\n\n\tif(Inside)\n\t{\n\t\tUI()->SetHotItem(s_pEditorID);\n\n\t\t// do global operations like pan and zoom\n\t\tif(UI()->ActiveItem() == 0 && (UI()->MouseButton(0) || UI()->MouseButton(2)))\n\t\t{\n\t\t\ts_StartWx = wx;\n\t\t\ts_StartWy = wy;\n\n\t\t\tif(Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL) || UI()->MouseButton(2))\n\t\t\t{\n\t\t\t\tif(Input()->KeyPressed(KEY_LSHIFT))\n\t\t\t\t\ts_Operation = OP_PAN_EDITOR;\n\t\t\t\telse\n\t\t\t\t\ts_Operation = OP_PAN_WORLD;\n\t\t\t\tUI()->SetActiveItem(s_pEditorID);\n\t\t\t}\n\t\t}\n\n\t\t// brush editing\n\t\tif(UI()->HotItem() == s_pEditorID)\n\t\t{\n\t\t\tif(m_Brush.IsEmpty())\n\t\t\t\tm_pTooltip = \"Use left mouse button to drag and create a brush.\";\n\t\t\telse\n\t\t\t\tm_pTooltip = \"Use left mouse button to paint with the brush. Right button clears the brush.\";\n\n\t\t\tif(UI()->ActiveItem() == s_pEditorID)\n\t\t\t{\n\t\t\t\tCUIRect r;\n\t\t\t\tr.x = s_StartWx;\n\t\t\t\tr.y = s_StartWy;\n\t\t\t\tr.w = wx-s_StartWx;\n\t\t\t\tr.h = wy-s_StartWy;\n\t\t\t\tif(r.w < 0)\n\t\t\t\t{\n\t\t\t\t\tr.x += r.w;\n\t\t\t\t\tr.w = -r.w;\n\t\t\t\t}\n\n\t\t\t\tif(r.h < 0)\n\t\t\t\t{\n\t\t\t\t\tr.y += r.h;\n\t\t\t\t\tr.h = -r.h;\n\t\t\t\t}\n\n\t\t\t\tif(s_Operation == OP_BRUSH_DRAW)\n\t\t\t\t{\n\t\t\t\t\tif(!m_Brush.IsEmpty())\n\t\t\t\t\t{\n\t\t\t\t\t\t// draw with brush\n\t\t\t\t\t\tfor(int k = 0; k < NumEditLayers; k++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(pEditLayers[k]->m_Type == m_Brush.m_lLayers[0]->m_Type)\n\t\t\t\t\t\t\t\tpEditLayers[k]->BrushDraw(m_Brush.m_lLayers[0], wx, wy);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if(s_Operation == OP_BRUSH_GRAB)\n\t\t\t\t{\n\t\t\t\t\tif(!UI()->MouseButton(0))\n\t\t\t\t\t{\n\t\t\t\t\t\t// grab brush\n\t\t\t\t\t\tchar aBuf[256];\n\t\t\t\t\t\tstr_format(aBuf, sizeof(aBuf),\"grabbing %f %f %f %f\", r.x, r.y, r.w, r.h);\n\t\t\t\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"editor\", aBuf);\n\n\t\t\t\t\t\t// TODO: do all layers\n\t\t\t\t\t\tint Grabs = 0;\n\t\t\t\t\t\tfor(int k = 0; k < NumEditLayers; k++)\n\t\t\t\t\t\t\tGrabs += pEditLayers[k]->BrushGrab(&m_Brush, r);\n\t\t\t\t\t\tif(Grabs == 0)\n\t\t\t\t\t\t\tm_Brush.Clear();\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t//editor.map.groups[selected_group]->mapscreen();\n\t\t\t\t\t\tfor(int k = 0; k < NumEditLayers; k++)\n\t\t\t\t\t\t\tpEditLayers[k]->BrushSelecting(r);\n\t\t\t\t\t\tGraphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if(s_Operation == OP_BRUSH_PAINT)\n\t\t\t\t{\n\t\t\t\t\tif(!UI()->MouseButton(0))\n\t\t\t\t\t{\n\t\t\t\t\t\tfor(int k = 0; k < NumEditLayers; k++)\n\t\t\t\t\t\t\tpEditLayers[k]->FillSelection(m_Brush.IsEmpty(), m_Brush.m_lLayers[0], r);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t//editor.map.groups[selected_group]->mapscreen();\n\t\t\t\t\t\tfor(int k = 0; k < NumEditLayers; k++)\n\t\t\t\t\t\t\tpEditLayers[k]->BrushSelecting(r);\n\t\t\t\t\t\tGraphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(UI()->MouseButton(1))\n\t\t\t\t\tm_Brush.Clear();\n\n\t\t\t\tif(UI()->MouseButton(0) && s_Operation == OP_NONE)\n\t\t\t\t{\n\t\t\t\t\tUI()->SetActiveItem(s_pEditorID);\n\n\t\t\t\t\tif(m_Brush.IsEmpty())\n\t\t\t\t\t\ts_Operation = OP_BRUSH_GRAB;\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\ts_Operation = OP_BRUSH_DRAW;\n\t\t\t\t\t\tfor(int k = 0; k < NumEditLayers; k++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(pEditLayers[k]->m_Type == m_Brush.m_lLayers[0]->m_Type)\n\t\t\t\t\t\t\t\tpEditLayers[k]->BrushPlace(m_Brush.m_lLayers[0], wx, wy);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tCLayerTiles *pLayer = (CLayerTiles*)GetSelectedLayerType(0, LAYERTYPE_TILES);\n\t\t\t\t\tif((Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) && pLayer)\n\t\t\t\t\t\ts_Operation = OP_BRUSH_PAINT;\n\t\t\t\t}\n\n\t\t\t\tif(!m_Brush.IsEmpty())\n\t\t\t\t{\n\t\t\t\t\tm_Brush.m_OffsetX = -(int)wx;\n\t\t\t\t\tm_Brush.m_OffsetY = -(int)wy;\n\t\t\t\t\tfor(int i = 0; i < m_Brush.m_lLayers.size(); i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(m_Brush.m_lLayers[i]->m_Type == LAYERTYPE_TILES)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tm_Brush.m_OffsetX = -(int)(wx/32.0f)*32;\n\t\t\t\t\t\t\tm_Brush.m_OffsetY = -(int)(wy/32.0f)*32;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tCLayerGroup *g = GetSelectedGroup();\n\t\t\t\t\tif(g)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_Brush.m_OffsetX += g->m_OffsetX;\n\t\t\t\t\t\tm_Brush.m_OffsetY += g->m_OffsetY;\n\t\t\t\t\t\tm_Brush.m_ParallaxX = g->m_ParallaxX;\n\t\t\t\t\t\tm_Brush.m_ParallaxY = g->m_ParallaxY;\n\t\t\t\t\t\tm_Brush.Render();\n\t\t\t\t\t\tfloat w, h;\n\t\t\t\t\t\tm_Brush.GetSize(&w, &h);\n\n\t\t\t\t\t\tIGraphics::CLineItem Array[4] = {\n\t\t\t\t\t\t\tIGraphics::CLineItem(0, 0, w, 0),\n\t\t\t\t\t\t\tIGraphics::CLineItem(w, 0, w, h),\n\t\t\t\t\t\t\tIGraphics::CLineItem(w, h, 0, h),\n\t\t\t\t\t\t\tIGraphics::CLineItem(0, h, 0, 0)};\n\t\t\t\t\t\tGraphics()->TextureClear();\n\t\t\t\t\t\tGraphics()->LinesBegin();\n\t\t\t\t\t\tGraphics()->LinesDraw(Array, 4);\n\t\t\t\t\t\tGraphics()->LinesEnd();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// quad editing\n\t\t{\n\t\t\tif(!m_ShowPicker && m_Brush.IsEmpty())\n\t\t\t{\n\t\t\t\t// fetch layers\n\t\t\t\tCLayerGroup *g = GetSelectedGroup();\n\t\t\t\tif(g)\n\t\t\t\t\tg->MapScreen();\n\n\t\t\t\tfor(int k = 0; k < NumEditLayers; k++)\n\t\t\t\t{\n\t\t\t\t\tif(pEditLayers[k]->m_Type == LAYERTYPE_QUADS)\n\t\t\t\t\t{\n\t\t\t\t\t\tCLayerQuads *pLayer = (CLayerQuads *)pEditLayers[k];\n\n\t\t\t\t\t\tif(!m_ShowEnvelopePreview)\n\t\t\t\t\t\t\tm_ShowEnvelopePreview = 2;\n\n\t\t\t\t\t\tGraphics()->TextureClear();\n\t\t\t\t\t\tGraphics()->QuadsBegin();\n\t\t\t\t\t\tfor(int i = 0; i < pLayer->m_lQuads.size(); i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor(int v = 0; v < 4; v++)\n\t\t\t\t\t\t\t\tDoQuadPoint(&pLayer->m_lQuads[i], i, v);\n\n\t\t\t\t\t\t\tDoQuad(&pLayer->m_lQuads[i], i);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tGraphics()->QuadsEnd();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tGraphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h);\n\t\t\t}\n\n\t\t\t// do panning\n\t\t\tif(UI()->ActiveItem() == s_pEditorID)\n\t\t\t{\n\t\t\t\tif(s_Operation == OP_PAN_WORLD)\n\t\t\t\t{\n\t\t\t\t\tm_WorldOffsetX -= m_MouseDeltaX*m_WorldZoom;\n\t\t\t\t\tm_WorldOffsetY -= m_MouseDeltaY*m_WorldZoom;\n\t\t\t\t}\n\t\t\t\telse if(s_Operation == OP_PAN_EDITOR)\n\t\t\t\t{\n\t\t\t\t\tm_EditorOffsetX -= m_MouseDeltaX*m_WorldZoom;\n\t\t\t\t\tm_EditorOffsetY -= m_MouseDeltaY*m_WorldZoom;\n\t\t\t\t}\n\n\t\t\t\t// release mouse\n\t\t\t\tif(!UI()->MouseButton(0))\n\t\t\t\t{\n\t\t\t\t\ts_Operation = OP_NONE;\n\t\t\t\t\tUI()->SetActiveItem(0);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse if(UI()->ActiveItem() == s_pEditorID)\n\t{\n\t\t// release mouse\n\t\tif(!UI()->MouseButton(0))\n\t\t{\n\t\t\ts_Operation = OP_NONE;\n\t\t\tUI()->SetActiveItem(0);\n\t\t}\n\t}\n\n\tif(!m_ShowPicker && GetSelectedGroup() && GetSelectedGroup()->m_UseClipping)\n\t{\n\t\tCLayerGroup *g = m_Map.m_pGameGroup;\n\t\tg->MapScreen();\n\n\t\tGraphics()->TextureClear();\n\t\tGraphics()->LinesBegin();\n\n\t\t\tCUIRect r;\n\t\t\tr.x = GetSelectedGroup()->m_ClipX;\n\t\t\tr.y = GetSelectedGroup()->m_ClipY;\n\t\t\tr.w = GetSelectedGroup()->m_ClipW;\n\t\t\tr.h = GetSelectedGroup()->m_ClipH;\n\n\t\t\tIGraphics::CLineItem Array[4] = {\n\t\t\t\tIGraphics::CLineItem(r.x, r.y, r.x+r.w, r.y),\n\t\t\t\tIGraphics::CLineItem(r.x+r.w, r.y, r.x+r.w, r.y+r.h),\n\t\t\t\tIGraphics::CLineItem(r.x+r.w, r.y+r.h, r.x, r.y+r.h),\n\t\t\t\tIGraphics::CLineItem(r.x, r.y+r.h, r.x, r.y)};\n\t\t\tGraphics()->SetColor(1,0,0,1);\n\t\t\tGraphics()->LinesDraw(Array, 4);\n\n\t\tGraphics()->LinesEnd();\n\t}\n\n\t// render screen sizes\n\tif(m_ProofBorders)\n\t{\n\t\tCLayerGroup *g = m_Map.m_pGameGroup;\n\t\tg->MapScreen();\n\n\t\tGraphics()->TextureClear();\n\t\tGraphics()->LinesBegin();\n\n\t\tfloat aLastPoints[4];\n\t\tfloat Start = 1.0f; //9.0f/16.0f;\n\t\tfloat End = 16.0f/9.0f;\n\t\tconst int NumSteps = 20;\n\t\tfor(int i = 0; i <= NumSteps; i++)\n\t\t{\n\t\t\tfloat aPoints[4];\n\t\t\tfloat Aspect = Start + (End-Start)*(i/(float)NumSteps);\n\n\t\t\tRenderTools()->MapscreenToWorld(\n\t\t\t\tm_WorldOffsetX, m_WorldOffsetY,\n\t\t\t\t1.0f, 1.0f, 0.0f, 0.0f, Aspect, 1.0f, aPoints);\n\n\t\t\tif(i == 0)\n\t\t\t{\n\t\t\t\tIGraphics::CLineItem Array[2] = {\n\t\t\t\t\tIGraphics::CLineItem(aPoints[0], aPoints[1], aPoints[2], aPoints[1]),\n\t\t\t\t\tIGraphics::CLineItem(aPoints[0], aPoints[3], aPoints[2], aPoints[3])};\n\t\t\t\tGraphics()->LinesDraw(Array, 2);\n\t\t\t}\n\n\t\t\tif(i != 0)\n\t\t\t{\n\t\t\t\tIGraphics::CLineItem Array[4] = {\n\t\t\t\t\tIGraphics::CLineItem(aPoints[0], aPoints[1], aLastPoints[0], aLastPoints[1]),\n\t\t\t\t\tIGraphics::CLineItem(aPoints[2], aPoints[1], aLastPoints[2], aLastPoints[1]),\n\t\t\t\t\tIGraphics::CLineItem(aPoints[0], aPoints[3], aLastPoints[0], aLastPoints[3]),\n\t\t\t\t\tIGraphics::CLineItem(aPoints[2], aPoints[3], aLastPoints[2], aLastPoints[3])};\n\t\t\t\tGraphics()->LinesDraw(Array, 4);\n\t\t\t}\n\n\t\t\tif(i == NumSteps)\n\t\t\t{\n\t\t\t\tIGraphics::CLineItem Array[2] = {\n\t\t\t\t\tIGraphics::CLineItem(aPoints[0], aPoints[1], aPoints[0], aPoints[3]),\n\t\t\t\t\tIGraphics::CLineItem(aPoints[2], aPoints[1], aPoints[2], aPoints[3])};\n\t\t\t\tGraphics()->LinesDraw(Array, 2);\n\t\t\t}\n\n\t\t\tmem_copy(aLastPoints, aPoints, sizeof(aPoints));\n\t\t}\n\n\t\tif(1)\n\t\t{\n\t\t\tGraphics()->SetColor(1,0,0,1);\n\t\t\tfor(int i = 0; i < 2; i++)\n\t\t\t{\n\t\t\t\tfloat aPoints[4];\n\t\t\t\tfloat aAspects[] = {4.0f/3.0f, 16.0f/10.0f, 5.0f/4.0f, 16.0f/9.0f};\n\t\t\t\tfloat Aspect = aAspects[i];\n\n\t\t\t\tRenderTools()->MapscreenToWorld(\n\t\t\t\t\tm_WorldOffsetX, m_WorldOffsetY,\n\t\t\t\t\t1.0f, 1.0f, 0.0f, 0.0f, Aspect, 1.0f, aPoints);\n\n\t\t\t\tCUIRect r;\n\t\t\t\tr.x = aPoints[0];\n\t\t\t\tr.y = aPoints[1];\n\t\t\t\tr.w = aPoints[2]-aPoints[0];\n\t\t\t\tr.h = aPoints[3]-aPoints[1];\n\n\t\t\t\tIGraphics::CLineItem Array[4] = {\n\t\t\t\t\tIGraphics::CLineItem(r.x, r.y, r.x+r.w, r.y),\n\t\t\t\t\tIGraphics::CLineItem(r.x+r.w, r.y, r.x+r.w, r.y+r.h),\n\t\t\t\t\tIGraphics::CLineItem(r.x+r.w, r.y+r.h, r.x, r.y+r.h),\n\t\t\t\t\tIGraphics::CLineItem(r.x, r.y+r.h, r.x, r.y)};\n\t\t\t\tGraphics()->LinesDraw(Array, 4);\n\t\t\t\tGraphics()->SetColor(0,1,0,1);\n\t\t\t}\n\t\t}\n\n\t\tGraphics()->LinesEnd();\n\t}\n\n\tif (!m_ShowPicker && m_ShowTileInfo && m_ShowEnvelopePreview != 0 && GetSelectedLayer(0) && GetSelectedLayer(0)->m_Type == LAYERTYPE_QUADS)\n\t{\n\t\tGetSelectedGroup()->MapScreen();\n\n\t\tCLayerQuads *pLayer = (CLayerQuads*)GetSelectedLayer(0);\n\t\tIGraphics::CTextureHandle Texture;\n\t\tif(pLayer->m_Image >= 0 && pLayer->m_Image < m_Map.m_lImages.size())\n\t\t\tTexture = m_Map.m_lImages[pLayer->m_Image]->m_Texture;\n\n\t\tDoQuadEnvelopes(pLayer->m_lQuads, Texture);\n\t\tm_ShowEnvelopePreview = 0;\n    }\n\n\tGraphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h);\n\t//UI()->ClipDisable();\n}\n\n\nint CEditor::DoProperties(CUIRect *pToolBox, CProperty *pProps, int *pIDs, int *pNewVal)\n{\n\tint Change = -1;\n\n\tfor(int i = 0; pProps[i].m_pName; i++)\n\t{\n\t\tCUIRect Slot;\n\t\tpToolBox->HSplitTop(13.0f, &Slot, pToolBox);\n\t\tCUIRect Label, Shifter;\n\t\tSlot.VSplitMid(&Label, &Shifter);\n\t\tShifter.HMargin(1.0f, &Shifter);\n\t\tUI()->DoLabel(&Label, pProps[i].m_pName, 10.0f, -1, -1);\n\n\t\tif(pProps[i].m_Type == PROPTYPE_INT_STEP)\n\t\t{\n\t\t\tCUIRect Inc, Dec;\n\t\t\tchar aBuf[64];\n\n\t\t\tShifter.VSplitRight(10.0f, &Shifter, &Inc);\n\t\t\tShifter.VSplitLeft(10.0f, &Dec, &Shifter);\n\t\t\tstr_format(aBuf, sizeof(aBuf),\"%d\", pProps[i].m_Value);\n\t\t\tRenderTools()->DrawUIRect(&Shifter, vec4(1,1,1,0.5f), 0, 0.0f);\n\t\t\tUI()->DoLabel(&Shifter, aBuf, 10.0f, 0, -1);\n\n\t\t\tif(DoButton_ButtonDec(&pIDs[i], 0, 0, &Dec, 0, \"Decrease\"))\n\t\t\t{\n\t\t\t\t*pNewVal = pProps[i].m_Value-1;\n\t\t\t\tChange = i;\n\t\t\t}\n\t\t\tif(DoButton_ButtonInc(((char *)&pIDs[i])+1, 0, 0, &Inc, 0, \"Increase\"))\n\t\t\t{\n\t\t\t\t*pNewVal = pProps[i].m_Value+1;\n\t\t\t\tChange = i;\n\t\t\t}\n\t\t}\n\t\telse if(pProps[i].m_Type == PROPTYPE_BOOL)\n\t\t{\n\t\t\tCUIRect No, Yes;\n\t\t\tShifter.VSplitMid(&No, &Yes);\n\t\t\tif(DoButton_ButtonDec(&pIDs[i], \"No\", !pProps[i].m_Value, &No, 0, \"\"))\n\t\t\t{\n\t\t\t\t*pNewVal = 0;\n\t\t\t\tChange = i;\n\t\t\t}\n\t\t\tif(DoButton_ButtonInc(((char *)&pIDs[i])+1, \"Yes\", pProps[i].m_Value, &Yes, 0, \"\"))\n\t\t\t{\n\t\t\t\t*pNewVal = 1;\n\t\t\t\tChange = i;\n\t\t\t}\n\t\t}\n\t\telse if(pProps[i].m_Type == PROPTYPE_INT_SCROLL)\n\t\t{\n\t\t\tint NewValue = UiDoValueSelector(&pIDs[i], &Shifter, \"\", pProps[i].m_Value, pProps[i].m_Min, pProps[i].m_Max, 1, 1.0f, \"Use left mouse button to drag and change the value. Hold shift to be more precise.\");\n\t\t\tif(NewValue != pProps[i].m_Value)\n\t\t\t{\n\t\t\t\t*pNewVal = NewValue;\n\t\t\t\tChange = i;\n\t\t\t}\n\t\t}\n\t\telse if(pProps[i].m_Type == PROPTYPE_COLOR)\n\t\t{\n\t\t\tstatic const char *s_paTexts[4] = {\"R\", \"G\", \"B\", \"A\"};\n\t\t\tstatic int s_aShift[] = {24, 16, 8, 0};\n\t\t\tint NewColor = 0;\n\n\t\t\tfor(int c = 0; c < 4; c++)\n\t\t\t{\n\t\t\t\tint v = (pProps[i].m_Value >> s_aShift[c])&0xff;\n\t\t\t\tNewColor |= UiDoValueSelector(((char *)&pIDs[i])+c, &Shifter, s_paTexts[c], v, 0, 255, 1, 1.0f, \"Use left mouse button to drag and change the color value. Hold shift to be more precise.\")<<s_aShift[c];\n\n\t\t\t\tif(c != 3)\n\t\t\t\t{\n\t\t\t\t\tpToolBox->HSplitTop(13.0f, &Slot, pToolBox);\n\t\t\t\t\tSlot.VSplitMid(0, &Shifter);\n\t\t\t\t\tShifter.HMargin(1.0f, &Shifter);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(NewColor != pProps[i].m_Value)\n\t\t\t{\n\t\t\t\t*pNewVal = NewColor;\n\t\t\t\tChange = i;\n\t\t\t}\n\t\t}\n\t\telse if(pProps[i].m_Type == PROPTYPE_IMAGE)\n\t\t{\n\t\t\tchar aBuf[64];\n\t\t\tif(pProps[i].m_Value < 0)\n\t\t\t\tstr_copy(aBuf, \"None\", sizeof(aBuf));\n\t\t\telse\n\t\t\t\tstr_format(aBuf, sizeof(aBuf),\"%s\", m_Map.m_lImages[pProps[i].m_Value]->m_aName);\n\n\t\t\tif(DoButton_Editor(&pIDs[i], aBuf, 0, &Shifter, 0, 0))\n\t\t\t\tPopupSelectImageInvoke(pProps[i].m_Value, UI()->MouseX(), UI()->MouseY());\n\n\t\t\tint r = PopupSelectImageResult();\n\t\t\tif(r >= -1)\n\t\t\t{\n\t\t\t\t*pNewVal = r;\n\t\t\t\tChange = i;\n\t\t\t}\n\t\t}\n\t\telse if(pProps[i].m_Type == PROPTYPE_SHIFT)\n\t\t{\n\t\t\tCUIRect Left, Right, Up, Down;\n\t\t\tShifter.VSplitMid(&Left, &Up);\n\t\t\tLeft.VSplitRight(1.0f, &Left, 0);\n\t\t\tUp.VSplitLeft(1.0f, 0, &Up);\n\t\t\tLeft.VSplitLeft(10.0f, &Left, &Shifter);\n\t\t\tShifter.VSplitRight(10.0f, &Shifter, &Right);\n\t\t\tRenderTools()->DrawUIRect(&Shifter, vec4(1,1,1,0.5f), 0, 0.0f);\n\t\t\tUI()->DoLabel(&Shifter, \"X\", 10.0f, 0, -1);\n\t\t\tUp.VSplitLeft(10.0f, &Up, &Shifter);\n\t\t\tShifter.VSplitRight(10.0f, &Shifter, &Down);\n\t\t\tRenderTools()->DrawUIRect(&Shifter, vec4(1,1,1,0.5f), 0, 0.0f);\n\t\t\tUI()->DoLabel(&Shifter, \"Y\", 10.0f, 0, -1);\n\t\t\tif(DoButton_ButtonDec(&pIDs[i], \"-\", 0, &Left, 0, \"Left\"))\n\t\t\t{\n\t\t\t\t*pNewVal = 1;\n\t\t\t\tChange = i;\n\t\t\t}\n\t\t\tif(DoButton_ButtonInc(((char *)&pIDs[i])+3, \"+\", 0, &Right, 0, \"Right\"))\n\t\t\t{\n\t\t\t\t*pNewVal = 2;\n\t\t\t\tChange = i;\n\t\t\t}\n\t\t\tif(DoButton_ButtonDec(((char *)&pIDs[i])+1, \"-\", 0, &Up, 0, \"Up\"))\n\t\t\t{\n\t\t\t\t*pNewVal = 4;\n\t\t\t\tChange = i;\n\t\t\t}\n\t\t\tif(DoButton_ButtonInc(((char *)&pIDs[i])+2, \"+\", 0, &Down, 0, \"Down\"))\n\t\t\t{\n\t\t\t\t*pNewVal = 8;\n\t\t\t\tChange = i;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn Change;\n}\n\nvoid CEditor::RenderLayers(CUIRect ToolBox, CUIRect ToolBar, CUIRect View)\n{\n\tCUIRect LayersBox = ToolBox;\n\n\tif(!m_GuiActive)\n\t\treturn;\n\n\tCUIRect Slot, Button;\n\tchar aBuf[64];\n\n\tfloat LayersHeight = 12.0f;\t // Height of AddGroup button\n\tstatic int s_ScrollBar = 0;\n\tstatic float s_ScrollValue = 0;\n\n\tfor(int g = 0; g < m_Map.m_lGroups.size(); g++)\n\t{\n\t\t// Each group is 19.0f\n\t\t// Each layer is 14.0f\n\t\tLayersHeight += 19.0f;\n\t\tif(!m_Map.m_lGroups[g]->m_Collapse)\n\t\t\tLayersHeight += m_Map.m_lGroups[g]->m_lLayers.size() * 14.0f;\n\t}\n\n\tfloat ScrollDifference = LayersHeight - LayersBox.h;\n\n\tif(LayersHeight > LayersBox.h)\t// Do we even need a scrollbar?\n\t{\n\t\tCUIRect Scroll;\n\t\tLayersBox.VSplitRight(15.0f, &LayersBox, &Scroll);\n\t\tLayersBox.VSplitRight(3.0f, &LayersBox, 0);\t// extra spacing\n\t\tScroll.HMargin(5.0f, &Scroll);\n\t\ts_ScrollValue = UiDoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue);\n\n\t\tif(UI()->MouseInside(&Scroll) || UI()->MouseInside(&LayersBox))\n\t\t{\n\t\t\tint ScrollNum = (int)((LayersHeight-LayersBox.h)/15.0f)+1;\n\t\t\tif(ScrollNum > 0)\n\t\t\t{\n\t\t\t\tif(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP))\n\t\t\t\t\ts_ScrollValue = clamp(s_ScrollValue - 1.0f/ScrollNum, 0.0f, 1.0f);\n\t\t\t\tif(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN))\n\t\t\t\t\ts_ScrollValue = clamp(s_ScrollValue + 1.0f/ScrollNum, 0.0f, 1.0f);\n\t\t\t}\n\t\t}\n\t}\n\n\tfloat LayerStartAt = ScrollDifference * s_ScrollValue;\n\tif(LayerStartAt < 0.0f)\n\t\tLayerStartAt = 0.0f;\n\n\tfloat LayerStopAt = LayersHeight - ScrollDifference * (1 - s_ScrollValue);\n\tfloat LayerCur = 0;\n\n\t// render layers\n\t{\n\t\tfor(int g = 0; g < m_Map.m_lGroups.size(); g++)\n\t\t{\n\t\t\tif(LayerCur > LayerStopAt)\n\t\t\t\tbreak;\n\t\t\telse if(LayerCur + m_Map.m_lGroups[g]->m_lLayers.size() * 14.0f + 19.0f < LayerStartAt)\n\t\t\t{\n\t\t\t\tLayerCur += m_Map.m_lGroups[g]->m_lLayers.size() * 14.0f + 19.0f;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tCUIRect VisibleToggle, SaveCheck;\n\t\t\tif(LayerCur >= LayerStartAt)\n\t\t\t{\n\t\t\t\tLayersBox.HSplitTop(12.0f, &Slot, &LayersBox);\n\t\t\t\tSlot.VSplitLeft(12, &VisibleToggle, &Slot);\n\t\t\t\tif(DoButton_Ex(&m_Map.m_lGroups[g]->m_Visible, m_Map.m_lGroups[g]->m_Visible?\"V\":\"H\", m_Map.m_lGroups[g]->m_Collapse ? 1 : 0, &VisibleToggle, 0, \"Toggle group visibility\", CUI::CORNER_L))\n\t\t\t\t\tm_Map.m_lGroups[g]->m_Visible = !m_Map.m_lGroups[g]->m_Visible;\n\n\t\t\t\tSlot.VSplitRight(12.0f, &Slot, &SaveCheck);\n\t\t\t\tif(DoButton_Ex(&m_Map.m_lGroups[g]->m_SaveToMap, \"S\", m_Map.m_lGroups[g]->m_SaveToMap, &SaveCheck, 0, \"Enable/disable group for saving\", CUI::CORNER_R))\n\t\t\t\t\tif(!m_Map.m_lGroups[g]->m_GameGroup)\n\t\t\t\t\t\tm_Map.m_lGroups[g]->m_SaveToMap = !m_Map.m_lGroups[g]->m_SaveToMap;\n\n\t\t\t\tstr_format(aBuf, sizeof(aBuf),\"#%d %s\", g, m_Map.m_lGroups[g]->m_aName);\n\t\t\t\tfloat FontSize = 10.0f;\n\t\t\t\twhile(TextRender()->TextWidth(0, FontSize, aBuf, -1) > Slot.w)\n\t\t\t\t\tFontSize--;\n\t\t\t\tif(int Result = DoButton_Ex(&m_Map.m_lGroups[g], aBuf, g==m_SelectedGroup, &Slot,\n\t\t\t\t\tBUTTON_CONTEXT, m_Map.m_lGroups[g]->m_Collapse ? \"Select group. Double click to expand.\" : \"Select group. Double click to collapse.\", 0, FontSize))\n\t\t\t\t{\n\t\t\t\t\tm_SelectedGroup = g;\n\t\t\t\t\tm_SelectedLayer = 0;\n\n\t\t\t\t\tstatic int s_GroupPopupId = 0;\n\t\t\t\t\tif(Result == 2)\n\t\t\t\t\t\tUiInvokePopupMenu(&s_GroupPopupId, 0, UI()->MouseX(), UI()->MouseY(), 145, 220, PopupGroup);\n\n\t\t\t\t\tif(m_Map.m_lGroups[g]->m_lLayers.size() && Input()->MouseDoubleClick())\n\t\t\t\t\t\tm_Map.m_lGroups[g]->m_Collapse ^= 1;\n\t\t\t\t}\n\t\t\t\tLayersBox.HSplitTop(2.0f, &Slot, &LayersBox);\n\t\t\t}\n\t\t\tLayerCur += 14.0f;\n\n\t\t\tfor(int i = 0; i < m_Map.m_lGroups[g]->m_lLayers.size(); i++)\n\t\t\t{\n\t\t\t\tif(LayerCur > LayerStopAt)\n\t\t\t\t\tbreak;\n\t\t\t\telse if(LayerCur < LayerStartAt)\n\t\t\t\t{\n\t\t\t\t\tLayerCur += 14.0f;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif(m_Map.m_lGroups[g]->m_Collapse)\n\t\t\t\t\tcontinue;\n\n\t\t\t\t//visible\n\t\t\t\tLayersBox.HSplitTop(12.0f, &Slot, &LayersBox);\n\t\t\t\tSlot.VSplitLeft(12.0f, 0, &Button);\n\t\t\t\tButton.VSplitLeft(15, &VisibleToggle, &Button);\n\n\t\t\t\tif(DoButton_Ex(&m_Map.m_lGroups[g]->m_lLayers[i]->m_Visible, m_Map.m_lGroups[g]->m_lLayers[i]->m_Visible?\"V\":\"H\", 0, &VisibleToggle, 0, \"Toggle layer visibility\", CUI::CORNER_L))\n\t\t\t\t\tm_Map.m_lGroups[g]->m_lLayers[i]->m_Visible = !m_Map.m_lGroups[g]->m_lLayers[i]->m_Visible;\n\n\t\t\t\tButton.VSplitRight(12.0f, &Button, &SaveCheck);\n\t\t\t\tif(DoButton_Ex(&m_Map.m_lGroups[g]->m_lLayers[i]->m_SaveToMap, \"S\", m_Map.m_lGroups[g]->m_lLayers[i]->m_SaveToMap, &SaveCheck, 0, \"Enable/disable layer for saving\", CUI::CORNER_R))\n\t\t\t\t\tif(m_Map.m_lGroups[g]->m_lLayers[i] != m_Map.m_pGameLayer)\n\t\t\t\t\t\tm_Map.m_lGroups[g]->m_lLayers[i]->m_SaveToMap = !m_Map.m_lGroups[g]->m_lLayers[i]->m_SaveToMap;\n\n\t\t\t\tif(m_Map.m_lGroups[g]->m_lLayers[i]->m_aName[0])\n\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"%s\", m_Map.m_lGroups[g]->m_lLayers[i]->m_aName);\n\t\t\t\telse if(m_Map.m_lGroups[g]->m_lLayers[i]->m_Type == LAYERTYPE_TILES)\n\t\t\t\t\tstr_copy(aBuf, \"Tiles\", sizeof(aBuf));\n\t\t\t\telse\n\t\t\t\t\tstr_copy(aBuf, \"Quads\", sizeof(aBuf));\n\n\t\t\t\tfloat FontSize = 10.0f;\n\t\t\t\twhile(TextRender()->TextWidth(0, FontSize, aBuf, -1) > Button.w)\n\t\t\t\t\tFontSize--;\n\t\t\t\tif(int Result = DoButton_Ex(m_Map.m_lGroups[g]->m_lLayers[i], aBuf, g==m_SelectedGroup&&i==m_SelectedLayer, &Button,\n\t\t\t\t\tBUTTON_CONTEXT, \"Select layer.\", 0, FontSize))\n\t\t\t\t{\n\t\t\t\t\tm_SelectedLayer = i;\n\t\t\t\t\tm_SelectedGroup = g;\n\t\t\t\t\tstatic int s_LayerPopupID = 0;\n\t\t\t\t\tif(Result == 2)\n\t\t\t\t\t\tUiInvokePopupMenu(&s_LayerPopupID, 0, UI()->MouseX(), UI()->MouseY(), 120, 245, PopupLayer);\n\t\t\t\t}\n\n\t\t\t\tLayerCur += 14.0f;\n\t\t\t\tLayersBox.HSplitTop(2.0f, &Slot, &LayersBox);\n\t\t\t}\n\t\t\tif(LayerCur > LayerStartAt && LayerCur < LayerStopAt)\n\t\t\t\tLayersBox.HSplitTop(5.0f, &Slot, &LayersBox);\n\t\t\tLayerCur += 5.0f;\n\t\t}\n\t}\n\n\tif(LayerCur <= LayerStopAt)\n\t{\n\t\tLayersBox.HSplitTop(12.0f, &Slot, &LayersBox);\n\n\t\tstatic int s_NewGroupButton = 0;\n\t\tif(DoButton_Editor(&s_NewGroupButton, \"Add group\", 0, &Slot, 0, \"Adds a new group\"))\n\t\t{\n\t\t\tm_Map.NewGroup();\n\t\t\tm_SelectedGroup = m_Map.m_lGroups.size()-1;\n\t\t}\n\t}\n}\n\nvoid CEditor::ReplaceImage(const char *pFileName, int StorageType, void *pUser)\n{\n\tCEditor *pEditor = (CEditor *)pUser;\n\tCEditorImage ImgInfo(pEditor);\n\tif(!pEditor->Graphics()->LoadPNG(&ImgInfo, pFileName, StorageType))\n\t\treturn;\n\n\tCEditorImage *pImg = pEditor->m_Map.m_lImages[pEditor->m_SelectedImage];\n\tint External = pImg->m_External;\n\tpEditor->Graphics()->UnloadTexture(pImg->m_Texture);\n\tpImg->m_Texture = IGraphics::CTextureHandle();\n\tif(pImg->m_pData)\n\t{\n\t\tmem_free(pImg->m_pData);\n\t\tpImg->m_pData = 0;\n\t}\n\tif(pImg->m_pAutoMapper)\n\t{\n\t\tdelete pImg->m_pAutoMapper;\n\t\tpImg->m_pAutoMapper = 0;\n\t}\n\t*pImg = ImgInfo;\n\tpImg->m_External = External;\n\tpEditor->ExtractName(pFileName, pImg->m_aName, sizeof(pImg->m_aName));\n\tpImg->LoadAutoMapper();\n\tpImg->m_Texture = pEditor->Graphics()->LoadTextureRaw(ImgInfo.m_Width, ImgInfo.m_Height, ImgInfo.m_Format, ImgInfo.m_pData, CImageInfo::FORMAT_AUTO, 0);\n\tImgInfo.m_pData = 0;\n\tpEditor->SortImages();\n\tfor(int i = 0; i < pEditor->m_Map.m_lImages.size(); ++i)\n\t{\n\t\tif(!str_comp(pEditor->m_Map.m_lImages[i]->m_aName, pImg->m_aName))\n\t\t\tpEditor->m_SelectedImage = i;\n\t}\n\tpEditor->m_Dialog = DIALOG_NONE;\n}\n\nvoid CEditor::AddImage(const char *pFileName, int StorageType, void *pUser)\n{\n\tCEditor *pEditor = (CEditor *)pUser;\n\tCEditorImage ImgInfo(pEditor);\n\tif(!pEditor->Graphics()->LoadPNG(&ImgInfo, pFileName, StorageType))\n\t\treturn;\n\n\t// check if we have that image already\n\tchar aBuf[128];\n\tExtractName(pFileName, aBuf, sizeof(aBuf));\n\tfor(int i = 0; i < pEditor->m_Map.m_lImages.size(); ++i)\n\t{\n\t\tif(!str_comp(pEditor->m_Map.m_lImages[i]->m_aName, aBuf))\n\t\t\treturn;\n\t}\n\n\tCEditorImage *pImg = new CEditorImage(pEditor);\n\t*pImg = ImgInfo;\n\tpImg->m_Texture = pEditor->Graphics()->LoadTextureRaw(ImgInfo.m_Width, ImgInfo.m_Height, ImgInfo.m_Format, ImgInfo.m_pData, CImageInfo::FORMAT_AUTO, 0);\n\tImgInfo.m_pData = 0;\n\tpImg->m_External = 1;\t// external by default\n\tstr_copy(pImg->m_aName, aBuf, sizeof(pImg->m_aName));\n\tpImg->LoadAutoMapper();\n\tpEditor->m_Map.m_lImages.add(pImg);\n\tpEditor->SortImages();\n\tif(pEditor->m_SelectedImage > -1 && pEditor->m_SelectedImage < pEditor->m_Map.m_lImages.size())\n\t{\n\t\tfor(int i = 0; i <= pEditor->m_SelectedImage; ++i)\n\t\t\tif(!str_comp(pEditor->m_Map.m_lImages[i]->m_aName, aBuf))\n\t\t\t{\n\t\t\t\tpEditor->m_SelectedImage++;\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n\tpEditor->m_Dialog = DIALOG_NONE;\n}\n\n\nstatic int gs_ModifyIndexDeletedIndex;\nstatic void ModifyIndexDeleted(int *pIndex)\n{\n\tif(*pIndex == gs_ModifyIndexDeletedIndex)\n\t\t*pIndex = -1;\n\telse if(*pIndex > gs_ModifyIndexDeletedIndex)\n\t\t*pIndex = *pIndex - 1;\n}\n\nint CEditor::PopupImage(CEditor *pEditor, CUIRect View)\n{\n\tstatic int s_ReplaceButton = 0;\n\tstatic int s_RemoveButton = 0;\n\n\tCUIRect Slot;\n\tView.HSplitTop(2.0f, &Slot, &View);\n\tView.HSplitTop(12.0f, &Slot, &View);\n\tCEditorImage *pImg = pEditor->m_Map.m_lImages[pEditor->m_SelectedImage];\n\n\tstatic int s_ExternalButton = 0;\n\tif(pImg->m_External)\n\t{\n\t\tif(pEditor->DoButton_MenuItem(&s_ExternalButton, \"Embed\", 0, &Slot, 0, \"Embeds the image into the map file.\"))\n\t\t{\n\t\t\tpImg->m_External = 0;\n\t\t\treturn 1;\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(pEditor->DoButton_MenuItem(&s_ExternalButton, \"Make external\", 0, &Slot, 0, \"Removes the image from the map file.\"))\n\t\t{\n\t\t\tpImg->m_External = 1;\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tView.HSplitTop(10.0f, &Slot, &View);\n\tView.HSplitTop(12.0f, &Slot, &View);\n\tif(pEditor->DoButton_MenuItem(&s_ReplaceButton, \"Replace\", 0, &Slot, 0, \"Replaces the image with a new one\"))\n\t{\n\t\tpEditor->InvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_IMG, \"Replace Image\", \"Replace\", \"mapres\", \"\", ReplaceImage, pEditor);\n\t\treturn 1;\n\t}\n\n\tView.HSplitTop(10.0f, &Slot, &View);\n\tView.HSplitTop(12.0f, &Slot, &View);\n\tif(pEditor->DoButton_MenuItem(&s_RemoveButton, \"Remove\", 0, &Slot, 0, \"Removes the image from the map\"))\n\t{\n\t\tdelete pImg;\n\t\tpEditor->m_Map.m_lImages.remove_index(pEditor->m_SelectedImage);\n\t\tgs_ModifyIndexDeletedIndex = pEditor->m_SelectedImage;\n\t\tpEditor->m_Map.ModifyImageIndex(ModifyIndexDeleted);\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n\nstatic int CompareImageName(const void *pObject1, const void *pObject2)\n{\n\tCEditorImage *pImage1 = *(CEditorImage**)pObject1;\n\tCEditorImage *pImage2 = *(CEditorImage**)pObject2;\n\n\treturn str_comp(pImage1->m_aName, pImage2->m_aName);\n}\n\nstatic int *gs_pSortedIndex = 0;\nstatic void ModifySortedIndex(int *pIndex)\n{\n\tif(*pIndex > -1)\n\t\t*pIndex = gs_pSortedIndex[*pIndex];\n}\n\nvoid CEditor::SortImages()\n{\n\tbool Sorted = true;\n\tfor(int i = 1; i < m_Map.m_lImages.size(); i++)\n\t\tif( str_comp(m_Map.m_lImages[i]->m_aName, m_Map.m_lImages[i-1]->m_aName) < 0 )\n\t\t{\n\t\t\tSorted = false;\n\t\t\tbreak;\n\t\t}\n\n\tif(!Sorted)\n\t{\n\t\tarray<CEditorImage*> lTemp = array<CEditorImage*>(m_Map.m_lImages);\n\t\tgs_pSortedIndex = new int[lTemp.size()];\n\n\t\tqsort(m_Map.m_lImages.base_ptr(), m_Map.m_lImages.size(), sizeof(CEditorImage*), CompareImageName);\n\n\t\tfor(int OldIndex = 0; OldIndex < lTemp.size(); OldIndex++)\n\t\t\tfor(int NewIndex = 0; NewIndex < m_Map.m_lImages.size(); NewIndex++)\n\t\t\t\tif(lTemp[OldIndex] == m_Map.m_lImages[NewIndex])\n\t\t\t\t\tgs_pSortedIndex[OldIndex] = NewIndex;\n\n\t\tm_Map.ModifyImageIndex(ModifySortedIndex);\n\n\t\tdelete [] gs_pSortedIndex;\n\t\tgs_pSortedIndex = 0;\n\t}\n}\n\n\nvoid CEditor::RenderImages(CUIRect ToolBox, CUIRect ToolBar, CUIRect View)\n{\n\tstatic int s_ScrollBar = 0;\n\tstatic float s_ScrollValue = 0;\n\tfloat ImagesHeight = 30.0f + 14.0f * m_Map.m_lImages.size() + 27.0f;\n\tfloat ScrollDifference = ImagesHeight - ToolBox.h;\n\n\tif(ImagesHeight > ToolBox.h)\t// Do we even need a scrollbar?\n\t{\n\t\tCUIRect Scroll;\n\t\tToolBox.VSplitRight(15.0f, &ToolBox, &Scroll);\n\t\tToolBox.VSplitRight(3.0f, &ToolBox, 0);\t// extra spacing\n\t\tScroll.HMargin(5.0f, &Scroll);\n\t\ts_ScrollValue = UiDoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue);\n\n\t\tif(UI()->MouseInside(&Scroll) || UI()->MouseInside(&ToolBox))\n\t\t{\n\t\t\tint ScrollNum = (int)((ImagesHeight-ToolBox.h)/14.0f)+1;\n\t\t\tif(ScrollNum > 0)\n\t\t\t{\n\t\t\t\tif(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP))\n\t\t\t\t\ts_ScrollValue = clamp(s_ScrollValue - 1.0f/ScrollNum, 0.0f, 1.0f);\n\t\t\t\tif(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN))\n\t\t\t\t\ts_ScrollValue = clamp(s_ScrollValue + 1.0f/ScrollNum, 0.0f, 1.0f);\n\t\t\t}\n\t\t}\n\t}\n\n\tfloat ImageStartAt = ScrollDifference * s_ScrollValue;\n\tif(ImageStartAt < 0.0f)\n\t\tImageStartAt = 0.0f;\n\n\tfloat ImageStopAt = ImagesHeight - ScrollDifference * (1 - s_ScrollValue);\n\tfloat ImageCur = 0.0f;\n\n\tfor(int e = 0; e < 2; e++) // two passes, first embedded, then external\n\t{\n\t\tCUIRect Slot;\n\n\t\tif(ImageCur > ImageStopAt)\n\t\t\tbreak;\n\t\telse if(ImageCur >= ImageStartAt)\n\t\t{\n\n\t\t\tToolBox.HSplitTop(15.0f, &Slot, &ToolBox);\n\t\t\tif(e == 0)\n\t\t\t\tUI()->DoLabel(&Slot, \"Embedded\", 12.0f, 0);\n\t\t\telse\n\t\t\t\tUI()->DoLabel(&Slot, \"External\", 12.0f, 0);\n\t\t}\n\t\tImageCur += 15.0f;\n\n\t\tfor(int i = 0; i < m_Map.m_lImages.size(); i++)\n\t\t{\n\t\t\tif((e && !m_Map.m_lImages[i]->m_External) ||\n\t\t\t\t(!e && m_Map.m_lImages[i]->m_External))\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif(ImageCur > ImageStopAt)\n\t\t\t\tbreak;\n\t\t\telse if(ImageCur < ImageStartAt)\n\t\t\t{\n\t\t\t\tImageCur += 14.0f;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tImageCur += 14.0f;\n\n\t\t\tchar aBuf[128];\n\t\t\tstr_copy(aBuf, m_Map.m_lImages[i]->m_aName, sizeof(aBuf));\n\t\t\tToolBox.HSplitTop(12.0f, &Slot, &ToolBox);\n\n\t\t\tif(int Result = DoButton_Editor(&m_Map.m_lImages[i], aBuf, m_SelectedImage == i, &Slot,\n\t\t\t\tBUTTON_CONTEXT, \"Select image\"))\n\t\t\t{\n\t\t\t\tm_SelectedImage = i;\n\n\t\t\t\tstatic int s_PopupImageID = 0;\n\t\t\t\tif(Result == 2)\n\t\t\t\t\tUiInvokePopupMenu(&s_PopupImageID, 0, UI()->MouseX(), UI()->MouseY(), 120, 80, PopupImage);\n\t\t\t}\n\n\t\t\tToolBox.HSplitTop(2.0f, 0, &ToolBox);\n\n\t\t\t// render image\n\t\t\tif(m_SelectedImage == i)\n\t\t\t{\n\t\t\t\tCUIRect r;\n\t\t\t\tView.Margin(10.0f, &r);\n\t\t\t\tif(r.h < r.w)\n\t\t\t\t\tr.w = r.h;\n\t\t\t\telse\n\t\t\t\t\tr.h = r.w;\n\t\t\t\tfloat Max = (float)(max(m_Map.m_lImages[i]->m_Width, m_Map.m_lImages[i]->m_Height));\n\t\t\t\tr.w *= m_Map.m_lImages[i]->m_Width/Max;\n\t\t\t\tr.h *= m_Map.m_lImages[i]->m_Height/Max;\n\t\t\t\tGraphics()->TextureSet(m_Map.m_lImages[i]->m_Texture);\n\t\t\t\tGraphics()->BlendNormal();\n\t\t\t\tGraphics()->WrapClamp();\n\t\t\t\tGraphics()->QuadsBegin();\n\t\t\t\tIGraphics::CQuadItem QuadItem(r.x, r.y, r.w, r.h);\n\t\t\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t\t\t\tGraphics()->QuadsEnd();\n\t\t\t\tGraphics()->WrapNormal();\n\t\t\t}\n\t\t}\n\n\t\t// separator\n\t\tToolBox.HSplitTop(5.0f, &Slot, &ToolBox);\n\t\tImageCur += 5.0f;\n\t\tIGraphics::CLineItem LineItem(Slot.x, Slot.y+Slot.h/2, Slot.x+Slot.w, Slot.y+Slot.h/2);\n\t\tGraphics()->TextureClear();\n\t\tGraphics()->LinesBegin();\n\t\tGraphics()->LinesDraw(&LineItem, 1);\n\t\tGraphics()->LinesEnd();\n\t}\n\n\tif(ImageCur + 27.0f > ImageStopAt)\n\t\treturn;\n\n\tCUIRect Slot;\n\tToolBox.HSplitTop(5.0f, &Slot, &ToolBox);\n\n\t// new image\n\tstatic int s_NewImageButton = 0;\n\tToolBox.HSplitTop(12.0f, &Slot, &ToolBox);\n\tif(DoButton_Editor(&s_NewImageButton, \"Add\", 0, &Slot, 0, \"Load a new image to use in the map\"))\n\t\tInvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_IMG, \"Add Image\", \"Add\", \"mapres\", \"\", AddImage, this);\n}\n\n\nstatic int EditorListdirCallback(const char *pName, int IsDir, int StorageType, void *pUser)\n{\n\tCEditor *pEditor = (CEditor*)pUser;\n\tint Length = str_length(pName);\n\tif((pName[0] == '.' && (pName[1] == 0 ||\n\t\t(pName[1] == '.' && pName[2] == 0 && (!str_comp(pEditor->m_pFileDialogPath, \"maps\") || !str_comp(pEditor->m_pFileDialogPath, \"mapres\"))))) ||\n\t\t(!IsDir && ((pEditor->m_FileDialogFileType == CEditor::FILETYPE_MAP && (Length < 4 || str_comp(pName+Length-4, \".map\"))) ||\n\t\t(pEditor->m_FileDialogFileType == CEditor::FILETYPE_IMG && (Length < 4 || str_comp(pName+Length-4, \".png\"))))))\n\t\treturn 0;\n\n\tCEditor::CFilelistItem Item;\n\tstr_copy(Item.m_aFilename, pName, sizeof(Item.m_aFilename));\n\tif(IsDir)\n\t\tstr_format(Item.m_aName, sizeof(Item.m_aName), \"%s/\", pName);\n\telse\n\t\tstr_copy(Item.m_aName, pName, min(static_cast<int>(sizeof(Item.m_aName)), Length-3));\n\tItem.m_IsDir = IsDir != 0;\n\tItem.m_IsLink = false;\n\tItem.m_StorageType = StorageType;\n\tpEditor->m_FileList.add(Item);\n\n\treturn 0;\n}\n\nvoid CEditor::AddFileDialogEntry(int Index, CUIRect *pView)\n{\n\tm_FilesCur++;\n\tif(m_FilesCur-1 < m_FilesStartAt || m_FilesCur >= m_FilesStopAt)\n\t\treturn;\n\n\tCUIRect Button, FileIcon;\n\tpView->HSplitTop(15.0f, &Button, pView);\n\tpView->HSplitTop(2.0f, 0, pView);\n\tButton.VSplitLeft(Button.h, &FileIcon, &Button);\n\tButton.VSplitLeft(5.0f, 0, &Button);\n\n\tGraphics()->TextureSet(g_pData->m_aImages[IMAGE_FILEICONS].m_Id);\n\tGraphics()->QuadsBegin();\n\tRenderTools()->SelectSprite(m_FileList[Index].m_IsDir?SPRITE_FILE_FOLDER:SPRITE_FILE_MAP2);\n\tIGraphics::CQuadItem QuadItem(FileIcon.x, FileIcon.y, FileIcon.w, FileIcon.h);\n\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\tGraphics()->QuadsEnd();\n\n\tif(DoButton_File(&m_FileList[Index], m_FileList[Index].m_aName, m_FilesSelectedIndex == Index, &Button, 0, 0))\n\t{\n\t\tif(!m_FileList[Index].m_IsDir)\n\t\t\tstr_copy(m_aFileDialogFileName, m_FileList[Index].m_aFilename, sizeof(m_aFileDialogFileName));\n\t\telse\n\t\t\tm_aFileDialogFileName[0] = 0;\n\t\tm_FilesSelectedIndex = Index;\n\n\t\tif(Input()->MouseDoubleClick())\n\t\t\tm_aFileDialogActivate = true;\n\t}\n}\n\nvoid CEditor::RenderFileDialog()\n{\n\t// GUI coordsys\n\tGraphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h);\n\tCUIRect View = *UI()->Screen();\n\tfloat Width = View.w, Height = View.h;\n\n\tRenderTools()->DrawUIRect(&View, vec4(0,0,0,0.25f), 0, 0);\n\tView.VMargin(150.0f, &View);\n\tView.HMargin(50.0f, &View);\n\tRenderTools()->DrawUIRect(&View, vec4(0,0,0,0.75f), CUI::CORNER_ALL, 5.0f);\n\tView.Margin(10.0f, &View);\n\n\tCUIRect Title, FileBox, FileBoxLabel, ButtonBar, Scroll, PathBox;\n\tView.HSplitTop(18.0f, &Title, &View);\n\tView.HSplitTop(5.0f, 0, &View); // some spacing\n\tView.HSplitBottom(14.0f, &View, &ButtonBar);\n\tView.HSplitBottom(10.0f, &View, 0); // some spacing\n\tView.HSplitBottom(14.0f, &View, &PathBox);\n\tView.HSplitBottom(5.0f, &View, 0); // some spacing\n\tView.HSplitBottom(14.0f, &View, &FileBox);\n\tFileBox.VSplitLeft(55.0f, &FileBoxLabel, &FileBox);\n\tView.HSplitBottom(10.0f, &View, 0); // some spacing\n\tView.VSplitRight(15.0f, &View, &Scroll);\n\n\t// title\n\tRenderTools()->DrawUIRect(&Title, vec4(1, 1, 1, 0.25f), CUI::CORNER_ALL, 4.0f);\n\tTitle.VMargin(10.0f, &Title);\n\tUI()->DoLabel(&Title, m_pFileDialogTitle, 12.0f, -1, -1);\n\n\t// pathbox\n\tchar aPath[128], aBuf[128];\n\tif(m_FilesSelectedIndex != -1)\n\t\tStorage()->GetCompletePath(m_FileList[m_FilesSelectedIndex].m_StorageType, m_pFileDialogPath, aPath, sizeof(aPath));\n\telse\n\t\taPath[0] = 0;\n\tstr_format(aBuf, sizeof(aBuf), \"Current path: %s\", aPath);\n\tUI()->DoLabel(&PathBox, aBuf, 10.0f, -1, -1);\n\n\t// filebox\n\tif(m_FileDialogStorageType == IStorage::TYPE_SAVE)\n\t{\n\t\tstatic float s_FileBoxID = 0;\n\t\tUI()->DoLabel(&FileBoxLabel, \"Filename:\", 10.0f, -1, -1);\n\t\tif(DoEditBox(&s_FileBoxID, &FileBox, m_aFileDialogFileName, sizeof(m_aFileDialogFileName), 10.0f, &s_FileBoxID))\n\t\t{\n\t\t\t// remove '/' and '\\'\n\t\t\tfor(int i = 0; m_aFileDialogFileName[i]; ++i)\n\t\t\t\tif(m_aFileDialogFileName[i] == '/' || m_aFileDialogFileName[i] == '\\\\')\n\t\t\t\t\tstr_copy(&m_aFileDialogFileName[i], &m_aFileDialogFileName[i+1], (int)(sizeof(m_aFileDialogFileName))-i);\n\t\t\tm_FilesSelectedIndex = -1;\n\t\t}\n\t}\n\n\tint Num = (int)(View.h/17.0f)+1;\n\tstatic int ScrollBar = 0;\n\tScroll.HMargin(5.0f, &Scroll);\n\tm_FileDialogScrollValue = UiDoScrollbarV(&ScrollBar, &Scroll, m_FileDialogScrollValue);\n\n\tint ScrollNum = m_FileList.size()-Num+1;\n\tif(ScrollNum > 0)\n\t{\n\t\tif(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP))\n\t\t\tm_FileDialogScrollValue -= 3.0f/ScrollNum;\n\t\tif(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN))\n\t\t\tm_FileDialogScrollValue += 3.0f/ScrollNum;\n\t}\n\telse\n\t\tScrollNum = 0;\n\n\tif(m_FilesSelectedIndex > -1)\n\t{\n\t\tfor(int i = 0; i < Input()->NumEvents(); i++)\n\t\t{\n\t\t\tint NewIndex = -1;\n\t\t\tif(Input()->GetEvent(i).m_Flags&IInput::FLAG_PRESS)\n\t\t\t{\n\t\t\t\tif(Input()->GetEvent(i).m_Key == KEY_DOWN) NewIndex = m_FilesSelectedIndex + 1;\n\t\t\t\tif(Input()->GetEvent(i).m_Key == KEY_UP) NewIndex = m_FilesSelectedIndex - 1;\n\t\t\t}\n\t\t\tif(NewIndex > -1 && NewIndex < m_FileList.size())\n\t\t\t{\n\t\t\t\t//scroll\n\t\t\t\tfloat IndexY = View.y - m_FileDialogScrollValue*ScrollNum*17.0f + NewIndex*17.0f;\n\t\t\t\tint Scroll = View.y > IndexY ? -1 : View.y+View.h < IndexY+17.0f ? 1 : 0;\n\t\t\t\tif(Scroll)\n\t\t\t\t{\n\t\t\t\t\tif(Scroll < 0)\n\t\t\t\t\t\tm_FileDialogScrollValue = ((float)(NewIndex)+0.5f)/ScrollNum;\n\t\t\t\t\telse\n\t\t\t\t\t\tm_FileDialogScrollValue = ((float)(NewIndex-Num)+2.5f)/ScrollNum;\n\t\t\t\t}\n\n\t\t\t\tif(!m_FileList[NewIndex].m_IsDir)\n\t\t\t\t\tstr_copy(m_aFileDialogFileName, m_FileList[NewIndex].m_aFilename, sizeof(m_aFileDialogFileName));\n\t\t\t\telse\n\t\t\t\t\tm_aFileDialogFileName[0] = 0;\n\t\t\t\tm_FilesSelectedIndex = NewIndex;\n\t\t\t}\n\t\t}\n\t}\n\n\tfor(int i = 0; i < Input()->NumEvents(); i++)\n\t{\n\t\tif(Input()->GetEvent(i).m_Flags&IInput::FLAG_PRESS)\n\t\t{\n\t\t\tif(Input()->GetEvent(i).m_Key == KEY_RETURN || Input()->GetEvent(i).m_Key == KEY_KP_ENTER)\n\t\t\t\tm_aFileDialogActivate = true;\n\t\t}\n\t}\n\n\tif(m_FileDialogScrollValue < 0) m_FileDialogScrollValue = 0;\n\tif(m_FileDialogScrollValue > 1) m_FileDialogScrollValue = 1;\n\n\tm_FilesStartAt = (int)(ScrollNum*m_FileDialogScrollValue);\n\tif(m_FilesStartAt < 0)\n\t\tm_FilesStartAt = 0;\n\n\tm_FilesStopAt = m_FilesStartAt+Num;\n\n\tm_FilesCur = 0;\n\n\t// set clipping\n\tUI()->ClipEnable(&View);\n\n\tfor(int i = 0; i < m_FileList.size(); i++)\n\t\tAddFileDialogEntry(i, &View);\n\n\t// disable clipping again\n\tUI()->ClipDisable();\n\n\t// the buttons\n\tstatic int s_OkButton = 0;\n\tstatic int s_CancelButton = 0;\n\tstatic int s_NewFolderButton = 0;\n\tstatic int s_MapInfoButton = 0;\n\n\tCUIRect Button;\n\tButtonBar.VSplitRight(50.0f, &ButtonBar, &Button);\n\tbool IsDir = m_FilesSelectedIndex >= 0 && m_FileList[m_FilesSelectedIndex].m_IsDir;\n\tif(DoButton_Editor(&s_OkButton, IsDir ? \"Open\" : m_pFileDialogButtonText, 0, &Button, 0, 0) || m_aFileDialogActivate)\n\t{\n\t\tm_aFileDialogActivate = false;\n\t\tif(IsDir)\t// folder\n\t\t{\n\t\t\tif(str_comp(m_FileList[m_FilesSelectedIndex].m_aFilename, \"..\") == 0)\t// parent folder\n\t\t\t{\n\t\t\t\tif(fs_parent_dir(m_pFileDialogPath))\n\t\t\t\t\tm_pFileDialogPath = m_aFileDialogCurrentFolder;\t// leave the link\n\t\t\t}\n\t\t\telse\t// sub folder\n\t\t\t{\n\t\t\t\tif(m_FileList[m_FilesSelectedIndex].m_IsLink)\n\t\t\t\t{\n\t\t\t\t\tm_pFileDialogPath = m_aFileDialogCurrentLink;\t// follow the link\n\t\t\t\t\tstr_copy(m_aFileDialogCurrentLink, m_FileList[m_FilesSelectedIndex].m_aFilename, sizeof(m_aFileDialogCurrentLink));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tchar aTemp[MAX_PATH_LENGTH];\n\t\t\t\t\tstr_copy(aTemp, m_pFileDialogPath, sizeof(aTemp));\n\t\t\t\t\tstr_format(m_pFileDialogPath, MAX_PATH_LENGTH, \"%s/%s\", aTemp, m_FileList[m_FilesSelectedIndex].m_aFilename);\n\t\t\t\t}\n\t\t\t}\n\t\t\tFilelistPopulate(!str_comp(m_pFileDialogPath, \"maps\") || !str_comp(m_pFileDialogPath, \"mapres\") ? m_FileDialogStorageType :\n\t\t\t\tm_FileList[m_FilesSelectedIndex].m_StorageType);\n\t\t\tif(m_FilesSelectedIndex >= 0 && !m_FileList[m_FilesSelectedIndex].m_IsDir)\n\t\t\t\tstr_copy(m_aFileDialogFileName, m_FileList[m_FilesSelectedIndex].m_aFilename, sizeof(m_aFileDialogFileName));\n\t\t\telse\n\t\t\t\tm_aFileDialogFileName[0] = 0;\n\t\t}\n\t\telse // file\n\t\t{\n\t\t\tstr_format(m_aFileSaveName, sizeof(m_aFileSaveName), \"%s/%s\", m_pFileDialogPath, m_aFileDialogFileName);\n\t\t\tif(!str_comp(m_pFileDialogButtonText, \"Save\"))\n\t\t\t{\n\t\t\t\tIOHANDLE File = Storage()->OpenFile(m_aFileSaveName, IOFLAG_READ, IStorage::TYPE_SAVE);\n\t\t\t\tif(File)\n\t\t\t\t{\n\t\t\t\t\tio_close(File);\n\t\t\t\t\tm_PopupEventType = POPEVENT_SAVE;\n\t\t\t\t\tm_PopupEventActivated = true;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tif(m_pfnFileDialogFunc)\n\t\t\t\t\t\tm_pfnFileDialogFunc(m_aFileSaveName, m_FilesSelectedIndex >= 0 ? m_FileList[m_FilesSelectedIndex].m_StorageType : m_FileDialogStorageType, m_pFileDialogUser);\n\t\t\t}\n\t\t\telse\n\t\t\t\tif(m_pfnFileDialogFunc)\n\t\t\t\t\tm_pfnFileDialogFunc(m_aFileSaveName, m_FilesSelectedIndex >= 0 ? m_FileList[m_FilesSelectedIndex].m_StorageType : m_FileDialogStorageType, m_pFileDialogUser);\n\t\t}\n\t}\n\n\tButtonBar.VSplitRight(40.0f, &ButtonBar, &Button);\n\tButtonBar.VSplitRight(50.0f, &ButtonBar, &Button);\n\tif(DoButton_Editor(&s_CancelButton, \"Cancel\", 0, &Button, 0, 0) || Input()->KeyPressed(KEY_ESCAPE))\n\t\tm_Dialog = DIALOG_NONE;\n\n\tif(m_FileDialogStorageType == IStorage::TYPE_SAVE)\n\t{\n\t\tButtonBar.VSplitLeft(40.0f, 0, &ButtonBar);\n\t\tButtonBar.VSplitLeft(70.0f, &Button, &ButtonBar);\n\t\tif(DoButton_Editor(&s_NewFolderButton, \"New folder\", 0, &Button, 0, 0))\n\t\t{\n\t\t\tm_FileDialogNewFolderName[0] = 0;\n\t\t\tm_FileDialogErrString[0] = 0;\n\t\t\tstatic int s_NewFolderPopupID = 0;\n\t\t\tUiInvokePopupMenu(&s_NewFolderPopupID, 0, Width/2.0f-200.0f, Height/2.0f-100.0f, 400.0f, 200.0f, PopupNewFolder);\n\t\t\tUI()->SetActiveItem(0);\n\t\t}\n\t}\n\n\tif(m_FileDialogStorageType == IStorage::TYPE_SAVE)\n\t{\n\t\tButtonBar.VSplitLeft(40.0f, 0, &ButtonBar);\n\t\tButtonBar.VSplitLeft(70.0f, &Button, &ButtonBar);\n\t\tif(DoButton_Editor(&s_MapInfoButton, \"Map details\", 0, &Button, 0, 0))\n\t\t{\n\t\t\tstr_copy(m_Map.m_MapInfo.m_aAuthorTmp, m_Map.m_MapInfo.m_aAuthor, sizeof(m_Map.m_MapInfo.m_aAuthorTmp));\n\t\t\tstr_copy(m_Map.m_MapInfo.m_aVersionTmp, m_Map.m_MapInfo.m_aVersion, sizeof(m_Map.m_MapInfo.m_aVersionTmp));\n\t\t\tstr_copy(m_Map.m_MapInfo.m_aCreditsTmp, m_Map.m_MapInfo.m_aCredits, sizeof(m_Map.m_MapInfo.m_aCreditsTmp));\n\t\t\tstr_copy(m_Map.m_MapInfo.m_aLicenseTmp, m_Map.m_MapInfo.m_aLicense, sizeof(m_Map.m_MapInfo.m_aLicenseTmp));\n\t\t\tstatic int s_MapInfoPopupID = 0;\n\t\t\tUiInvokePopupMenu(&s_MapInfoPopupID, 0, Width/2.0f-200.0f, Height/2.0f-100.0f, 400.0f, 200.0f, PopupMapInfo);\n\t\t\tUI()->SetActiveItem(0);\n\t\t}\n\t}\n}\n\nvoid CEditor::FilelistPopulate(int StorageType)\n{\n\tm_FileList.clear();\n\tif(m_FileDialogStorageType != IStorage::TYPE_SAVE && !str_comp(m_pFileDialogPath, \"maps\"))\n\t{\n\t\tCFilelistItem Item;\n\t\tstr_copy(Item.m_aFilename, \"downloadedmaps\", sizeof(Item.m_aFilename));\n\t\tstr_copy(Item.m_aName, \"downloadedmaps/\", sizeof(Item.m_aName));\n\t\tItem.m_IsDir = true;\n\t\tItem.m_IsLink = true;\n\t\tItem.m_StorageType = IStorage::TYPE_SAVE;\n\t\tm_FileList.add(Item);\n\t}\n\tStorage()->ListDirectory(StorageType, m_pFileDialogPath, EditorListdirCallback, this);\n\tm_FilesSelectedIndex = m_FileList.size() ? 0 : -1;\n\tm_aFileDialogActivate = false;\n}\n\nvoid CEditor::InvokeFileDialog(int StorageType, int FileType, const char *pTitle, const char *pButtonText,\n\tconst char *pBasePath, const char *pDefaultName,\n\tvoid (*pfnFunc)(const char *pFileName, int StorageType, void *pUser), void *pUser)\n{\n\tm_FileDialogStorageType = StorageType;\n\tm_pFileDialogTitle = pTitle;\n\tm_pFileDialogButtonText = pButtonText;\n\tm_pfnFileDialogFunc = pfnFunc;\n\tm_pFileDialogUser = pUser;\n\tm_aFileDialogFileName[0] = 0;\n\tm_aFileDialogCurrentFolder[0] = 0;\n\tm_aFileDialogCurrentLink[0] = 0;\n\tm_pFileDialogPath = m_aFileDialogCurrentFolder;\n\tm_FileDialogFileType = FileType;\n\tm_FileDialogScrollValue = 0.0f;\n\n\tif(pDefaultName)\n\t\tstr_copy(m_aFileDialogFileName, pDefaultName, sizeof(m_aFileDialogFileName));\n\tif(pBasePath)\n\t\tstr_copy(m_aFileDialogCurrentFolder, pBasePath, sizeof(m_aFileDialogCurrentFolder));\n\n\tFilelistPopulate(m_FileDialogStorageType);\n\n\tm_Dialog = DIALOG_FILE;\n}\n\n\n\nvoid CEditor::RenderModebar(CUIRect View)\n{\n\tCUIRect Button;\n\n\t// mode buttons\n\t{\n\t\tView.VSplitLeft(65.0f, &Button, &View);\n\t\tButton.HSplitTop(30.0f, 0, &Button);\n\t\tstatic int s_Button = 0;\n\t\tconst char *pButName = m_Mode == MODE_LAYERS ? \"Layers\" : \"Images\";\n\t\tif(DoButton_Tab(&s_Button, pButName, 0, &Button, 0, \"Switch between images and layers managment.\"))\n\t\t{\n\t\t\tif(m_Mode == MODE_LAYERS)\n\t\t\t\tm_Mode = MODE_IMAGES;\n\t\t\telse\n\t\t\t\tm_Mode = MODE_LAYERS;\n\t\t}\n\t}\n\n\tView.VSplitLeft(5.0f, 0, &View);\n}\n\nvoid CEditor::RenderStatusbar(CUIRect View)\n{\n\tCUIRect Button;\n\tView.VSplitRight(60.0f, &View, &Button);\n\tstatic int s_EnvelopeButton = 0;\n\tif(DoButton_Editor(&s_EnvelopeButton, \"Envelopes\", m_ShowEnvelopeEditor, &Button, 0, \"Toggles the envelope editor.\"))\n\t\tm_ShowEnvelopeEditor = (m_ShowEnvelopeEditor+1)%4;\n\n\tif(m_pTooltip)\n\t{\n\t\tif(ms_pUiGotContext && ms_pUiGotContext == UI()->HotItem())\n\t\t{\n\t\t\tchar aBuf[512];\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"%s Right click for context menu.\", m_pTooltip);\n\t\t\tUI()->DoLabel(&View, aBuf, 10.0f, -1, -1);\n\t\t}\n\t\telse\n\t\t\tUI()->DoLabel(&View, m_pTooltip, 10.0f, -1, -1);\n\t}\n}\n\nvoid CEditor::RenderEnvelopeEditor(CUIRect View)\n{\n\tif(m_SelectedEnvelope < 0) m_SelectedEnvelope = 0;\n\tif(m_SelectedEnvelope >= m_Map.m_lEnvelopes.size()) m_SelectedEnvelope = m_Map.m_lEnvelopes.size()-1;\n\n\tCEnvelope *pEnvelope = 0;\n\tif(m_SelectedEnvelope >= 0 && m_SelectedEnvelope < m_Map.m_lEnvelopes.size())\n\t\tpEnvelope = m_Map.m_lEnvelopes[m_SelectedEnvelope];\n\n\tCUIRect ToolBar, CurveBar, ColorBar;\n\tView.HSplitTop(15.0f, &ToolBar, &View);\n\tView.HSplitTop(15.0f, &CurveBar, &View);\n\tToolBar.Margin(2.0f, &ToolBar);\n\tCurveBar.Margin(2.0f, &CurveBar);\n\n\t// do the toolbar\n\t{\n\t\tCUIRect Button;\n\t\tCEnvelope *pNewEnv = 0;\n\n\t\tToolBar.VSplitRight(50.0f, &ToolBar, &Button);\n\t\tstatic int s_New4dButton = 0;\n\t\tif(DoButton_Editor(&s_New4dButton, \"Color+\", 0, &Button, 0, \"Creates a new color envelope\"))\n\t\t{\n\t\t\tm_Map.m_Modified = true;\n\t\t\tpNewEnv = m_Map.NewEnvelope(4);\n\t\t}\n\n\t\tToolBar.VSplitRight(5.0f, &ToolBar, &Button);\n\t\tToolBar.VSplitRight(50.0f, &ToolBar, &Button);\n\t\tstatic int s_New2dButton = 0;\n\t\tif(DoButton_Editor(&s_New2dButton, \"Pos.+\", 0, &Button, 0, \"Creates a new pos envelope\"))\n\t\t{\n\t\t\tm_Map.m_Modified = true;\n\t\t\tpNewEnv = m_Map.NewEnvelope(3);\n\t\t}\n\n\t\t// Delete button\n\t\tif(m_SelectedEnvelope >= 0)\n\t\t{\n\t\t\tToolBar.VSplitRight(10.0f, &ToolBar, &Button);\n\t\t\tToolBar.VSplitRight(50.0f, &ToolBar, &Button);\n\t\t\tstatic int s_DelButton = 0;\n\t\t\tif(DoButton_Editor(&s_DelButton, \"Delete\", 0, &Button, 0, \"Delete this envelope\"))\n\t\t\t{\n\t\t\t\tm_Map.m_Modified = true;\n\t\t\t\tm_Map.DeleteEnvelope(m_SelectedEnvelope);\n\t\t\t\tif(m_SelectedEnvelope >= m_Map.m_lEnvelopes.size())\n\t\t\t\t\tm_SelectedEnvelope = m_Map.m_lEnvelopes.size()-1;\n\t\t\t\tpEnvelope = m_SelectedEnvelope >= 0 ? m_Map.m_lEnvelopes[m_SelectedEnvelope] : 0;\n\t\t\t}\n\t\t}\n\n\t\tif(pNewEnv) // add the default points\n\t\t{\n\t\t\tif(pNewEnv->m_Channels == 4)\n\t\t\t{\n\t\t\t\tpNewEnv->AddPoint(0, 1,1,1,1);\n\t\t\t\tpNewEnv->AddPoint(1000, 1,1,1,1);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tpNewEnv->AddPoint(0, 0);\n\t\t\t\tpNewEnv->AddPoint(1000, 0);\n\t\t\t}\n\t\t}\n\n\t\tCUIRect Shifter, Inc, Dec;\n\t\tToolBar.VSplitLeft(60.0f, &Shifter, &ToolBar);\n\t\tShifter.VSplitRight(15.0f, &Shifter, &Inc);\n\t\tShifter.VSplitLeft(15.0f, &Dec, &Shifter);\n\t\tchar aBuf[512];\n\t\tstr_format(aBuf, sizeof(aBuf),\"%d/%d\", m_SelectedEnvelope+1, m_Map.m_lEnvelopes.size());\n\t\tRenderTools()->DrawUIRect(&Shifter, vec4(1,1,1,0.5f), 0, 0.0f);\n\t\tUI()->DoLabel(&Shifter, aBuf, 10.0f, 0, -1);\n\n\t\tstatic int s_PrevButton = 0;\n\t\tif(DoButton_ButtonDec(&s_PrevButton, 0, 0, &Dec, 0, \"Previous Envelope\"))\n\t\t\tm_SelectedEnvelope--;\n\n\t\tstatic int s_NextButton = 0;\n\t\tif(DoButton_ButtonInc(&s_NextButton, 0, 0, &Inc, 0, \"Next Envelope\"))\n\t\t\tm_SelectedEnvelope++;\n\n\t\tif(pEnvelope)\n\t\t{\n\t\t\tToolBar.VSplitLeft(15.0f, &Button, &ToolBar);\n\t\t\tToolBar.VSplitLeft(35.0f, &Button, &ToolBar);\n\t\t\tUI()->DoLabel(&Button, \"Name:\", 10.0f, -1, -1);\n\n\t\t\tToolBar.VSplitLeft(80.0f, &Button, &ToolBar);\n\n\t\t\tstatic float s_NameBox = 0;\n\t\t\tif(DoEditBox(&s_NameBox, &Button, pEnvelope->m_aName, sizeof(pEnvelope->m_aName), 10.0f, &s_NameBox))\n\t\t\t\tm_Map.m_Modified = true;\n\t\t}\n\t}\n\n\tbool ShowColorBar = false;\n\tif(pEnvelope && pEnvelope->m_Channels == 4)\n\t{\n\t\tShowColorBar = true;\n\t\tView.HSplitTop(20.0f, &ColorBar, &View);\n\t\tColorBar.Margin(2.0f, &ColorBar);\n\t\tRenderBackground(ColorBar, m_CheckerTexture, 16.0f, 1.0f);\n\t}\n\n\tRenderBackground(View, m_CheckerTexture, 32.0f, 0.1f);\n\n\tif(pEnvelope)\n\t{\n\t\tstatic array<int> Selection;\n\t\tstatic int sEnvelopeEditorID = 0;\n\t\tstatic int s_ActiveChannels = 0xf;\n\n\t\tif(pEnvelope)\n\t\t{\n\t\t\tCUIRect Button;\n\n\t\t\tToolBar.VSplitLeft(15.0f, &Button, &ToolBar);\n\n\t\t\tstatic const char *s_paNames[2][4] = {\n\t\t\t\t{\"X\", \"Y\", \"R\", \"\"},\n\t\t\t\t{\"R\", \"G\", \"B\", \"A\"},\n\t\t\t};\n\n\t\t\tconst char *paDescriptions[2][4] = {\n\t\t\t\t{\"X-axis of the envelope\", \"Y-axis of the envelope\", \"Rotation of the envelope\", \"\"},\n\t\t\t\t{\"Red value of the envelope\", \"Green value of the envelope\", \"Blue value of the envelope\", \"Alpha value of the envelope\"},\n\t\t\t};\n\n\t\t\tstatic int s_aChannelButtons[4] = {0};\n\t\t\tint Bit = 1;\n\t\t\t//ui_draw_button_func draw_func;\n\n\t\t\tfor(int i = 0; i < pEnvelope->m_Channels; i++, Bit<<=1)\n\t\t\t{\n\t\t\t\tToolBar.VSplitLeft(15.0f, &Button, &ToolBar);\n\n\t\t\t\t/*if(i == 0) draw_func = draw_editor_button_l;\n\t\t\t\telse if(i == envelope->channels-1) draw_func = draw_editor_button_r;\n\t\t\t\telse draw_func = draw_editor_button_m;*/\n\n\t\t\t\tif(DoButton_Editor(&s_aChannelButtons[i], s_paNames[pEnvelope->m_Channels-3][i], s_ActiveChannels&Bit, &Button, 0, paDescriptions[pEnvelope->m_Channels-3][i]))\n\t\t\t\t\ts_ActiveChannels ^= Bit;\n\t\t\t}\n\n\t\t\t// sync checkbox\n\t\t\tToolBar.VSplitLeft(15.0f, &Button, &ToolBar);\n\t\t\tToolBar.VSplitLeft(12.0f, &Button, &ToolBar);\n\t\t\tstatic int s_SyncButton;\n\t\t\tif(DoButton_Editor(&s_SyncButton, pEnvelope->m_Synchronized?\"X\":\"\", 0, &Button, 0, \"Enable envelope synchronization between clients\"))\n\t\t\t\tpEnvelope->m_Synchronized = !pEnvelope->m_Synchronized;\n\n\t\t\tToolBar.VSplitLeft(4.0f, &Button, &ToolBar);\n\t\t\tToolBar.VSplitLeft(80.0f, &Button, &ToolBar);\n\t\t\tUI()->DoLabel(&Button, \"Synchronized\", 10.0f, -1, -1);\n\t\t}\n\n\t\tfloat EndTime = pEnvelope->EndTime();\n\t\tif(EndTime < 1)\n\t\t\tEndTime = 1;\n\n\t\tpEnvelope->FindTopBottom(s_ActiveChannels);\n\t\tfloat Top = pEnvelope->m_Top;\n\t\tfloat Bottom = pEnvelope->m_Bottom;\n\n\t\tif(Top < 1)\n\t\t\tTop = 1;\n\t\tif(Bottom >= 0)\n\t\t\tBottom = 0;\n\n\t\tfloat TimeScale = EndTime/View.w;\n\t\tfloat ValueScale = (Top-Bottom)/View.h;\n\n\t\tif(UI()->MouseInside(&View))\n\t\t\tUI()->SetHotItem(&sEnvelopeEditorID);\n\n\t\tif(UI()->HotItem() == &sEnvelopeEditorID)\n\t\t{\n\t\t\t// do stuff\n\t\t\tif(pEnvelope)\n\t\t\t{\n\t\t\t\tif(UI()->MouseButtonClicked(1))\n\t\t\t\t{\n\t\t\t\t\t// add point\n\t\t\t\t\tint Time = (int)(((UI()->MouseX()-View.x)*TimeScale)*1000.0f);\n\t\t\t\t\t//float env_y = (UI()->MouseY()-view.y)/TimeScale;\n\t\t\t\t\tfloat aChannels[4];\n\t\t\t\t\tpEnvelope->Eval(Time, aChannels);\n\t\t\t\t\tpEnvelope->AddPoint(Time,\n\t\t\t\t\t\tf2fx(aChannels[0]), f2fx(aChannels[1]),\n\t\t\t\t\t\tf2fx(aChannels[2]), f2fx(aChannels[3]));\n\t\t\t\t\tm_Map.m_Modified = true;\n\t\t\t\t}\n\n\t\t\t\tm_ShowEnvelopePreview = 1;\n\t\t\t\tm_pTooltip = \"Press right mouse button to create a new point\";\n\t\t\t}\n\t\t}\n\n\t\tvec3 aColors[] = {vec3(1,0.2f,0.2f), vec3(0.2f,1,0.2f), vec3(0.2f,0.2f,1), vec3(1,1,0.2f)};\n\n\t\t// render lines\n\t\t{\n\t\t\tUI()->ClipEnable(&View);\n\t\t\tGraphics()->TextureClear();\n\t\t\tGraphics()->LinesBegin();\n\t\t\tfor(int c = 0; c < pEnvelope->m_Channels; c++)\n\t\t\t{\n\t\t\t\tif(s_ActiveChannels&(1<<c))\n\t\t\t\t\tGraphics()->SetColor(aColors[c].r,aColors[c].g,aColors[c].b,1);\n\t\t\t\telse\n\t\t\t\t\tGraphics()->SetColor(aColors[c].r*0.5f,aColors[c].g*0.5f,aColors[c].b*0.5f,1);\n\n\t\t\t\tfloat PrevX = 0;\n\t\t\t\tfloat aResults[4];\n\t\t\t\tpEnvelope->Eval(0.000001f, aResults);\n\t\t\t\tfloat PrevValue = aResults[c];\n\n\t\t\t\tint Steps = (int)((View.w/UI()->Screen()->w) * Graphics()->ScreenWidth());\n\t\t\t\tfor(int i = 1; i <= Steps; i++)\n\t\t\t\t{\n\t\t\t\t\tfloat a = i/(float)Steps;\n\t\t\t\t\tpEnvelope->Eval(a*EndTime, aResults);\n\t\t\t\t\tfloat v = aResults[c];\n\t\t\t\t\tv = (v-Bottom)/(Top-Bottom);\n\n\t\t\t\t\tIGraphics::CLineItem LineItem(View.x + PrevX*View.w, View.y+View.h - PrevValue*View.h, View.x + a*View.w, View.y+View.h - v*View.h);\n\t\t\t\t\tGraphics()->LinesDraw(&LineItem, 1);\n\t\t\t\t\tPrevX = a;\n\t\t\t\t\tPrevValue = v;\n\t\t\t\t}\n\t\t\t}\n\t\t\tGraphics()->LinesEnd();\n\t\t\tUI()->ClipDisable();\n\t\t}\n\n\t\t// render curve options\n\t\t{\n\t\t\tfor(int i = 0; i < pEnvelope->m_lPoints.size()-1; i++)\n\t\t\t{\n\t\t\t\tfloat t0 = pEnvelope->m_lPoints[i].m_Time/1000.0f/EndTime;\n\t\t\t\tfloat t1 = pEnvelope->m_lPoints[i+1].m_Time/1000.0f/EndTime;\n\n\t\t\t\t//dbg_msg(\"\", \"%f\", end_time);\n\n\t\t\t\tCUIRect v;\n\t\t\t\tv.x = CurveBar.x + (t0+(t1-t0)*0.5f) * CurveBar.w;\n\t\t\t\tv.y = CurveBar.y;\n\t\t\t\tv.h = CurveBar.h;\n\t\t\t\tv.w = CurveBar.h;\n\t\t\t\tv.x -= v.w/2;\n\t\t\t\tvoid *pID = &pEnvelope->m_lPoints[i].m_Curvetype;\n\t\t\t\tconst char *paTypeName[] = {\n\t\t\t\t\t\"N\", \"L\", \"S\", \"F\", \"M\"\n\t\t\t\t\t};\n\n\t\t\t\tif(DoButton_Editor(pID, paTypeName[pEnvelope->m_lPoints[i].m_Curvetype], 0, &v, 0, \"Switch curve type\"))\n\t\t\t\t\tpEnvelope->m_lPoints[i].m_Curvetype = (pEnvelope->m_lPoints[i].m_Curvetype+1)%NUM_CURVETYPES;\n\t\t\t}\n\t\t}\n\n\t\t// render colorbar\n\t\tif(ShowColorBar)\n\t\t{\n\t\t\tGraphics()->TextureClear();\n\t\t\tGraphics()->QuadsBegin();\n\t\t\tfor(int i = 0; i < pEnvelope->m_lPoints.size()-1; i++)\n\t\t\t{\n\t\t\t\tfloat r0 = fx2f(pEnvelope->m_lPoints[i].m_aValues[0]);\n\t\t\t\tfloat g0 = fx2f(pEnvelope->m_lPoints[i].m_aValues[1]);\n\t\t\t\tfloat b0 = fx2f(pEnvelope->m_lPoints[i].m_aValues[2]);\n\t\t\t\tfloat a0 = fx2f(pEnvelope->m_lPoints[i].m_aValues[3]);\n\t\t\t\tfloat r1 = fx2f(pEnvelope->m_lPoints[i+1].m_aValues[0]);\n\t\t\t\tfloat g1 = fx2f(pEnvelope->m_lPoints[i+1].m_aValues[1]);\n\t\t\t\tfloat b1 = fx2f(pEnvelope->m_lPoints[i+1].m_aValues[2]);\n\t\t\t\tfloat a1 = fx2f(pEnvelope->m_lPoints[i+1].m_aValues[3]);\n\n\t\t\t\tIGraphics::CColorVertex Array[4] = {IGraphics::CColorVertex(0, r0, g0, b0, a0),\n\t\t\t\t\t\t\t\t\t\t\t\t\tIGraphics::CColorVertex(1, r1, g1, b1, a1),\n\t\t\t\t\t\t\t\t\t\t\t\t\tIGraphics::CColorVertex(2, r1, g1, b1, a1),\n\t\t\t\t\t\t\t\t\t\t\t\t\tIGraphics::CColorVertex(3, r0, g0, b0, a0)};\n\t\t\t\tGraphics()->SetColorVertex(Array, 4);\n\n\t\t\t\tfloat x0 = pEnvelope->m_lPoints[i].m_Time/1000.0f/EndTime;\n//\t\t\t\tfloat y0 = (fx2f(envelope->points[i].values[c])-bottom)/(top-bottom);\n\t\t\t\tfloat x1 = pEnvelope->m_lPoints[i+1].m_Time/1000.0f/EndTime;\n\t\t\t\t//float y1 = (fx2f(envelope->points[i+1].values[c])-bottom)/(top-bottom);\n\t\t\t\tCUIRect v;\n\t\t\t\tv.x = ColorBar.x + x0*ColorBar.w;\n\t\t\t\tv.y = ColorBar.y;\n\t\t\t\tv.w = (x1-x0)*ColorBar.w;\n\t\t\t\tv.h = ColorBar.h;\n\n\t\t\t\tIGraphics::CQuadItem QuadItem(v.x, v.y, v.w, v.h);\n\t\t\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t\t\t}\n\t\t\tGraphics()->QuadsEnd();\n\t\t}\n\n\t\t// render handles\n\t\t{\n\t\t\tint CurrentValue = 0, CurrentTime = 0;\n\n\t\t\tGraphics()->TextureClear();\n\t\t\tGraphics()->QuadsBegin();\n\t\t\tfor(int c = 0; c < pEnvelope->m_Channels; c++)\n\t\t\t{\n\t\t\t\tif(!(s_ActiveChannels&(1<<c)))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tfor(int i = 0; i < pEnvelope->m_lPoints.size(); i++)\n\t\t\t\t{\n\t\t\t\t\tfloat x0 = pEnvelope->m_lPoints[i].m_Time/1000.0f/EndTime;\n\t\t\t\t\tfloat y0 = (fx2f(pEnvelope->m_lPoints[i].m_aValues[c])-Bottom)/(Top-Bottom);\n\t\t\t\t\tCUIRect Final;\n\t\t\t\t\tFinal.x = View.x + x0*View.w;\n\t\t\t\t\tFinal.y = View.y+View.h - y0*View.h;\n\t\t\t\t\tFinal.x -= 2.0f;\n\t\t\t\t\tFinal.y -= 2.0f;\n\t\t\t\t\tFinal.w = 4.0f;\n\t\t\t\t\tFinal.h = 4.0f;\n\n\t\t\t\t\tvoid *pID = &pEnvelope->m_lPoints[i].m_aValues[c];\n\n\t\t\t\t\tif(UI()->MouseInside(&Final))\n\t\t\t\t\t\tUI()->SetHotItem(pID);\n\n\t\t\t\t\tfloat ColorMod = 1.0f;\n\n\t\t\t\t\tif(UI()->ActiveItem() == pID)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(!UI()->MouseButton(0))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tm_SelectedQuadEnvelope = -1;\n\t\t\t\t\t\t\tm_SelectedEnvelopePoint = -1;\n\n\t\t\t\t\t\t\tUI()->SetActiveItem(0);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif(i != 0)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tif((Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)))\n\t\t\t\t\t\t\t\t\t\tpEnvelope->m_lPoints[i].m_Time += (int)((m_MouseDeltaX));\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\tpEnvelope->m_lPoints[i].m_Time += (int)((m_MouseDeltaX*TimeScale)*1000.0f);\n\t\t\t\t\t\t\t\t\tif(pEnvelope->m_lPoints[i].m_Time < pEnvelope->m_lPoints[i-1].m_Time)\n\t\t\t\t\t\t\t\t\t\tpEnvelope->m_lPoints[i].m_Time = pEnvelope->m_lPoints[i-1].m_Time + 1;\n\t\t\t\t\t\t\t\t\tif(i+1 != pEnvelope->m_lPoints.size() && pEnvelope->m_lPoints[i].m_Time > pEnvelope->m_lPoints[i+1].m_Time)\n\t\t\t\t\t\t\t\t\t\tpEnvelope->m_lPoints[i].m_Time = pEnvelope->m_lPoints[i+1].m_Time - 1;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif((Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)))\n\t\t\t\t\t\t\t\t\tpEnvelope->m_lPoints[i].m_aValues[c] -= f2fx(m_MouseDeltaY*0.001f);\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tpEnvelope->m_lPoints[i].m_aValues[c] -= f2fx(m_MouseDeltaY*ValueScale);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tm_SelectedQuadEnvelope = m_SelectedEnvelope;\n\t\t\t\t\t\t\tm_ShowEnvelopePreview = 1;\n\t\t\t\t\t\t\tm_SelectedEnvelopePoint = i;\n\t\t\t\t\t\t\tm_Map.m_Modified = true;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tColorMod = 100.0f;\n\t\t\t\t\t\tGraphics()->SetColor(1,1,1,1);\n\t\t\t\t\t}\n\t\t\t\t\telse if(UI()->HotItem() == pID)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(UI()->MouseButton(0))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSelection.clear();\n\t\t\t\t\t\t\tSelection.add(i);\n\t\t\t\t\t\t\tUI()->SetActiveItem(pID);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// remove point\n\t\t\t\t\t\tif(UI()->MouseButtonClicked(1))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpEnvelope->m_lPoints.remove_index(i);\n\t\t\t\t\t\t\tm_Map.m_Modified = true;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tm_ShowEnvelopePreview = 1;\n\t\t\t\t\t\tColorMod = 100.0f;\n\t\t\t\t\t\tGraphics()->SetColor(1,0.75f,0.75f,1);\n\t\t\t\t\t\tm_pTooltip = \"Left mouse to drag. Hold ctrl to be more precise. Hold shift to alter time point aswell. Right click to delete.\";\n\t\t\t\t\t}\n\n\t\t\t\t\tif(UI()->ActiveItem() == pID || UI()->HotItem() == pID)\n\t\t\t\t\t{\n\t\t\t\t\t\tCurrentTime = pEnvelope->m_lPoints[i].m_Time;\n\t\t\t\t\t\tCurrentValue = pEnvelope->m_lPoints[i].m_aValues[c];\n\t\t\t\t\t}\n\n\t\t\t\t\tif (m_SelectedQuadEnvelope == m_SelectedEnvelope && m_SelectedEnvelopePoint == i)\n\t\t\t\t\t\tGraphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);\n\t\t\t\t\telse\n\t\t\t\t\t\tGraphics()->SetColor(aColors[c].r*ColorMod, aColors[c].g*ColorMod, aColors[c].b*ColorMod, 1.0f);\n\t\t\t\t\tIGraphics::CQuadItem QuadItem(Final.x, Final.y, Final.w, Final.h);\n\t\t\t\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tGraphics()->QuadsEnd();\n\n\t\t\tchar aBuf[512];\n\t\t\tstr_format(aBuf, sizeof(aBuf),\"%.3f %.3f\", CurrentTime/1000.0f, fx2f(CurrentValue));\n\t\t\tUI()->DoLabel(&ToolBar, aBuf, 10.0f, 0, -1);\n\t\t}\n\t}\n}\n\nint CEditor::PopupMenuFile(CEditor *pEditor, CUIRect View)\n{\n\tstatic int s_NewMapButton = 0;\n\tstatic int s_SaveButton = 0;\n\tstatic int s_SaveAsButton = 0;\n\tstatic int s_OpenButton = 0;\n\tstatic int s_AppendButton = 0;\n\tstatic int s_ExitButton = 0;\n\n\tCUIRect Slot;\n\tView.HSplitTop(2.0f, &Slot, &View);\n\tView.HSplitTop(12.0f, &Slot, &View);\n\tif(pEditor->DoButton_MenuItem(&s_NewMapButton, \"New\", 0, &Slot, 0, \"Creates a new map\"))\n\t{\n\t\tif(pEditor->HasUnsavedData())\n\t\t{\n\t\t\tpEditor->m_PopupEventType = POPEVENT_NEW;\n\t\t\tpEditor->m_PopupEventActivated = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpEditor->Reset();\n\t\t\tpEditor->m_aFileName[0] = 0;\n\t\t}\n\t\treturn 1;\n\t}\n\n\tView.HSplitTop(10.0f, &Slot, &View);\n\tView.HSplitTop(12.0f, &Slot, &View);\n\tif(pEditor->DoButton_MenuItem(&s_OpenButton, \"Load\", 0, &Slot, 0, \"Opens a map for editing\"))\n\t{\n\t\tif(pEditor->HasUnsavedData())\n\t\t{\n\t\t\tpEditor->m_PopupEventType = POPEVENT_LOAD;\n\t\t\tpEditor->m_PopupEventActivated = true;\n\t\t}\n\t\telse\n\t\t\tpEditor->InvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_MAP, \"Load map\", \"Load\", \"maps\", \"\", pEditor->CallbackOpenMap, pEditor);\n\t\treturn 1;\n\t}\n\n\tView.HSplitTop(10.0f, &Slot, &View);\n\tView.HSplitTop(12.0f, &Slot, &View);\n\tif(pEditor->DoButton_MenuItem(&s_AppendButton, \"Append\", 0, &Slot, 0, \"Opens a map and adds everything from that map to the current one\"))\n\t{\n\t\tpEditor->InvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_MAP, \"Append map\", \"Append\", \"maps\", \"\", pEditor->CallbackAppendMap, pEditor);\n\t\treturn 1;\n\t}\n\n\tView.HSplitTop(10.0f, &Slot, &View);\n\tView.HSplitTop(12.0f, &Slot, &View);\n\tif(pEditor->DoButton_MenuItem(&s_SaveButton, \"Save\", 0, &Slot, 0, \"Saves the current map\"))\n\t{\n\t\tif(pEditor->m_aFileName[0] && pEditor->m_ValidSaveFilename)\n\t\t{\n\t\t\tstr_copy(pEditor->m_aFileSaveName, pEditor->m_aFileName, sizeof(pEditor->m_aFileSaveName));\n\t\t\tpEditor->m_PopupEventType = POPEVENT_SAVE;\n\t\t\tpEditor->m_PopupEventActivated = true;\n\t\t}\n\t\telse\n\t\t\tpEditor->InvokeFileDialog(IStorage::TYPE_SAVE, FILETYPE_MAP, \"Save map\", \"Save\", \"maps\", \"\", pEditor->CallbackSaveMap, pEditor);\n\t\treturn 1;\n\t}\n\n\tView.HSplitTop(2.0f, &Slot, &View);\n\tView.HSplitTop(12.0f, &Slot, &View);\n\tif(pEditor->DoButton_MenuItem(&s_SaveAsButton, \"Save As\", 0, &Slot, 0, \"Saves the current map under a new name\"))\n\t{\n\t\tpEditor->InvokeFileDialog(IStorage::TYPE_SAVE, FILETYPE_MAP, \"Save map\", \"Save\", \"maps\", \"\", pEditor->CallbackSaveMap, pEditor);\n\t\treturn 1;\n\t}\n\n\tView.HSplitTop(10.0f, &Slot, &View);\n\tView.HSplitTop(12.0f, &Slot, &View);\n\tif(pEditor->DoButton_MenuItem(&s_ExitButton, \"Exit\", 0, &Slot, 0, \"Exits from the editor\"))\n\t{\n\t\tif(pEditor->HasUnsavedData())\n\t\t{\n\t\t\tpEditor->m_PopupEventType = POPEVENT_EXIT;\n\t\t\tpEditor->m_PopupEventActivated = true;\n\t\t}\n\t\telse\n\t\t\tg_Config.m_ClEditor = 0;\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n\nvoid CEditor::RenderMenubar(CUIRect MenuBar)\n{\n\tstatic CUIRect s_File /*, view, help*/;\n\n\tMenuBar.VSplitLeft(60.0f, &s_File, &MenuBar);\n\tif(DoButton_Menu(&s_File, \"File\", 0, &s_File, 0, 0))\n\t\tUiInvokePopupMenu(&s_File, 1, s_File.x, s_File.y+s_File.h-1.0f, 120, 150, PopupMenuFile, this);\n\n\t/*\n\tmenubar.VSplitLeft(5.0f, 0, &menubar);\n\tmenubar.VSplitLeft(60.0f, &view, &menubar);\n\tif(do_editor_button(&view, \"View\", 0, &view, draw_editor_button_menu, 0, 0))\n\t\t(void)0;\n\n\tmenubar.VSplitLeft(5.0f, 0, &menubar);\n\tmenubar.VSplitLeft(60.0f, &help, &menubar);\n\tif(do_editor_button(&help, \"Help\", 0, &help, draw_editor_button_menu, 0, 0))\n\t\t(void)0;\n\t\t*/\n\n\tCUIRect Info;\n\tMenuBar.VSplitLeft(40.0f, 0, &MenuBar);\n\tMenuBar.VSplitLeft(MenuBar.w*0.75f, &MenuBar, &Info);\n\tchar aBuf[128];\n\tstr_format(aBuf, sizeof(aBuf), \"File: %s\", m_aFileName);\n\tUI()->DoLabel(&MenuBar, aBuf, 10.0f, -1, -1);\n\n\tstr_format(aBuf, sizeof(aBuf), \"Z: %i, A: %.1f, G: %i\", m_ZoomLevel, m_AnimateSpeed, m_GridFactor);\n\tUI()->DoLabel(&Info, aBuf, 10.0f, 1, -1);\n}\n\nvoid CEditor::Render()\n{\n\t// basic start\n\tGraphics()->Clear(1.0f, 0.0f, 1.0f);\n\tCUIRect View = *UI()->Screen();\n\tGraphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h);\n\n\tfloat Width = View.w;\n\tfloat Height = View.h;\n\n\t// reset tip\n\tm_pTooltip = 0;\n\n\tif(m_EditBoxActive)\n\t\t--m_EditBoxActive;\n\n\t// render checker\n\tRenderBackground(View, m_CheckerTexture, 32.0f, 1.0f);\n\n\tCUIRect MenuBar, CModeBar, ToolBar, StatusBar, EnvelopeEditor, ToolBox;\n\tm_ShowPicker = Input()->KeyPressed(KEY_SPACE) != 0 && m_Dialog == DIALOG_NONE;\n\n\tif(m_GuiActive)\n\t{\n\n\t\tView.HSplitTop(16.0f, &MenuBar, &View);\n\t\tView.HSplitTop(53.0f, &ToolBar, &View);\n\t\tView.VSplitLeft(100.0f, &ToolBox, &View);\n\t\tView.HSplitBottom(16.0f, &View, &StatusBar);\n\n\t\tif(m_ShowEnvelopeEditor && !m_ShowPicker)\n\t\t{\n\t\t\tfloat size = 125.0f;\n\t\t\tif(m_ShowEnvelopeEditor == 2)\n\t\t\t\tsize *= 2.0f;\n\t\t\telse if(m_ShowEnvelopeEditor == 3)\n\t\t\t\tsize *= 3.0f;\n\t\t\tView.HSplitBottom(size, &View, &EnvelopeEditor);\n\t\t}\n\t}\n\n\t//\ta little hack for now\n\tif(m_Mode == MODE_LAYERS)\n\t\tDoMapEditor(View, ToolBar);\n\n\t// do zooming\n\tif(Input()->KeyDown(KEY_KP_MINUS))\n\t\tm_ZoomLevel += 50;\n\tif(Input()->KeyDown(KEY_KP_PLUS))\n\t\tm_ZoomLevel -= 50;\n\tif(Input()->KeyDown(KEY_KP_MULTIPLY))\n\t{\n\t\tm_EditorOffsetX = 0;\n\t\tm_EditorOffsetY = 0;\n\t\tm_ZoomLevel = 100;\n\t}\n\tif(m_Dialog == DIALOG_NONE && UI()->MouseInside(&View))\n\t{\n\t\tif(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP))\n\t\t\tm_ZoomLevel -= 20;\n\n\t\tif(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN))\n\t\t\tm_ZoomLevel += 20;\n\t}\n\tm_ZoomLevel = clamp(m_ZoomLevel, 50, 2000);\n\tm_WorldZoom = m_ZoomLevel/100.0f;\n\n\tif(m_GuiActive)\n\t{\n\t\tfloat Brightness = 0.25f;\n\t\tRenderBackground(MenuBar, m_BackgroundTexture, 128.0f, Brightness*0);\n\t\tMenuBar.Margin(2.0f, &MenuBar);\n\n\t\tRenderBackground(ToolBox, m_BackgroundTexture, 128.0f, Brightness);\n\t\tToolBox.Margin(2.0f, &ToolBox);\n\n\t\tRenderBackground(ToolBar, m_BackgroundTexture, 128.0f, Brightness);\n\t\tToolBar.Margin(2.0f, &ToolBar);\n\t\tToolBar.VSplitLeft(100.0f, &CModeBar, &ToolBar);\n\n\t\tRenderBackground(StatusBar, m_BackgroundTexture, 128.0f, Brightness);\n\t\tStatusBar.Margin(2.0f, &StatusBar);\n\n\t\t// do the toolbar\n\t\tif(m_Mode == MODE_LAYERS)\n\t\t\tDoToolbar(ToolBar);\n\n\t\tif(m_ShowEnvelopeEditor)\n\t\t{\n\t\t\tRenderBackground(EnvelopeEditor, m_BackgroundTexture, 128.0f, Brightness);\n\t\t\tEnvelopeEditor.Margin(2.0f, &EnvelopeEditor);\n\t\t}\n\t}\n\n\n\tif(m_Mode == MODE_LAYERS)\n\t\tRenderLayers(ToolBox, ToolBar, View);\n\telse if(m_Mode == MODE_IMAGES)\n\t\tRenderImages(ToolBox, ToolBar, View);\n\n\tGraphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h);\n\n\tif(m_GuiActive)\n\t{\n\t\tRenderMenubar(MenuBar);\n\n\t\tRenderModebar(CModeBar);\n\t\tif(m_ShowEnvelopeEditor)\n\t\t\tRenderEnvelopeEditor(EnvelopeEditor);\n\t}\n\n\tif(m_Dialog == DIALOG_FILE)\n\t{\n\t\tstatic int s_NullUiTarget = 0;\n\t\tUI()->SetHotItem(&s_NullUiTarget);\n\t\tRenderFileDialog();\n\t}\n\n\tif(m_PopupEventActivated)\n\t{\n\t\tstatic int s_PopupID = 0;\n\t\tUiInvokePopupMenu(&s_PopupID, 0, Width/2.0f-200.0f, Height/2.0f-100.0f, 400.0f, 200.0f, PopupEvent);\n\t\tm_PopupEventActivated = false;\n\t\tm_PopupEventWasActivated = true;\n\t}\n\n\n\tUiDoPopupMenu();\n\n\tif(m_GuiActive)\n\t\tRenderStatusbar(StatusBar);\n\n\t//\n\tif(g_Config.m_EdShowkeys)\n\t{\n\t\tGraphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h);\n\t\tCTextCursor Cursor;\n\t\tTextRender()->SetCursor(&Cursor, View.x+10, View.y+View.h-24-10, 24.0f, TEXTFLAG_RENDER);\n\n\t\tint NKeys = 0;\n\t\tfor(int i = 0; i < KEY_LAST; i++)\n\t\t{\n\t\t\tif(Input()->KeyPressed(i))\n\t\t\t{\n\t\t\t\tif(NKeys)\n\t\t\t\t\tTextRender()->TextEx(&Cursor, \" + \", -1);\n\t\t\t\tTextRender()->TextEx(&Cursor, Input()->KeyName(i), -1);\n\t\t\t\tNKeys++;\n\t\t\t}\n\t\t}\n\t}\n\n\tif(m_ShowMousePointer)\n\t{\n\t\t// render butt ugly mouse cursor\n\t\tfloat mx = UI()->MouseX();\n\t\tfloat my = UI()->MouseY();\n\t\tGraphics()->TextureSet(m_CursorTexture);\n\t\tGraphics()->QuadsBegin();\n\t\tif(ms_pUiGotContext == UI()->HotItem())\n\t\t\tGraphics()->SetColor(1,0,0,1);\n\t\tIGraphics::CQuadItem QuadItem(mx,my, 16.0f, 16.0f);\n\t\tGraphics()->QuadsDrawTL(&QuadItem, 1);\n\t\tGraphics()->QuadsEnd();\n\t}\n}\n\nvoid CEditor::Reset(bool CreateDefault)\n{\n\tm_Map.Clean();\n\n\t// create default layers\n\tif(CreateDefault)\n\t\tm_Map.CreateDefault(m_EntitiesTexture);\n\n\t/*\n\t{\n\t}*/\n\n\tm_SelectedLayer = 0;\n\tm_SelectedGroup = 0;\n\tm_SelectedQuad = -1;\n\tm_SelectedPoints = 0;\n\tm_SelectedEnvelope = 0;\n\tm_SelectedImage = 0;\n\n\tm_WorldOffsetX = 0;\n\tm_WorldOffsetY = 0;\n\tm_EditorOffsetX = 0.0f;\n\tm_EditorOffsetY = 0.0f;\n\n\tm_WorldZoom = 1.0f;\n\tm_ZoomLevel = 200;\n\n\tm_MouseDeltaX = 0;\n\tm_MouseDeltaY = 0;\n\tm_MouseDeltaWx = 0;\n\tm_MouseDeltaWy = 0;\n\n\tm_Map.m_Modified = false;\n\n\tm_ShowEnvelopePreview = 0;\n}\n\nint CEditor::GetLineDistance()\n{\n\tint LineDistance = 512;\n\n\tif(m_ZoomLevel <= 100)\n\t\tLineDistance = 16;\n\telse if(m_ZoomLevel <= 250)\n\t\tLineDistance = 32;\n\telse if(m_ZoomLevel <= 450)\n\t\tLineDistance = 64;\n\telse if(m_ZoomLevel <= 850)\n\t\tLineDistance = 128;\n\telse if(m_ZoomLevel <= 1550)\n\t\tLineDistance = 256;\n\n\treturn LineDistance;\n}\n\nvoid CEditorMap::DeleteEnvelope(int Index)\n{\n\tif(Index < 0 || Index >= m_lEnvelopes.size())\n\t\treturn;\n\n\tm_Modified = true;\n\n\t// fix links between envelopes and quads\n\tfor(int i = 0; i < m_lGroups.size(); ++i)\n\t\tfor(int j = 0; j < m_lGroups[i]->m_lLayers.size(); ++j)\n\t\t\tif(m_lGroups[i]->m_lLayers[j]->m_Type == LAYERTYPE_QUADS)\n\t\t\t{\n\t\t\t\tCLayerQuads *pLayer = static_cast<CLayerQuads *>(m_lGroups[i]->m_lLayers[j]);\n\t\t\t\tfor(int k = 0; k < pLayer->m_lQuads.size(); ++k)\n\t\t\t\t{\n\t\t\t\t\tif(pLayer->m_lQuads[k].m_PosEnv == Index)\n\t\t\t\t\t\tpLayer->m_lQuads[k].m_PosEnv = -1;\n\t\t\t\t\telse if(pLayer->m_lQuads[k].m_PosEnv > Index)\n\t\t\t\t\t\tpLayer->m_lQuads[k].m_PosEnv--;\n\t\t\t\t\tif(pLayer->m_lQuads[k].m_ColorEnv == Index)\n\t\t\t\t\t\tpLayer->m_lQuads[k].m_ColorEnv = -1;\n\t\t\t\t\telse if(pLayer->m_lQuads[k].m_ColorEnv > Index)\n\t\t\t\t\t\tpLayer->m_lQuads[k].m_ColorEnv--;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(m_lGroups[i]->m_lLayers[j]->m_Type == LAYERTYPE_TILES)\n\t\t\t{\n\t\t\t\tCLayerTiles *pLayer = static_cast<CLayerTiles *>(m_lGroups[i]->m_lLayers[j]);\n\t\t\t\tif(pLayer->m_ColorEnv == Index)\n\t\t\t\t\tpLayer->m_ColorEnv = -1;\n\t\t\t\tif(pLayer->m_ColorEnv > Index)\n\t\t\t\t\tpLayer->m_ColorEnv--;\n\t\t\t}\n\n\tm_lEnvelopes.remove_index(Index);\n}\n\nvoid CEditorMap::MakeGameLayer(CLayer *pLayer)\n{\n\tm_pGameLayer = (CLayerGame *)pLayer;\n\tm_pGameLayer->m_pEditor = m_pEditor;\n\tm_pGameLayer->m_Texture = m_pEditor->m_EntitiesTexture;\n}\n\nvoid CEditorMap::MakeGameGroup(CLayerGroup *pGroup)\n{\n\tm_pGameGroup = pGroup;\n\tm_pGameGroup->m_GameGroup = true;\n\tstr_copy(m_pGameGroup->m_aName, \"Game\", sizeof(m_pGameGroup->m_aName));\n}\n\n\n\nvoid CEditorMap::Clean()\n{\n\tm_lGroups.delete_all();\n\tm_lEnvelopes.delete_all();\n\tm_lImages.delete_all();\n\n\tm_MapInfo.Reset();\n\n\tm_pGameLayer = 0x0;\n\tm_pGameGroup = 0x0;\n\n\tm_Modified = false;\n}\n\nvoid CEditorMap::CreateDefault(IGraphics::CTextureHandle EntitiesTexture)\n{\n\t// add background\n\tCLayerGroup *pGroup = NewGroup();\n\tpGroup->m_ParallaxX = 0;\n\tpGroup->m_ParallaxY = 0;\n\tCLayerQuads *pLayer = new CLayerQuads;\n\tpLayer->m_pEditor = m_pEditor;\n\tCQuad *pQuad = pLayer->NewQuad();\n\tconst int Width = 800000;\n\tconst int Height = 600000;\n\tpQuad->m_aPoints[0].x = pQuad->m_aPoints[2].x = -Width;\n\tpQuad->m_aPoints[1].x = pQuad->m_aPoints[3].x = Width;\n\tpQuad->m_aPoints[0].y = pQuad->m_aPoints[1].y = -Height;\n\tpQuad->m_aPoints[2].y = pQuad->m_aPoints[3].y = Height;\n\tpQuad->m_aPoints[4].x = pQuad->m_aPoints[4].y = 0;\n\tpQuad->m_aColors[0].r = pQuad->m_aColors[1].r = 94;\n\tpQuad->m_aColors[0].g = pQuad->m_aColors[1].g = 132;\n\tpQuad->m_aColors[0].b = pQuad->m_aColors[1].b = 174;\n\tpQuad->m_aColors[2].r = pQuad->m_aColors[3].r = 204;\n\tpQuad->m_aColors[2].g = pQuad->m_aColors[3].g = 232;\n\tpQuad->m_aColors[2].b = pQuad->m_aColors[3].b = 255;\n\tpGroup->AddLayer(pLayer);\n\n\t// add game layer\n\tMakeGameGroup(NewGroup());\n\tMakeGameLayer(new CLayerGame(50, 50));\n\tm_pGameGroup->AddLayer(m_pGameLayer);\n}\n\nvoid CEditor::Init()\n{\n\tm_pInput = Kernel()->RequestInterface<IInput>();\n\tm_pClient = Kernel()->RequestInterface<IClient>();\n\tm_pConsole = Kernel()->RequestInterface<IConsole>();\n\tm_pGraphics = Kernel()->RequestInterface<IGraphics>();\n\tm_pTextRender = Kernel()->RequestInterface<ITextRender>();\n\tm_pStorage = Kernel()->RequestInterface<IStorage>();\n\tm_RenderTools.m_pGraphics = m_pGraphics;\n\tm_RenderTools.m_pUI = &m_UI;\n\tm_UI.SetGraphics(m_pGraphics, m_pTextRender);\n\tm_Map.m_pEditor = this;\n\n\tm_CheckerTexture = Graphics()->LoadTexture(\"editor/checker.png\", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0);\n\tm_BackgroundTexture = Graphics()->LoadTexture(\"editor/background.png\", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0);\n\tm_CursorTexture = Graphics()->LoadTexture(\"editor/cursor.png\", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0);\n\tm_EntitiesTexture = Graphics()->LoadTexture(\"editor/entities.png\", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0);\n\n\tm_TilesetPicker.m_pEditor = this;\n\tm_TilesetPicker.MakePalette();\n\tm_TilesetPicker.m_Readonly = true;\n\n\tm_Brush.m_pMap = &m_Map;\n\n\tReset();\n\tm_Map.m_Modified = false;\n}\n\nvoid CEditor::DoMapBorder()\n{\n\tCLayerTiles *pT = (CLayerTiles *)GetSelectedLayerType(0, LAYERTYPE_TILES);\n\n\tfor(int i = 0; i < pT->m_Width*2; ++i)\n\t\tpT->m_pTiles[i].m_Index = 1;\n\n\tfor(int i = 0; i < pT->m_Width*pT->m_Height; ++i)\n\t{\n\t\tif(i%pT->m_Width < 2 || i%pT->m_Width > pT->m_Width-3)\n\t\t\tpT->m_pTiles[i].m_Index = 1;\n\t}\n\n\tfor(int i = (pT->m_Width*(pT->m_Height-2)); i < pT->m_Width*pT->m_Height; ++i)\n\t\tpT->m_pTiles[i].m_Index = 1;\n}\n\nvoid CEditor::UpdateAndRender()\n{\n\tstatic float s_MouseX = 0.0f;\n\tstatic float s_MouseY = 0.0f;\n\n\tif(m_Animate)\n\t\tm_AnimateTime = (time_get()-m_AnimateStart)/(float)time_freq();\n\telse\n\t\tm_AnimateTime = 0;\n\tms_pUiGotContext = 0;\n\n\t// handle mouse movement\n\tfloat mx, my, Mwx, Mwy;\n\tfloat rx, ry;\n\t{\n\t\tInput()->MouseRelative(&rx, &ry);\n\t\tUI()->ConvertMouseMove(&rx, &ry);\n\t\tm_MouseDeltaX = rx;\n\t\tm_MouseDeltaY = ry;\n\n\t\tif(!m_LockMouse)\n\t\t{\n\t\t\ts_MouseX += rx;\n\t\t\ts_MouseY += ry;\n\t\t}\n\n\t\ts_MouseX = clamp(s_MouseX, 0.0f, UI()->Screen()->w);\n\t\ts_MouseY = clamp(s_MouseY, 0.0f, UI()->Screen()->h);\n\n\t\t// update the ui\n\t\tmx = s_MouseX;\n\t\tmy = s_MouseY;\n\t\tMwx = 0;\n\t\tMwy = 0;\n\n\t\t// fix correct world x and y\n\t\tCLayerGroup *g = GetSelectedGroup();\n\t\tif(g)\n\t\t{\n\t\t\tfloat aPoints[4];\n\t\t\tg->Mapping(aPoints);\n\n\t\t\tfloat WorldWidth = aPoints[2]-aPoints[0];\n\t\t\tfloat WorldHeight = aPoints[3]-aPoints[1];\n\n\t\t\tMwx = aPoints[0] + WorldWidth * (s_MouseX/UI()->Screen()->w);\n\t\t\tMwy = aPoints[1] + WorldHeight * (s_MouseY/UI()->Screen()->h);\n\t\t\tm_MouseDeltaWx = m_MouseDeltaX*(WorldWidth / UI()->Screen()->w);\n\t\t\tm_MouseDeltaWy = m_MouseDeltaY*(WorldHeight / UI()->Screen()->h);\n\t\t}\n\n\t\tint Buttons = 0;\n\t\tif(Input()->KeyPressed(KEY_MOUSE_1)) Buttons |= 1;\n\t\tif(Input()->KeyPressed(KEY_MOUSE_2)) Buttons |= 2;\n\t\tif(Input()->KeyPressed(KEY_MOUSE_3)) Buttons |= 4;\n\n\t\tUI()->Update(mx,my,Mwx,Mwy,Buttons);\n\t}\n\n\t// toggle gui\n\tif(Input()->KeyDown(KEY_TAB))\n\t\tm_GuiActive = !m_GuiActive;\n\n\tif(Input()->KeyDown(KEY_F10))\n\t\tm_ShowMousePointer = false;\n\n\tRender();\n\n\tif(Input()->KeyDown(KEY_F10))\n\t{\n\t\tGraphics()->TakeScreenshot(0);\n\t\tm_ShowMousePointer = true;\n\t}\n\n\tInput()->ClearEvents();\n}\n\nIEditor *CreateEditor() { return new CEditor; }\n"
  },
  {
    "path": "src/game/editor/editor.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_EDITOR_EDITOR_H\n#define GAME_EDITOR_EDITOR_H\n\n#include <math.h>\n\n#include <base/math.h>\n#include <base/system.h>\n\n#include <base/tl/algorithm.h>\n#include <base/tl/array.h>\n#include <base/tl/sorted_array.h>\n#include <base/tl/string.h>\n\n#include <game/client/ui.h>\n#include <game/mapitems.h>\n#include <game/client/render.h>\n\n#include <engine/shared/config.h>\n#include <engine/shared/datafile.h>\n#include <engine/editor.h>\n#include <engine/graphics.h>\n\n#include \"auto_map.h\"\n\ntypedef void (*INDEX_MODIFY_FUNC)(int *pIndex);\n\n//CRenderTools m_RenderTools;\n\n// CEditor SPECIFIC\nenum\n{\n\tMODE_LAYERS=0,\n\tMODE_IMAGES,\n\n\tDIALOG_NONE=0,\n\tDIALOG_FILE,\n};\n\nstruct CEntity\n{\n\tCPoint m_Position;\n\tint m_Type;\n};\n\nclass CEnvelope\n{\npublic:\n\tint m_Channels;\n\tarray<CEnvPoint> m_lPoints;\n\tchar m_aName[32];\n\tfloat m_Bottom, m_Top;\n\tbool m_Synchronized;\n\n\tCEnvelope(int Chan)\n\t{\n\t\tm_Channels = Chan;\n\t\tm_aName[0] = 0;\n\t\tm_Bottom = 0;\n\t\tm_Top = 0;\n\t\tm_Synchronized = true;\n\t}\n\n\tvoid Resort()\n\t{\n\t\tsort(m_lPoints.all());\n\t\tFindTopBottom(0xf);\n\t}\n\n\tvoid FindTopBottom(int ChannelMask)\n\t{\n\t\tm_Top = -1000000000.0f;\n\t\tm_Bottom = 1000000000.0f;\n\t\tfor(int i = 0; i < m_lPoints.size(); i++)\n\t\t{\n\t\t\tfor(int c = 0; c < m_Channels; c++)\n\t\t\t{\n\t\t\t\tif(ChannelMask&(1<<c))\n\t\t\t\t{\n\t\t\t\t\tfloat v = fx2f(m_lPoints[i].m_aValues[c]);\n\t\t\t\t\tif(v > m_Top) m_Top = v;\n\t\t\t\t\tif(v < m_Bottom) m_Bottom = v;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tint Eval(float Time, float *pResult)\n\t{\n\t\tCRenderTools::RenderEvalEnvelope(m_lPoints.base_ptr(), m_lPoints.size(), m_Channels, Time, pResult);\n\t\treturn m_Channels;\n\t}\n\n\tvoid AddPoint(int Time, int v0, int v1=0, int v2=0, int v3=0)\n\t{\n\t\tCEnvPoint p;\n\t\tp.m_Time = Time;\n\t\tp.m_aValues[0] = v0;\n\t\tp.m_aValues[1] = v1;\n\t\tp.m_aValues[2] = v2;\n\t\tp.m_aValues[3] = v3;\n\t\tp.m_Curvetype = CURVETYPE_LINEAR;\n\t\tm_lPoints.add(p);\n\t\tResort();\n\t}\n\n\tfloat EndTime()\n\t{\n\t\tif(m_lPoints.size())\n\t\t\treturn m_lPoints[m_lPoints.size()-1].m_Time*(1.0f/1000.0f);\n\t\treturn 0;\n\t}\n};\n\n\nclass CLayer;\nclass CLayerGroup;\nclass CEditorMap;\n\nclass CLayer\n{\npublic:\n\tclass CEditor *m_pEditor;\n\tclass IGraphics *Graphics();\n\tclass ITextRender *TextRender();\n\n\tCLayer()\n\t{\n\t\tm_Type = LAYERTYPE_INVALID;\n\t\tstr_copy(m_aName, \"(invalid)\", sizeof(m_aName));\n\t\tm_Visible = true;\n\t\tm_Readonly = false;\n\t\tm_SaveToMap = true;\n\t\tm_Flags = 0;\n\t\tm_pEditor = 0;\n\t}\n\n\tvirtual ~CLayer()\n\t{\n\t}\n\n\n\tvirtual void BrushSelecting(CUIRect Rect) {}\n\tvirtual int BrushGrab(CLayerGroup *pBrush, CUIRect Rect) { return 0; }\n\tvirtual void FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) {}\n\tvirtual void BrushDraw(CLayer *pBrush, float x, float y) {}\n\tvirtual void BrushPlace(CLayer *pBrush, float x, float y) {}\n\tvirtual void BrushFlipX() {}\n\tvirtual void BrushFlipY() {}\n\tvirtual void BrushRotate(float Amount) {}\n\n\tvirtual void Render() {}\n\tvirtual int RenderProperties(CUIRect *pToolbox) { return 0; }\n\n\tvirtual void ModifyImageIndex(INDEX_MODIFY_FUNC pfnFunc) {}\n\tvirtual void ModifyEnvelopeIndex(INDEX_MODIFY_FUNC pfnFunc) {}\n\n\tvirtual void GetSize(float *w, float *h) { *w = 0; *h = 0;}\n\n\tchar m_aName[12];\n\tint m_Type;\n\tint m_Flags;\n\n\tbool m_Readonly;\n\tbool m_Visible;\n\tbool m_SaveToMap;\n};\n\nclass CLayerGroup\n{\npublic:\n\tclass CEditorMap *m_pMap;\n\n\tarray<CLayer*> m_lLayers;\n\n\tint m_OffsetX;\n\tint m_OffsetY;\n\n\tint m_ParallaxX;\n\tint m_ParallaxY;\n\n\tint m_UseClipping;\n\tint m_ClipX;\n\tint m_ClipY;\n\tint m_ClipW;\n\tint m_ClipH;\n\n\tchar m_aName[12];\n\tbool m_GameGroup;\n\tbool m_Visible;\n\tbool m_SaveToMap;\n\tbool m_Collapse;\n\n\tCLayerGroup();\n\t~CLayerGroup();\n\n\tvoid Convert(CUIRect *pRect);\n\tvoid Render();\n\tvoid MapScreen();\n\tvoid Mapping(float *pPoints);\n\n\tvoid GetSize(float *w, float *h);\n\n\tvoid DeleteLayer(int Index);\n\tint SwapLayers(int Index0, int Index1);\n\n\tbool IsEmpty() const\n\t{\n\t\treturn m_lLayers.size() == 0;\n\t}\n\n\tvoid Clear()\n\t{\n\t\tm_lLayers.delete_all();\n\t}\n\n\tvoid AddLayer(CLayer *l);\n\n\tvoid ModifyImageIndex(INDEX_MODIFY_FUNC Func)\n\t{\n\t\tfor(int i = 0; i < m_lLayers.size(); i++)\n\t\t\tm_lLayers[i]->ModifyImageIndex(Func);\n\t}\n\n\tvoid ModifyEnvelopeIndex(INDEX_MODIFY_FUNC Func)\n\t{\n\t\tfor(int i = 0; i < m_lLayers.size(); i++)\n\t\t\tm_lLayers[i]->ModifyEnvelopeIndex(Func);\n\t}\n};\n\nclass CEditorImage : public CImageInfo\n{\npublic:\n\tCEditor *m_pEditor;\n\n\tCEditorImage(CEditor *pEditor)\n\t{\n\t\tm_pEditor = pEditor;\n\t\tm_aName[0] = 0;\n\t\tm_External = 0;\n\t\tm_Width = 0;\n\t\tm_Height = 0;\n\t\tm_pData = 0;\n\t\tm_Format = 0;\n\t\tm_pAutoMapper = 0;\n\t}\n\n\t~CEditorImage();\n\n\tvoid AnalyseTileFlags();\n\tvoid LoadAutoMapper();\n\n\tIGraphics::CTextureHandle m_Texture;\n\tint m_External;\n\tchar m_aName[128];\n\tunsigned char m_aTileFlags[256];\n\tclass IAutoMapper *m_pAutoMapper;\n};\n\nclass CEditorMap\n{\n\tvoid MakeGameGroup(CLayerGroup *pGroup);\n\tvoid MakeGameLayer(CLayer *pLayer);\npublic:\n\tCEditor *m_pEditor;\n\tbool m_Modified;\n\n\tCEditorMap()\n\t{\n\t\tClean();\n\t}\n\n\tarray<CLayerGroup*> m_lGroups;\n\tarray<CEditorImage*> m_lImages;\n\tarray<CEnvelope*> m_lEnvelopes;\n\n\tclass CMapInfo\n\t{\n\tpublic:\n\t\tchar m_aAuthorTmp[32];\n\t\tchar m_aVersionTmp[16];\n\t\tchar m_aCreditsTmp[128];\n\t\tchar m_aLicenseTmp[32];\n\n\t\tchar m_aAuthor[32];\n\t\tchar m_aVersion[16];\n\t\tchar m_aCredits[128];\n\t\tchar m_aLicense[32];\n\n\t\tvoid Reset()\n\t\t{\n\t\t\tm_aAuthorTmp[0] = 0;\n\t\t\tm_aVersionTmp[0] = 0;\n\t\t\tm_aCreditsTmp[0] = 0;\n\t\t\tm_aLicenseTmp[0] = 0;\n\n\t\t\tm_aAuthor[0] = 0;\n\t\t\tm_aVersion[0] = 0;\n\t\t\tm_aCredits[0] = 0;\n\t\t\tm_aLicense[0] = 0;\n\t\t}\n\t};\n\tCMapInfo m_MapInfo;\n\n\tclass CLayerGame *m_pGameLayer;\n\tCLayerGroup *m_pGameGroup;\n\n\tCEnvelope *NewEnvelope(int Channels)\n\t{\n\t\tm_Modified = true;\n\t\tCEnvelope *e = new CEnvelope(Channels);\n\t\tm_lEnvelopes.add(e);\n\t\treturn e;\n\t}\n\n\tvoid DeleteEnvelope(int Index);\n\n\tCLayerGroup *NewGroup()\n\t{\n\t\tm_Modified = true;\n\t\tCLayerGroup *g = new CLayerGroup;\n\t\tg->m_pMap = this;\n\t\tm_lGroups.add(g);\n\t\treturn g;\n\t}\n\n\tint SwapGroups(int Index0, int Index1)\n\t{\n\t\tif(Index0 < 0 || Index0 >= m_lGroups.size()) return Index0;\n\t\tif(Index1 < 0 || Index1 >= m_lGroups.size()) return Index0;\n\t\tif(Index0 == Index1) return Index0;\n\t\tm_Modified = true;\n\t\tswap(m_lGroups[Index0], m_lGroups[Index1]);\n\t\treturn Index1;\n\t}\n\n\tvoid DeleteGroup(int Index)\n\t{\n\t\tif(Index < 0 || Index >= m_lGroups.size()) return;\n\t\tm_Modified = true;\n\t\tdelete m_lGroups[Index];\n\t\tm_lGroups.remove_index(Index);\n\t}\n\n\tvoid ModifyImageIndex(INDEX_MODIFY_FUNC pfnFunc)\n\t{\n\t\tm_Modified = true;\n\t\tfor(int i = 0; i < m_lGroups.size(); i++)\n\t\t\tm_lGroups[i]->ModifyImageIndex(pfnFunc);\n\t}\n\n\tvoid ModifyEnvelopeIndex(INDEX_MODIFY_FUNC pfnFunc)\n\t{\n\t\tm_Modified = true;\n\t\tfor(int i = 0; i < m_lGroups.size(); i++)\n\t\t\tm_lGroups[i]->ModifyEnvelopeIndex(pfnFunc);\n\t}\n\n\tvoid Clean();\n\tvoid CreateDefault(IGraphics::CTextureHandle EntitiesTexture);\n\n\t// io\n\tint Save(class IStorage *pStorage, const char *pFilename);\n\tint Load(class IStorage *pStorage, const char *pFilename, int StorageType);\n};\n\n\nstruct CProperty\n{\n\tconst char *m_pName;\n\tint m_Value;\n\tint m_Type;\n\tint m_Min;\n\tint m_Max;\n};\n\nenum\n{\n\tPROPTYPE_NULL=0,\n\tPROPTYPE_BOOL,\n\tPROPTYPE_INT_STEP,\n\tPROPTYPE_INT_SCROLL,\n\tPROPTYPE_COLOR,\n\tPROPTYPE_IMAGE,\n\tPROPTYPE_ENVELOPE,\n\tPROPTYPE_SHIFT,\n};\n\ntypedef struct\n{\n\tint x, y;\n\tint w, h;\n} RECTi;\n\nclass CLayerTiles : public CLayer\n{\npublic:\n\tCLayerTiles(int w, int h);\n\t~CLayerTiles();\n\n\tvoid Resize(int NewW, int NewH);\n\tvoid Shift(int Direction);\n\n\tvoid MakePalette();\n\tvirtual void Render();\n\n\tint ConvertX(float x) const;\n\tint ConvertY(float y) const;\n\tvoid Convert(CUIRect Rect, RECTi *pOut);\n\tvoid Snap(CUIRect *pRect);\n\tvoid Clamp(RECTi *pRect);\n\n\tvirtual void BrushSelecting(CUIRect Rect);\n\tvirtual int BrushGrab(CLayerGroup *pBrush, CUIRect Rect);\n\tvirtual void FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect);\n\tvirtual void BrushDraw(CLayer *pBrush, float wx, float wy);\n\tvirtual void BrushFlipX();\n\tvirtual void BrushFlipY();\n\tvirtual void BrushRotate(float Amount);\n\n\tvirtual void ShowInfo();\n\tvirtual int RenderProperties(CUIRect *pToolbox);\n\n\tvirtual void ModifyImageIndex(INDEX_MODIFY_FUNC pfnFunc);\n\tvirtual void ModifyEnvelopeIndex(INDEX_MODIFY_FUNC pfnFunc);\n\n\tvoid PrepareForSave();\n\n\tvoid GetSize(float *w, float *h) { *w = m_Width*32.0f; *h = m_Height*32.0f; }\n\n\tIGraphics::CTextureHandle m_Texture;\n\tint m_Game;\n\tint m_Image;\n\tint m_Width;\n\tint m_Height;\n\tCColor m_Color;\n\tint m_ColorEnv;\n\tint m_ColorEnvOffset;\n\tCTile *m_pTiles;\n\tint m_SelectedRuleSet;\n\tint m_SelectedAmount;\n};\n\nclass CLayerQuads : public CLayer\n{\npublic:\n\tCLayerQuads();\n\t~CLayerQuads();\n\n\tvirtual void Render();\n\tCQuad *NewQuad();\n\n\tvirtual void BrushSelecting(CUIRect Rect);\n\tvirtual int BrushGrab(CLayerGroup *pBrush, CUIRect Rect);\n\tvirtual void BrushPlace(CLayer *pBrush, float wx, float wy);\n\tvirtual void BrushFlipX();\n\tvirtual void BrushFlipY();\n\tvirtual void BrushRotate(float Amount);\n\n\tvirtual int RenderProperties(CUIRect *pToolbox);\n\n\tvirtual void ModifyImageIndex(INDEX_MODIFY_FUNC pfnFunc);\n\tvirtual void ModifyEnvelopeIndex(INDEX_MODIFY_FUNC pfnFunc);\n\n\tvoid GetSize(float *w, float *h);\n\n\tint m_Image;\n\tarray<CQuad> m_lQuads;\n};\n\nclass CLayerGame : public CLayerTiles\n{\npublic:\n\tCLayerGame(int w, int h);\n\t~CLayerGame();\n\n\tvirtual int RenderProperties(CUIRect *pToolbox);\n};\n\nclass CEditor : public IEditor\n{\n\tclass IInput *m_pInput;\n\tclass IClient *m_pClient;\n\tclass IConsole *m_pConsole;\n\tclass IGraphics *m_pGraphics;\n\tclass ITextRender *m_pTextRender;\n\tclass IStorage *m_pStorage;\n\tCRenderTools m_RenderTools;\n\tCUI m_UI;\npublic:\n\tclass IInput *Input() { return m_pInput; };\n\tclass IClient *Client() { return m_pClient; };\n\tclass IConsole *Console() { return m_pConsole; };\n\tclass IGraphics *Graphics() { return m_pGraphics; };\n\tclass ITextRender *TextRender() { return m_pTextRender; };\n\tclass IStorage *Storage() { return m_pStorage; };\n\tCUI *UI() { return &m_UI; }\n\tCRenderTools *RenderTools() { return &m_RenderTools; }\n\n\tCEditor() : m_TilesetPicker(16, 16)\n\t{\n\t\tm_pInput = 0;\n\t\tm_pClient = 0;\n\t\tm_pGraphics = 0;\n\t\tm_pTextRender = 0;\n\n\t\tm_Mode = MODE_LAYERS;\n\t\tm_Dialog = 0;\n\t\tm_EditBoxActive = 0;\n\t\tm_pTooltip = 0;\n\n\t\tm_GridActive = false;\n\t\tm_GridFactor = 1;\n\n\t\tm_aFileName[0] = 0;\n\t\tm_aFileSaveName[0] = 0;\n\t\tm_ValidSaveFilename = false;\n\n\t\tm_PopupEventActivated = false;\n\t\tm_PopupEventWasActivated = false;\n\n\t\tm_FileDialogStorageType = 0;\n\t\tm_pFileDialogTitle = 0;\n\t\tm_pFileDialogButtonText = 0;\n\t\tm_pFileDialogUser = 0;\n\t\tm_aFileDialogFileName[0] = 0;\n\t\tm_aFileDialogCurrentFolder[0] = 0;\n\t\tm_aFileDialogCurrentLink[0] = 0;\n\t\tm_pFileDialogPath = m_aFileDialogCurrentFolder;\n\t\tm_aFileDialogActivate = false;\n\t\tm_FileDialogScrollValue = 0.0f;\n\t\tm_FilesSelectedIndex = -1;\n\t\tm_FilesStartAt = 0;\n\t\tm_FilesCur = 0;\n\t\tm_FilesStopAt = 999;\n\n\t\tm_WorldOffsetX = 0;\n\t\tm_WorldOffsetY = 0;\n\t\tm_EditorOffsetX = 0.0f;\n\t\tm_EditorOffsetY = 0.0f;\n\n\t\tm_WorldZoom = 1.0f;\n\t\tm_ZoomLevel = 200;\n\t\tm_LockMouse = false;\n\t\tm_ShowMousePointer = true;\n\t\tm_MouseDeltaX = 0;\n\t\tm_MouseDeltaY = 0;\n\t\tm_MouseDeltaWx = 0;\n\t\tm_MouseDeltaWy = 0;\n\n\t\tm_GuiActive = true;\n\t\tm_ProofBorders = false;\n\n\t\tm_ShowTileInfo = false;\n\t\tm_ShowDetail = true;\n\t\tm_Animate = false;\n\t\tm_AnimateStart = 0;\n\t\tm_AnimateTime = 0;\n\t\tm_AnimateSpeed = 1;\n\n\t\tm_ShowEnvelopeEditor = 0;\n\n\t\tm_ShowEnvelopePreview = 0;\n\t\tm_SelectedQuadEnvelope = -1;\n\t\tm_SelectedEnvelopePoint = -1;\n\n\t\tms_pUiGotContext = 0;\n\t}\n\n\tvirtual void Init();\n\tvirtual void UpdateAndRender();\n\tvirtual bool HasUnsavedData() { return m_Map.m_Modified; }\n\n\tvoid FilelistPopulate(int StorageType);\n\tvoid InvokeFileDialog(int StorageType, int FileType, const char *pTitle, const char *pButtonText,\n\t\tconst char *pBasepath, const char *pDefaultName,\n\t\tvoid (*pfnFunc)(const char *pFilename, int StorageType, void *pUser), void *pUser);\n\n\tvoid Reset(bool CreateDefault=true);\n\tint Save(const char *pFilename);\n\tint Load(const char *pFilename, int StorageType);\n\tint Append(const char *pFilename, int StorageType);\n\tvoid Render();\n\n\tCQuad *GetSelectedQuad();\n\tCLayer *GetSelectedLayerType(int Index, int Type);\n\tCLayer *GetSelectedLayer(int Index);\n\tCLayerGroup *GetSelectedGroup();\n\n\tint DoProperties(CUIRect *pToolbox, CProperty *pProps, int *pIDs, int *pNewVal);\n\n\tint m_Mode;\n\tint m_Dialog;\n\tint m_EditBoxActive;\n\tconst char *m_pTooltip;\n\n\tbool m_GridActive;\n\tint m_GridFactor;\n\n\tchar m_aFileName[512];\n\tchar m_aFileSaveName[512];\n\tbool m_ValidSaveFilename;\n\n\tenum\n\t{\n\t\tPOPEVENT_EXIT=0,\n\t\tPOPEVENT_LOAD,\n\t\tPOPEVENT_NEW,\n\t\tPOPEVENT_SAVE,\n\t};\n\n\tint m_PopupEventType;\n\tint m_PopupEventActivated;\n\tint m_PopupEventWasActivated;\n\n\tenum\n\t{\n\t\tFILETYPE_MAP,\n\t\tFILETYPE_IMG,\n\n\t\tMAX_PATH_LENGTH = 512\n\t};\n\n\tint m_FileDialogStorageType;\n\tconst char *m_pFileDialogTitle;\n\tconst char *m_pFileDialogButtonText;\n\tvoid (*m_pfnFileDialogFunc)(const char *pFileName, int StorageType, void *pUser);\n\tvoid *m_pFileDialogUser;\n\tchar m_aFileDialogFileName[MAX_PATH_LENGTH];\n\tchar m_aFileDialogCurrentFolder[MAX_PATH_LENGTH];\n\tchar m_aFileDialogCurrentLink[MAX_PATH_LENGTH];\n\tchar *m_pFileDialogPath;\n\tbool m_aFileDialogActivate;\n\tint m_FileDialogFileType;\n\tfloat m_FileDialogScrollValue;\n\tint m_FilesSelectedIndex;\n\tchar m_FileDialogNewFolderName[64];\n\tchar m_FileDialogErrString[64];\n\n\tstruct CFilelistItem\n\t{\n\t\tchar m_aFilename[128];\n\t\tchar m_aName[128];\n\t\tbool m_IsDir;\n\t\tbool m_IsLink;\n\t\tint m_StorageType;\n\n\t\tbool operator<(const CFilelistItem &Other) { return !str_comp(m_aFilename, \"..\") ? true : !str_comp(Other.m_aFilename, \"..\") ? false :\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tm_IsDir && !Other.m_IsDir ? true : !m_IsDir && Other.m_IsDir ? false :\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr_comp_filenames(m_aFilename, Other.m_aFilename) < 0; }\n\t};\n\tsorted_array<CFilelistItem> m_FileList;\n\tint m_FilesStartAt;\n\tint m_FilesCur;\n\tint m_FilesStopAt;\n\n\tfloat m_WorldOffsetX;\n\tfloat m_WorldOffsetY;\n\tfloat m_EditorOffsetX;\n\tfloat m_EditorOffsetY;\n\tfloat m_WorldZoom;\n\tint m_ZoomLevel;\n\tbool m_LockMouse;\n\tbool m_ShowMousePointer;\n\tbool m_GuiActive;\n\tbool m_ProofBorders;\n\tfloat m_MouseDeltaX;\n\tfloat m_MouseDeltaY;\n\tfloat m_MouseDeltaWx;\n\tfloat m_MouseDeltaWy;\n\n\tbool m_ShowTileInfo;\n\tbool m_ShowDetail;\n\tbool m_Animate;\n\tint64 m_AnimateStart;\n\tfloat m_AnimateTime;\n\tfloat m_AnimateSpeed;\n\n\tint m_ShowEnvelopeEditor;\n\tint m_ShowEnvelopePreview; //Values: 0-Off|1-Selected Envelope|2-All\n\tbool m_ShowPicker;\n\n\tint m_SelectedLayer;\n\tint m_SelectedGroup;\n\tint m_SelectedQuad;\n\tint m_SelectedPoints;\n\tint m_SelectedEnvelope;\n\tint m_SelectedEnvelopePoint;\n    int m_SelectedQuadEnvelope;\n\tint m_SelectedImage;\n\n\tIGraphics::CTextureHandle m_CheckerTexture;\n\tIGraphics::CTextureHandle m_BackgroundTexture;\n\tIGraphics::CTextureHandle m_CursorTexture;\n\tIGraphics::CTextureHandle m_EntitiesTexture;\n\n\tCLayerGroup m_Brush;\n\tCLayerTiles m_TilesetPicker;\n\n\tstatic const void *ms_pUiGotContext;\n\n\tCEditorMap m_Map;\n\n\tstatic void EnvelopeEval(float TimeOffset, int Env, float *pChannels, void *pUser);\n\n\tvoid DoMapBorder();\n\tint DoButton_Editor_Common(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip);\n\tint DoButton_Editor(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip);\n\n\tint DoButton_Tab(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip);\n\tint DoButton_Ex(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip, int Corners, float FontSize=10.0f);\n\tint DoButton_ButtonDec(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip);\n\tint DoButton_ButtonInc(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip);\n\n\tint DoButton_File(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip);\n\n\tint DoButton_Menu(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip);\n\tint DoButton_MenuItem(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags=0, const char *pToolTip=0);\n\n\tint DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned StrSize, float FontSize, float *Offset, bool Hidden=false, int Corners=CUI::CORNER_ALL);\n\n\tvoid RenderBackground(CUIRect View, IGraphics::CTextureHandle Texture, float Size, float Brightness);\n\n\tvoid RenderGrid(CLayerGroup *pGroup);\n\n\tvoid UiInvokePopupMenu(void *pID, int Flags, float X, float Y, float W, float H, int (*pfnFunc)(CEditor *pEditor, CUIRect Rect), void *pExtra=0);\n\tvoid UiDoPopupMenu();\n\n\tint UiDoValueSelector(void *pID, CUIRect *pRect, const char *pLabel, int Current, int Min, int Max, int Step, float Scale, const char *pToolTip);\n\n\tstatic int PopupGroup(CEditor *pEditor, CUIRect View);\n\tstatic int PopupLayer(CEditor *pEditor, CUIRect View);\n\tstatic int PopupQuad(CEditor *pEditor, CUIRect View);\n\tstatic int PopupPoint(CEditor *pEditor, CUIRect View);\n\tstatic int PopupNewFolder(CEditor *pEditor, CUIRect View);\n\tstatic int PopupMapInfo(CEditor *pEditor, CUIRect View);\n\tstatic int PopupEvent(CEditor *pEditor, CUIRect View);\n\tstatic int PopupSelectImage(CEditor *pEditor, CUIRect View);\n\tstatic int PopupSelectGametileOp(CEditor *pEditor, CUIRect View);\n\tstatic int PopupImage(CEditor *pEditor, CUIRect View);\n\tstatic int PopupMenuFile(CEditor *pEditor, CUIRect View);\n\tstatic int PopupSelectConfigAutoMap(CEditor *pEditor, CUIRect View);\n\n\tstatic int PopupSelectDoodadRuleSet(CEditor *pEditor, CUIRect View);\n\tstatic int PopupDoodadAutoMap(CEditor *pEditor, CUIRect View);\n\n\tstatic void CallbackOpenMap(const char *pFileName, int StorageType, void *pUser);\n\tstatic void CallbackAppendMap(const char *pFileName, int StorageType, void *pUser);\n\tstatic void CallbackSaveMap(const char *pFileName, int StorageType, void *pUser);\n\n\tvoid PopupSelectImageInvoke(int Current, float x, float y);\n\tint PopupSelectImageResult();\n\n\tvoid PopupSelectGametileOpInvoke(float x, float y);\n\tint PopupSelectGameTileOpResult();\n\n\tvoid PopupSelectConfigAutoMapInvoke(float x, float y);\n\tbool PopupAutoMapProceedOrder();\n\n\tvec4 ButtonColorMul(const void *pID);\n\n\tvoid DoQuadEnvelopes(const array<CQuad> &m_lQuads, IGraphics::CTextureHandle Texture);\n\tvoid DoQuadEnvPoint(const CQuad *pQuad, int QIndex, int pIndex);\n\tvoid DoQuadPoint(CQuad *pQuad, int QuadIndex, int v);\n\n\tvoid DoMapEditor(CUIRect View, CUIRect Toolbar);\n\tvoid DoToolbar(CUIRect Toolbar);\n\tvoid DoQuad(CQuad *pQuad, int Index);\n\tfloat UiDoScrollbarV(const void *pID, const CUIRect *pRect, float Current);\n\tvec4 GetButtonColor(const void *pID, int Checked);\n\n\tstatic void ReplaceImage(const char *pFilename, int StorageType, void *pUser);\n\tstatic void AddImage(const char *pFilename, int StorageType, void *pUser);\n\n\tvoid RenderImages(CUIRect Toolbox, CUIRect Toolbar, CUIRect View);\n\tvoid RenderLayers(CUIRect Toolbox, CUIRect Toolbar, CUIRect View);\n\tvoid RenderModebar(CUIRect View);\n\tvoid RenderStatusbar(CUIRect View);\n\tvoid RenderEnvelopeEditor(CUIRect View);\n\n\tvoid RenderMenubar(CUIRect Menubar);\n\tvoid RenderFileDialog();\n\n\tvoid AddFileDialogEntry(int Index, CUIRect *pView);\n\tvoid SortImages();\n\tstatic void ExtractName(const char *pFileName, char *pName, int BufferSize)\n\t{\n\t\tconst char *pExtractedName = pFileName;\n\t\tconst char *pEnd = 0;\n\t\tfor(; *pFileName; ++pFileName)\n\t\t{\n\t\t\tif(*pFileName == '/' || *pFileName == '\\\\')\n\t\t\t\tpExtractedName = pFileName+1;\n\t\t\telse if(*pFileName == '.')\n\t\t\t\tpEnd = pFileName;\n\t\t}\n\n\t\tint Length = pEnd > pExtractedName ? min(BufferSize, (int)(pEnd-pExtractedName+1)) : BufferSize;\n\t\tstr_copy(pName, pExtractedName, Length);\n\t}\n\n\tint GetLineDistance();\n};\n\n// make sure to inline this function\ninline class IGraphics *CLayer::Graphics() { return m_pEditor->Graphics(); }\ninline class ITextRender *CLayer::TextRender() { return m_pEditor->TextRender(); }\n\n#endif\n"
  },
  {
    "path": "src/game/editor/io.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/client.h>\n#include <engine/console.h>\n#include <engine/graphics.h>\n#include <engine/serverbrowser.h>\n#include <engine/storage.h>\n#include <game/gamecore.h>\n#include \"editor.h\"\n\ntemplate<typename T>\nstatic int MakeVersion(int i, const T &v)\n{ return (i<<16)+sizeof(T); }\n\n// backwards compatiblity\n/*\nvoid editor_load_old(DATAFILE *df, MAP *map)\n{\n\tclass mapres_image\n\t{\n\tpublic:\n\t\tint width;\n\t\tint height;\n\t\tint image_data;\n\t};\n\n\tstruct mapres_tilemap\n\t{\n\t\tint image;\n\t\tint width;\n\t\tint height;\n\t\tint x, y;\n\t\tint scale;\n\t\tint data;\n\t\tint main;\n\t};\n\n\tstruct mapres_entity\n\t{\n\t\tint x, y;\n\t\tint data[1];\n\t};\n\n\tstruct mapres_spawnpoint\n\t{\n\t\tint x, y;\n\t};\n\n\tstruct mapres_item\n\t{\n\t\tint x, y;\n\t\tint type;\n\t};\n\n\tstruct mapres_flagstand\n\t{\n\t\tint x, y;\n\t};\n\n\tenum\n\t{\n\t\tMAPRES_ENTS_START=1,\n\t\tMAPRES_SPAWNPOINT=1,\n\t\tMAPRES_ITEM=2,\n\t\tMAPRES_SPAWNPOINT_RED=3,\n\t\tMAPRES_SPAWNPOINT_BLUE=4,\n\t\tMAPRES_FLAGSTAND_RED=5,\n\t\tMAPRES_FLAGSTAND_BLUE=6,\n\t\tMAPRES_ENTS_END,\n\n\t\tITEM_NULL=0,\n\t\tITEM_WEAPON_GUN=0x00010001,\n\t\tITEM_WEAPON_SHOTGUN=0x00010002,\n\t\tITEM_WEAPON_ROCKET=0x00010003,\n\t\tITEM_WEAPON_SNIPER=0x00010004,\n\t\tITEM_WEAPON_HAMMER=0x00010005,\n\t\tITEM_HEALTH =0x00020001,\n\t\tITEM_ARMOR=0x00030001,\n\t\tITEM_NINJA=0x00040001,\n\t};\n\n\tenum\n\t{\n\t\tMAPRES_REGISTERED=0x8000,\n\t\tMAPRES_IMAGE=0x8001,\n\t\tMAPRES_TILEMAP=0x8002,\n\t\tMAPRES_COLLISIONMAP=0x8003,\n\t\tMAPRES_TEMP_THEME=0x8fff,\n\t};\n\n\t// load tilemaps\n\tint game_width = 0;\n\tint game_height = 0;\n\t{\n\t\tint start, num;\n\t\tdatafile_get_type(df, MAPRES_TILEMAP, &start, &num);\n\t\tfor(int t = 0; t < num; t++)\n\t\t{\n\t\t\tmapres_tilemap *tmap = (mapres_tilemap *)datafile_get_item(df, start+t,0,0);\n\n\t\t\tCLayerTiles *l = new CLayerTiles(tmap->width, tmap->height);\n\n\t\t\tif(tmap->main)\n\t\t\t{\n\t\t\t\t// move game layer to correct position\n\t\t\t\tfor(int i = 0; i < map->groups[0]->layers.len()-1; i++)\n\t\t\t\t{\n\t\t\t\t\tif(map->groups[0]->layers[i] == pEditor->map.game_layer)\n\t\t\t\t\t\tmap->groups[0]->swap_layers(i, i+1);\n\t\t\t\t}\n\n\t\t\t\tgame_width = tmap->width;\n\t\t\t\tgame_height = tmap->height;\n\t\t\t}\n\n\t\t\t// add new layer\n\t\t\tmap->groups[0]->add_layer(l);\n\n\t\t\t// process the data\n\t\t\tunsigned char *src_data = (unsigned char *)datafile_get_data(df, tmap->data);\n\t\t\tCTile *dst_data = l->tiles;\n\n\t\t\tfor(int y = 0; y < tmap->height; y++)\n\t\t\t\tfor(int x = 0; x < tmap->width; x++, dst_data++, src_data+=2)\n\t\t\t\t{\n\t\t\t\t\tdst_data->index = src_data[0];\n\t\t\t\t\tdst_data->flags = src_data[1];\n\t\t\t\t}\n\n\t\t\tl->image = tmap->image;\n\t\t}\n\t}\n\n\t// load images\n\t{\n\t\tint start, count;\n\t\tdatafile_get_type(df, MAPRES_IMAGE, &start, &count);\n\t\tfor(int i = 0; i < count; i++)\n\t\t{\n\t\t\tmapres_image *imgres = (mapres_image *)datafile_get_item(df, start+i, 0, 0);\n\t\t\tvoid *data = datafile_get_data(df, imgres->image_data);\n\n\t\t\tEDITOR_IMAGE *img = new EDITOR_IMAGE;\n\t\t\timg->width = imgres->width;\n\t\t\timg->height = imgres->height;\n\t\t\timg->format = CImageInfo::FORMAT_RGBA;\n\n\t\t\t// copy image data\n\t\t\timg->data = mem_alloc(img->width*img->height*4, 1);\n\t\t\tmem_copy(img->data, data, img->width*img->height*4);\n\t\t\timg->tex_id = Graphics()->LoadTextureRaw(img->width, img->height, img->format, img->data, CImageInfo::FORMAT_AUTO, 0);\n\t\t\tmap->images.add(img);\n\n\t\t\t// unload image\n\t\t\tdatafile_unload_data(df, imgres->image_data);\n\t\t}\n\t}\n\n\t// load entities\n\t{\n\t\tCLayerGame *g = map->game_layer;\n\t\tg->resize(game_width, game_height);\n\t\tfor(int t = MAPRES_ENTS_START; t < MAPRES_ENTS_END; t++)\n\t\t{\n\t\t\t// fetch entities of this class\n\t\t\tint start, num;\n\t\t\tdatafile_get_type(df, t, &start, &num);\n\n\n\t\t\tfor(int i = 0; i < num; i++)\n\t\t\t{\n\t\t\t\tmapres_entity *e = (mapres_entity *)datafile_get_item(df, start+i,0,0);\n\t\t\t\tint x = e->x/32;\n\t\t\t\tint y = e->y/32;\n\t\t\t\tint id = -1;\n\n\t\t\t\tif(t == MAPRES_SPAWNPOINT) id = ENTITY_SPAWN;\n\t\t\t\telse if(t == MAPRES_SPAWNPOINT_RED) id = ENTITY_SPAWN_RED;\n\t\t\t\telse if(t == MAPRES_SPAWNPOINT_BLUE) id = ENTITY_SPAWN_BLUE;\n\t\t\t\telse if(t == MAPRES_FLAGSTAND_RED) id = ENTITY_FLAGSTAND_RED;\n\t\t\t\telse if(t == MAPRES_FLAGSTAND_BLUE) id = ENTITY_FLAGSTAND_BLUE;\n\t\t\t\telse if(t == MAPRES_ITEM)\n\t\t\t\t{\n\t\t\t\t\tif(e->data[0] == ITEM_WEAPON_SHOTGUN) id = ENTITY_WEAPON_SHOTGUN;\n\t\t\t\t\telse if(e->data[0] == ITEM_WEAPON_ROCKET) id = ENTITY_WEAPON_GRENADE;\n\t\t\t\t\telse if(e->data[0] == ITEM_NINJA) id = ENTITY_POWERUP_NINJA;\n\t\t\t\t\telse if(e->data[0] == ITEM_ARMOR) id = ENTITY_ARMOR_1;\n\t\t\t\t\telse if(e->data[0] == ITEM_HEALTH) id = ENTITY_HEALTH_1;\n\t\t\t\t}\n\n\t\t\t\tif(id > 0 && x >= 0 && x < g->width && y >= 0 && y < g->height)\n\t\t\t\t\tg->tiles[y*g->width+x].index = id+ENTITY_OFFSET;\n\t\t\t}\n\t\t}\n\t}\n}*/\n\nint CEditor::Save(const char *pFilename)\n{\n\treturn m_Map.Save(Kernel()->RequestInterface<IStorage>(), pFilename);\n}\n\nint CEditorMap::Save(class IStorage *pStorage, const char *pFileName)\n{\n\tchar aBuf[256];\n\tstr_format(aBuf, sizeof(aBuf), \"saving to '%s'...\", pFileName);\n\tm_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"editor\", aBuf);\n\tCDataFileWriter df;\n\tif(!df.Open(pStorage, pFileName))\n\t{\n\t\tstr_format(aBuf, sizeof(aBuf), \"failed to open file '%s'...\", pFileName);\n\t\tm_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"editor\", aBuf);\n\t\treturn 0;\n\t}\n\n\t// save version\n\t{\n\t\tCMapItemVersion Item;\n\t\tItem.m_Version = 1;\n\t\tdf.AddItem(MAPITEMTYPE_VERSION, 0, sizeof(Item), &Item);\n\t}\n\n\t// save map info\n\t{\n\t\tCMapItemInfo Item;\n\t\tItem.m_Version = 1;\n\n\t\tif(m_MapInfo.m_aAuthor[0])\n\t\t\tItem.m_Author = df.AddData(str_length(m_MapInfo.m_aAuthor)+1, m_MapInfo.m_aAuthor);\n\t\telse\n\t\t\tItem.m_Author = -1;\n\t\tif(m_MapInfo.m_aVersion[0])\n\t\t\tItem.m_MapVersion = df.AddData(str_length(m_MapInfo.m_aVersion)+1, m_MapInfo.m_aVersion);\n\t\telse\n\t\t\tItem.m_MapVersion = -1;\n\t\tif(m_MapInfo.m_aCredits[0])\n\t\t\tItem.m_Credits = df.AddData(str_length(m_MapInfo.m_aCredits)+1, m_MapInfo.m_aCredits);\n\t\telse\n\t\t\tItem.m_Credits = -1;\n\t\tif(m_MapInfo.m_aLicense[0])\n\t\t\tItem.m_License = df.AddData(str_length(m_MapInfo.m_aLicense)+1, m_MapInfo.m_aLicense);\n\t\telse\n\t\t\tItem.m_License = -1;\n\n\t\tdf.AddItem(MAPITEMTYPE_INFO, 0, sizeof(Item), &Item);\n\t}\n\n\t// save images\n\tfor(int i = 0; i < m_lImages.size(); i++)\n\t{\n\t\tCEditorImage *pImg = m_lImages[i];\n\n\t\t// analyse the image for when saving (should be done when we load the image)\n\t\t// TODO!\n\t\tpImg->AnalyseTileFlags();\n\n\t\tCMapItemImage Item;\n\t\tItem.m_Version = CMapItemImage::CURRENT_VERSION;\n\n\t\tItem.m_Width = pImg->m_Width;\n\t\tItem.m_Height = pImg->m_Height;\n\t\tItem.m_External = pImg->m_External;\n\t\tItem.m_ImageName = df.AddData(str_length(pImg->m_aName)+1, pImg->m_aName);\n\t\tif(pImg->m_External)\n\t\t\tItem.m_ImageData = -1;\n\t\telse\n\t\t{\n\t\t\tint PixelSize = pImg->m_Format == CImageInfo::FORMAT_RGB ? 3 : 4;\n\t\t\tItem.m_ImageData = df.AddData(Item.m_Width*Item.m_Height*PixelSize, pImg->m_pData);\n\t\t}\n\t\tItem.m_Format = pImg->m_Format;\n\t\tdf.AddItem(MAPITEMTYPE_IMAGE, i, sizeof(Item), &Item);\n\t}\n\n\t// save layers\n\tint LayerCount = 0, GroupCount = 0;\n\tfor(int g = 0; g < m_lGroups.size(); g++)\n\t{\n\t\tCLayerGroup *pGroup = m_lGroups[g];\n\t\tif(!pGroup->m_SaveToMap)\n\t\t\tcontinue;\n\n\t\tCMapItemGroup GItem;\n\t\tGItem.m_Version = CMapItemGroup::CURRENT_VERSION;\n\n\t\tGItem.m_ParallaxX = pGroup->m_ParallaxX;\n\t\tGItem.m_ParallaxY = pGroup->m_ParallaxY;\n\t\tGItem.m_OffsetX = pGroup->m_OffsetX;\n\t\tGItem.m_OffsetY = pGroup->m_OffsetY;\n\t\tGItem.m_UseClipping = pGroup->m_UseClipping;\n\t\tGItem.m_ClipX = pGroup->m_ClipX;\n\t\tGItem.m_ClipY = pGroup->m_ClipY;\n\t\tGItem.m_ClipW = pGroup->m_ClipW;\n\t\tGItem.m_ClipH = pGroup->m_ClipH;\n\t\tGItem.m_StartLayer = LayerCount;\n\t\tGItem.m_NumLayers = 0;\n\n\t\t// save group name\n\t\tStrToInts(GItem.m_aName, sizeof(GItem.m_aName)/sizeof(int), pGroup->m_aName);\n\n\t\tfor(int l = 0; l < pGroup->m_lLayers.size(); l++)\n\t\t{\n\t\t\tif(!pGroup->m_lLayers[l]->m_SaveToMap)\n\t\t\t\tcontinue;\n\n\t\t\tif(pGroup->m_lLayers[l]->m_Type == LAYERTYPE_TILES)\n\t\t\t{\n\t\t\t\tm_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"editor\", \"saving tiles layer\");\n\t\t\t\tCLayerTiles *pLayer = (CLayerTiles *)pGroup->m_lLayers[l];\n\t\t\t\tpLayer->PrepareForSave();\n\n\t\t\t\tCMapItemLayerTilemap Item;\n\t\t\t\tItem.m_Version = 3;\n\n\t\t\t\tItem.m_Layer.m_Flags = pLayer->m_Flags;\n\t\t\t\tItem.m_Layer.m_Type = pLayer->m_Type;\n\n\t\t\t\tItem.m_Color = pLayer->m_Color;\n\t\t\t\tItem.m_ColorEnv = pLayer->m_ColorEnv;\n\t\t\t\tItem.m_ColorEnvOffset = pLayer->m_ColorEnvOffset;\n\n\t\t\t\tItem.m_Width = pLayer->m_Width;\n\t\t\t\tItem.m_Height = pLayer->m_Height;\n\t\t\t\tItem.m_Flags = pLayer->m_Game ? TILESLAYERFLAG_GAME : 0;\n\t\t\t\tItem.m_Image = pLayer->m_Image;\n\t\t\t\tItem.m_Data = df.AddData(pLayer->m_Width*pLayer->m_Height*sizeof(CTile), pLayer->m_pTiles);\n\n\t\t\t\t// save layer name\n\t\t\t\tStrToInts(Item.m_aName, sizeof(Item.m_aName)/sizeof(int), pLayer->m_aName);\n\n\t\t\t\tdf.AddItem(MAPITEMTYPE_LAYER, LayerCount, sizeof(Item), &Item);\n\n\t\t\t\tGItem.m_NumLayers++;\n\t\t\t\tLayerCount++;\n\t\t\t}\n\t\t\telse if(pGroup->m_lLayers[l]->m_Type == LAYERTYPE_QUADS)\n\t\t\t{\n\t\t\t\tm_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"editor\", \"saving quads layer\");\n\t\t\t\tCLayerQuads *pLayer = (CLayerQuads *)pGroup->m_lLayers[l];\n\t\t\t\tif(pLayer->m_lQuads.size())\n\t\t\t\t{\n\t\t\t\t\tCMapItemLayerQuads Item;\n\t\t\t\t\tItem.m_Version = 2;\n\t\t\t\t\tItem.m_Layer.m_Flags = pLayer->m_Flags;\n\t\t\t\t\tItem.m_Layer.m_Type = pLayer->m_Type;\n\t\t\t\t\tItem.m_Image = pLayer->m_Image;\n\n\t\t\t\t\t// add the data\n\t\t\t\t\tItem.m_NumQuads = pLayer->m_lQuads.size();\n\t\t\t\t\tItem.m_Data = df.AddDataSwapped(pLayer->m_lQuads.size()*sizeof(CQuad), pLayer->m_lQuads.base_ptr());\n\n\t\t\t\t\t// save layer name\n\t\t\t\t\tStrToInts(Item.m_aName, sizeof(Item.m_aName)/sizeof(int), pLayer->m_aName);\n\n\t\t\t\t\tdf.AddItem(MAPITEMTYPE_LAYER, LayerCount, sizeof(Item), &Item);\n\n\t\t\t\t\t// clean up\n\t\t\t\t\t//mem_free(quads);\n\n\t\t\t\t\tGItem.m_NumLayers++;\n\t\t\t\t\tLayerCount++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdf.AddItem(MAPITEMTYPE_GROUP, GroupCount++, sizeof(GItem), &GItem);\n\t}\n\n\t// save envelopes\n\tint PointCount = 0;\n\tfor(int e = 0; e < m_lEnvelopes.size(); e++)\n\t{\n\t\tCMapItemEnvelope Item;\n\t\tItem.m_Version = CMapItemEnvelope::CURRENT_VERSION;\n\t\tItem.m_Channels = m_lEnvelopes[e]->m_Channels;\n\t\tItem.m_StartPoint = PointCount;\n\t\tItem.m_NumPoints = m_lEnvelopes[e]->m_lPoints.size();\n\t\tItem.m_Synchronized = m_lEnvelopes[e]->m_Synchronized;\n\t\tStrToInts(Item.m_aName, sizeof(Item.m_aName)/sizeof(int), m_lEnvelopes[e]->m_aName);\n\n\t\tdf.AddItem(MAPITEMTYPE_ENVELOPE, e, sizeof(Item), &Item);\n\t\tPointCount += Item.m_NumPoints;\n\t}\n\n\t// save points\n\tint TotalSize = sizeof(CEnvPoint) * PointCount;\n\tCEnvPoint *pPoints = (CEnvPoint *)mem_alloc(TotalSize, 1);\n\tPointCount = 0;\n\n\tfor(int e = 0; e < m_lEnvelopes.size(); e++)\n\t{\n\t\tint Count = m_lEnvelopes[e]->m_lPoints.size();\n\t\tmem_copy(&pPoints[PointCount], m_lEnvelopes[e]->m_lPoints.base_ptr(), sizeof(CEnvPoint)*Count);\n\t\tPointCount += Count;\n\t}\n\n\tdf.AddItem(MAPITEMTYPE_ENVPOINTS, 0, TotalSize, pPoints);\n\tmem_free(pPoints);\n\n\t// finish the data file\n\tdf.Finish();\n\tm_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, \"editor\", \"saving done\");\n\n\t// send rcon.. if we can\n\tif(m_pEditor->Client()->RconAuthed())\n\t{\n\t\tCServerInfo CurrentServerInfo;\n\t\tm_pEditor->Client()->GetServerInfo(&CurrentServerInfo);\n\t\tchar aMapName[128];\n\t\tm_pEditor->ExtractName(pFileName, aMapName, sizeof(aMapName));\n\t\tif(!str_comp(aMapName, CurrentServerInfo.m_aMap))\n\t\t\tm_pEditor->Client()->Rcon(\"reload\");\n\t}\n\n\treturn 1;\n}\n\nint CEditor::Load(const char *pFileName, int StorageType)\n{\n\tReset();\n\treturn m_Map.Load(Kernel()->RequestInterface<IStorage>(), pFileName, StorageType);\n}\n\nint CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int StorageType)\n{\n\tCDataFileReader DataFile;\n\t//DATAFILE *df = datafile_load(filename);\n\tif(!DataFile.Open(pStorage, pFileName, StorageType))\n\t\treturn 0;\n\n\tClean();\n\n\t// check version\n\tCMapItemVersion *pItem = (CMapItemVersion *)DataFile.FindItem(MAPITEMTYPE_VERSION, 0);\n\tif(!pItem)\n\t{\n\t\t// import old map\n\t\t/*MAP old_mapstuff;\n\t\teditor->reset();\n\t\teditor_load_old(df, this);\n\t\t*/\n\t\treturn 0;\n\t}\n\telse if(pItem->m_Version == CMapItemVersion::CURRENT_VERSION)\n\t{\n\t\t//editor.reset(false);\n\n\t\t// load map info\n\t\t{\n\t\t\tCMapItemInfo *pItem = (CMapItemInfo *)DataFile.FindItem(MAPITEMTYPE_INFO, 0);\n\t\t\tif(pItem && pItem->m_Version == 1)\n\t\t\t{\n\t\t\t\tif(pItem->m_Author > -1)\n\t\t\t\t\tstr_copy(m_MapInfo.m_aAuthor, (char *)DataFile.GetData(pItem->m_Author), sizeof(m_MapInfo.m_aAuthor));\n\t\t\t\tif(pItem->m_MapVersion > -1)\n\t\t\t\t\tstr_copy(m_MapInfo.m_aVersion, (char *)DataFile.GetData(pItem->m_MapVersion), sizeof(m_MapInfo.m_aVersion));\n\t\t\t\tif(pItem->m_Credits > -1)\n\t\t\t\t\tstr_copy(m_MapInfo.m_aCredits, (char *)DataFile.GetData(pItem->m_Credits), sizeof(m_MapInfo.m_aCredits));\n\t\t\t\tif(pItem->m_License > -1)\n\t\t\t\t\tstr_copy(m_MapInfo.m_aLicense, (char *)DataFile.GetData(pItem->m_License), sizeof(m_MapInfo.m_aLicense));\n\t\t\t}\n\t\t}\n\n\t\t// load images\n\t\t{\n\t\t\tint Start, Num;\n\t\t\tDataFile.GetType( MAPITEMTYPE_IMAGE, &Start, &Num);\n\t\t\tfor(int i = 0; i < Num; i++)\n\t\t\t{\n\t\t\t\tCMapItemImage *pItem = (CMapItemImage *)DataFile.GetItem(Start+i, 0, 0);\n\t\t\t\tchar *pName = (char *)DataFile.GetData(pItem->m_ImageName);\n\n\t\t\t\t// copy base info\n\t\t\t\tCEditorImage *pImg = new CEditorImage(m_pEditor);\n\t\t\t\tpImg->m_External = pItem->m_External;\n\n\t\t\t\tif(pItem->m_External || (pItem->m_Version > 1 && pItem->m_Format != CImageInfo::FORMAT_RGB && pItem->m_Format != CImageInfo::FORMAT_RGBA))\n\t\t\t\t{\n\t\t\t\t\tchar aBuf[256];\n\t\t\t\t\tstr_format(aBuf, sizeof(aBuf),\"mapres/%s.png\", pName);\n\n\t\t\t\t\t// load external\n\t\t\t\t\tCEditorImage ImgInfo(m_pEditor);\n\t\t\t\t\tif(m_pEditor->Graphics()->LoadPNG(&ImgInfo, aBuf, IStorage::TYPE_ALL))\n\t\t\t\t\t{\n\t\t\t\t\t\t*pImg = ImgInfo;\n\t\t\t\t\t\tpImg->m_Texture = m_pEditor->Graphics()->LoadTextureRaw(ImgInfo.m_Width, ImgInfo.m_Height, ImgInfo.m_Format, ImgInfo.m_pData, CImageInfo::FORMAT_AUTO, 0);\n\t\t\t\t\t\tImgInfo.m_pData = 0;\n\t\t\t\t\t\tpImg->m_External = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tpImg->m_Width = pItem->m_Width;\n\t\t\t\t\tpImg->m_Height = pItem->m_Height;\n\t\t\t\t\tpImg->m_Format = pItem->m_Version == 1 ? CImageInfo::FORMAT_RGBA : pItem->m_Format;\n\t\t\t\t\tint PixelSize = pImg->m_Format == CImageInfo::FORMAT_RGB ? 3 : 4;\n\n\t\t\t\t\t// copy image data\n\t\t\t\t\tvoid *pData = DataFile.GetData(pItem->m_ImageData);\n\t\t\t\t\tpImg->m_pData = mem_alloc(pImg->m_Width*pImg->m_Height*PixelSize, 1);\n\t\t\t\t\tmem_copy(pImg->m_pData, pData, pImg->m_Width*pImg->m_Height*PixelSize);\n\t\t\t\t\tpImg->m_Texture = m_pEditor->Graphics()->LoadTextureRaw(pImg->m_Width, pImg->m_Height, pImg->m_Format, pImg->m_pData, CImageInfo::FORMAT_AUTO, 0);\n\t\t\t\t}\n\n\t\t\t\t// copy image name\n\t\t\t\tif(pName)\n\t\t\t\t\tstr_copy(pImg->m_aName, pName, 128);\n\n\t\t\t\t// load auto mapper file\n\t\t\t\tpImg->LoadAutoMapper();\n\n\t\t\t\tm_lImages.add(pImg);\n\n\t\t\t\t// unload image\n\t\t\t\tDataFile.UnloadData(pItem->m_ImageData);\n\t\t\t\tDataFile.UnloadData(pItem->m_ImageName);\n\t\t\t}\n\t\t}\n\n\t\t// load groups\n\t\t{\n\t\t\tint LayersStart, LayersNum;\n\t\t\tDataFile.GetType(MAPITEMTYPE_LAYER, &LayersStart, &LayersNum);\n\n\t\t\tint Start, Num;\n\t\t\tDataFile.GetType(MAPITEMTYPE_GROUP, &Start, &Num);\n\t\t\tfor(int g = 0; g < Num; g++)\n\t\t\t{\n\t\t\t\tCMapItemGroup *pGItem = (CMapItemGroup *)DataFile.GetItem(Start+g, 0, 0);\n\n\t\t\t\tif(pGItem->m_Version < 1 || pGItem->m_Version > CMapItemGroup::CURRENT_VERSION)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tCLayerGroup *pGroup = NewGroup();\n\t\t\t\tpGroup->m_ParallaxX = pGItem->m_ParallaxX;\n\t\t\t\tpGroup->m_ParallaxY = pGItem->m_ParallaxY;\n\t\t\t\tpGroup->m_OffsetX = pGItem->m_OffsetX;\n\t\t\t\tpGroup->m_OffsetY = pGItem->m_OffsetY;\n\n\t\t\t\tif(pGItem->m_Version >= 2)\n\t\t\t\t{\n\t\t\t\t\tpGroup->m_UseClipping = pGItem->m_UseClipping;\n\t\t\t\t\tpGroup->m_ClipX = pGItem->m_ClipX;\n\t\t\t\t\tpGroup->m_ClipY = pGItem->m_ClipY;\n\t\t\t\t\tpGroup->m_ClipW = pGItem->m_ClipW;\n\t\t\t\t\tpGroup->m_ClipH = pGItem->m_ClipH;\n\t\t\t\t}\n\n\t\t\t\t// load group name\n\t\t\t\tif(pGItem->m_Version >= 3)\n\t\t\t\t\tIntsToStr(pGItem->m_aName, sizeof(pGroup->m_aName)/sizeof(int), pGroup->m_aName);\n\n\t\t\t\tfor(int l = 0; l < pGItem->m_NumLayers; l++)\n\t\t\t\t{\n\t\t\t\t\tCLayer *pLayer = 0;\n\t\t\t\t\tCMapItemLayer *pLayerItem = (CMapItemLayer *)DataFile.GetItem(LayersStart+pGItem->m_StartLayer+l, 0, 0);\n\t\t\t\t\tif(!pLayerItem)\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tif(pLayerItem->m_Type == LAYERTYPE_TILES)\n\t\t\t\t\t{\n\t\t\t\t\t\tCMapItemLayerTilemap *pTilemapItem = (CMapItemLayerTilemap *)pLayerItem;\n\t\t\t\t\t\tCLayerTiles *pTiles = 0;\n\n\t\t\t\t\t\tif(pTilemapItem->m_Flags&TILESLAYERFLAG_GAME)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpTiles = new CLayerGame(pTilemapItem->m_Width, pTilemapItem->m_Height);\n\t\t\t\t\t\t\tMakeGameLayer(pTiles);\n\t\t\t\t\t\t\tMakeGameGroup(pGroup);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpTiles = new CLayerTiles(pTilemapItem->m_Width, pTilemapItem->m_Height);\n\t\t\t\t\t\t\tpTiles->m_pEditor = m_pEditor;\n\t\t\t\t\t\t\tpTiles->m_Color = pTilemapItem->m_Color;\n\t\t\t\t\t\t\tpTiles->m_ColorEnv = pTilemapItem->m_ColorEnv;\n\t\t\t\t\t\t\tpTiles->m_ColorEnvOffset = pTilemapItem->m_ColorEnvOffset;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tpLayer = pTiles;\n\n\t\t\t\t\t\tpGroup->AddLayer(pTiles);\n\t\t\t\t\t\tvoid *pData = DataFile.GetData(pTilemapItem->m_Data);\n\t\t\t\t\t\tpTiles->m_Image = pTilemapItem->m_Image;\n\t\t\t\t\t\tpTiles->m_Game = pTilemapItem->m_Flags&TILESLAYERFLAG_GAME;\n\n\t\t\t\t\t\t// load layer name\n\t\t\t\t\t\tif(pTilemapItem->m_Version >= 3)\n\t\t\t\t\t\t\tIntsToStr(pTilemapItem->m_aName, sizeof(pTiles->m_aName)/sizeof(int), pTiles->m_aName);\n\n\t\t\t\t\t\tmem_copy(pTiles->m_pTiles, pData, pTiles->m_Width*pTiles->m_Height*sizeof(CTile));\n\n\t\t\t\t\t\tif(pTiles->m_Game && pTilemapItem->m_Version == MakeVersion(1, *pTilemapItem))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor(int i = 0; i < pTiles->m_Width*pTiles->m_Height; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif(pTiles->m_pTiles[i].m_Index)\n\t\t\t\t\t\t\t\t\tpTiles->m_pTiles[i].m_Index += ENTITY_OFFSET;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tDataFile.UnloadData(pTilemapItem->m_Data);\n\t\t\t\t\t}\n\t\t\t\t\telse if(pLayerItem->m_Type == LAYERTYPE_QUADS)\n\t\t\t\t\t{\n\t\t\t\t\t\tCMapItemLayerQuads *pQuadsItem = (CMapItemLayerQuads *)pLayerItem;\n\t\t\t\t\t\tCLayerQuads *pQuads = new CLayerQuads;\n\t\t\t\t\t\tpQuads->m_pEditor = m_pEditor;\n\t\t\t\t\t\tpLayer = pQuads;\n\t\t\t\t\t\tpQuads->m_Image = pQuadsItem->m_Image;\n\t\t\t\t\t\tif(pQuads->m_Image < -1 || pQuads->m_Image >= m_lImages.size())\n\t\t\t\t\t\t\tpQuads->m_Image = -1;\n\n\t\t\t\t\t\t// load layer name\n\t\t\t\t\t\tif(pQuadsItem->m_Version >= 2)\n\t\t\t\t\t\t\tIntsToStr(pQuadsItem->m_aName, sizeof(pQuads->m_aName)/sizeof(int), pQuads->m_aName);\n\n\t\t\t\t\t\tvoid *pData = DataFile.GetDataSwapped(pQuadsItem->m_Data);\n\t\t\t\t\t\tpGroup->AddLayer(pQuads);\n\t\t\t\t\t\tpQuads->m_lQuads.set_size(pQuadsItem->m_NumQuads);\n\t\t\t\t\t\tmem_copy(pQuads->m_lQuads.base_ptr(), pData, sizeof(CQuad)*pQuadsItem->m_NumQuads);\n\t\t\t\t\t\tDataFile.UnloadData(pQuadsItem->m_Data);\n\t\t\t\t\t}\n\n\t\t\t\t\tif(pLayer)\n\t\t\t\t\t\tpLayer->m_Flags = pLayerItem->m_Flags;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// load envelopes\n\t\t{\n\t\t\tCEnvPoint *pPoints = 0;\n\n\t\t\t{\n\t\t\t\tint Start, Num;\n\t\t\t\tDataFile.GetType(MAPITEMTYPE_ENVPOINTS, &Start, &Num);\n\t\t\t\tif(Num)\n\t\t\t\t\tpPoints = (CEnvPoint *)DataFile.GetItem(Start, 0, 0);\n\t\t\t}\n\n\t\t\tint Start, Num;\n\t\t\tDataFile.GetType(MAPITEMTYPE_ENVELOPE, &Start, &Num);\n\t\t\tfor(int e = 0; e < Num; e++)\n\t\t\t{\n\t\t\t\tCMapItemEnvelope *pItem = (CMapItemEnvelope *)DataFile.GetItem(Start+e, 0, 0);\n\t\t\t\tCEnvelope *pEnv = new CEnvelope(pItem->m_Channels);\n\t\t\t\tpEnv->m_lPoints.set_size(pItem->m_NumPoints);\n\t\t\t\tmem_copy(pEnv->m_lPoints.base_ptr(), &pPoints[pItem->m_StartPoint], sizeof(CEnvPoint)*pItem->m_NumPoints);\n\t\t\t\tif(pItem->m_aName[0] != -1)\t// compatibility with old maps\n\t\t\t\t\tIntsToStr(pItem->m_aName, sizeof(pItem->m_aName)/sizeof(int), pEnv->m_aName);\n\t\t\t\tm_lEnvelopes.add(pEnv);\n\t\t\t\tif(pItem->m_Version >= 2)\n\t\t\t\t\tpEnv->m_Synchronized = pItem->m_Synchronized;\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t\treturn 0;\n\n\treturn 1;\n}\n\nstatic int gs_ModifyAddAmount = 0;\nstatic void ModifyAdd(int *pIndex)\n{\n\tif(*pIndex >= 0)\n\t\t*pIndex += gs_ModifyAddAmount;\n}\n\nint CEditor::Append(const char *pFileName, int StorageType)\n{\n\tCEditorMap NewMap;\n\tNewMap.m_pEditor = this;\n\n\tint Err;\n\tErr = NewMap.Load(Kernel()->RequestInterface<IStorage>(), pFileName, StorageType);\n\tif(!Err)\n\t\treturn Err;\n\n\t// modify indecies\n\tgs_ModifyAddAmount = m_Map.m_lImages.size();\n\tNewMap.ModifyImageIndex(ModifyAdd);\n\n\tgs_ModifyAddAmount = m_Map.m_lEnvelopes.size();\n\tNewMap.ModifyEnvelopeIndex(ModifyAdd);\n\n\t// transfer images\n\tfor(int i = 0; i < NewMap.m_lImages.size(); i++)\n\t\tm_Map.m_lImages.add(NewMap.m_lImages[i]);\n\tNewMap.m_lImages.clear();\n\n\t// transfer envelopes\n\tfor(int i = 0; i < NewMap.m_lEnvelopes.size(); i++)\n\t\tm_Map.m_lEnvelopes.add(NewMap.m_lEnvelopes[i]);\n\tNewMap.m_lEnvelopes.clear();\n\n\t// transfer groups\n\n\tfor(int i = 0; i < NewMap.m_lGroups.size(); i++)\n\t{\n\t\tif(NewMap.m_lGroups[i] == NewMap.m_pGameGroup)\n\t\t\tdelete NewMap.m_lGroups[i];\n\t\telse\n\t\t{\n\t\t\tNewMap.m_lGroups[i]->m_pMap = &m_Map;\n\t\t\tm_Map.m_lGroups.add(NewMap.m_lGroups[i]);\n\t\t}\n\t}\n\tNewMap.m_lGroups.clear();\n\n\t// all done \\o/\n\treturn 0;\n}\n"
  },
  {
    "path": "src/game/editor/layer_game.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include \"editor.h\"\n\n\nCLayerGame::CLayerGame(int w, int h)\n: CLayerTiles(w, h)\n{\n\tstr_copy(m_aName, \"Game\", sizeof(m_aName));\n\tm_Game = 1;\n}\n\nCLayerGame::~CLayerGame()\n{\n}\n\nint CLayerGame::RenderProperties(CUIRect *pToolbox)\n{\n\tint r = CLayerTiles::RenderProperties(pToolbox);\n\tm_Image = -1;\n\treturn r;\n}\n"
  },
  {
    "path": "src/game/editor/layer_quads.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/math.h>\n\n#include <engine/console.h>\n#include <engine/graphics.h>\n\n#include \"editor.h\"\n#include <game/generated/client_data.h>\n#include <game/client/localization.h>\n#include <game/client/render.h>\n\n\nCLayerQuads::CLayerQuads()\n{\n\tm_Type = LAYERTYPE_QUADS;\n\tstr_copy(m_aName, \"Quads\", sizeof(m_aName));\n\tm_Image = -1;\n}\n\nCLayerQuads::~CLayerQuads()\n{\n}\n\nvoid CLayerQuads::Render()\n{\n\tGraphics()->TextureClear();\n\tif(m_Image >= 0 && m_Image < m_pEditor->m_Map.m_lImages.size())\n\t\tGraphics()->TextureSet(m_pEditor->m_Map.m_lImages[m_Image]->m_Texture);\n\n\tGraphics()->BlendNone();\n\tm_pEditor->RenderTools()->RenderQuads(m_lQuads.base_ptr(), m_lQuads.size(), LAYERRENDERFLAG_OPAQUE, m_pEditor->EnvelopeEval, m_pEditor);\n\tGraphics()->BlendNormal();\n\tm_pEditor->RenderTools()->RenderQuads(m_lQuads.base_ptr(), m_lQuads.size(), LAYERRENDERFLAG_TRANSPARENT, m_pEditor->EnvelopeEval, m_pEditor);\n}\n\nCQuad *CLayerQuads::NewQuad()\n{\n\tm_pEditor->m_Map.m_Modified = true;\n\n\tCQuad *q = &m_lQuads[m_lQuads.add(CQuad())];\n\n\tq->m_PosEnv = -1;\n\tq->m_ColorEnv = -1;\n\tq->m_PosEnvOffset = 0;\n\tq->m_ColorEnvOffset = 0;\n\tint x = 0, y = 0;\n\tq->m_aPoints[0].x = x;\n\tq->m_aPoints[0].y = y;\n\tq->m_aPoints[1].x = x+64;\n\tq->m_aPoints[1].y = y;\n\tq->m_aPoints[2].x = x;\n\tq->m_aPoints[2].y = y+64;\n\tq->m_aPoints[3].x = x+64;\n\tq->m_aPoints[3].y = y+64;\n\n\tq->m_aPoints[4].x = x+32; // pivot\n\tq->m_aPoints[4].y = y+32;\n\n\tfor(int i = 0; i < 5; i++)\n\t{\n\t\tq->m_aPoints[i].x <<= 10;\n\t\tq->m_aPoints[i].y <<= 10;\n\t}\n\n\n\tq->m_aTexcoords[0].x = 0;\n\tq->m_aTexcoords[0].y = 0;\n\n\tq->m_aTexcoords[1].x = 1<<10;\n\tq->m_aTexcoords[1].y = 0;\n\n\tq->m_aTexcoords[2].x = 0;\n\tq->m_aTexcoords[2].y = 1<<10;\n\n\tq->m_aTexcoords[3].x = 1<<10;\n\tq->m_aTexcoords[3].y = 1<<10;\n\n\tq->m_aColors[0].r = 255; q->m_aColors[0].g = 255; q->m_aColors[0].b = 255; q->m_aColors[0].a = 255;\n\tq->m_aColors[1].r = 255; q->m_aColors[1].g = 255; q->m_aColors[1].b = 255; q->m_aColors[1].a = 255;\n\tq->m_aColors[2].r = 255; q->m_aColors[2].g = 255; q->m_aColors[2].b = 255; q->m_aColors[2].a = 255;\n\tq->m_aColors[3].r = 255; q->m_aColors[3].g = 255; q->m_aColors[3].b = 255; q->m_aColors[3].a = 255;\n\n\treturn q;\n}\n\nvoid CLayerQuads::BrushSelecting(CUIRect Rect)\n{\n\t// draw selection rectangle\n\tIGraphics::CLineItem Array[4] = {\n\t\tIGraphics::CLineItem(Rect.x, Rect.y, Rect.x+Rect.w, Rect.y),\n\t\tIGraphics::CLineItem(Rect.x+Rect.w, Rect.y, Rect.x+Rect.w, Rect.y+Rect.h),\n\t\tIGraphics::CLineItem(Rect.x+Rect.w, Rect.y+Rect.h, Rect.x, Rect.y+Rect.h),\n\t\tIGraphics::CLineItem(Rect.x, Rect.y+Rect.h, Rect.x, Rect.y)};\n\tGraphics()->TextureClear();\n\tGraphics()->LinesBegin();\n\tGraphics()->LinesDraw(Array, 4);\n\tGraphics()->LinesEnd();\n}\n\nint CLayerQuads::BrushGrab(CLayerGroup *pBrush, CUIRect Rect)\n{\n\t// create new layers\n\tCLayerQuads *pGrabbed = new CLayerQuads();\n\tpGrabbed->m_pEditor = m_pEditor;\n\tpGrabbed->m_Image = m_Image;\n\tpBrush->AddLayer(pGrabbed);\n\n\t//dbg_msg(\"\", \"%f %f %f %f\", rect.x, rect.y, rect.w, rect.h);\n\tfor(int i = 0; i < m_lQuads.size(); i++)\n\t{\n\t\tCQuad *q = &m_lQuads[i];\n\t\tfloat px = fx2f(q->m_aPoints[4].x);\n\t\tfloat py = fx2f(q->m_aPoints[4].y);\n\n\t\tif(px > Rect.x && px < Rect.x+Rect.w && py > Rect.y && py < Rect.y+Rect.h)\n\t\t{\n\t\t\tCQuad n;\n\t\t\tn = *q;\n\n\t\t\tfor(int p = 0; p < 5; p++)\n\t\t\t{\n\t\t\t\tn.m_aPoints[p].x -= f2fx(Rect.x);\n\t\t\t\tn.m_aPoints[p].y -= f2fx(Rect.y);\n\t\t\t}\n\n\t\t\tpGrabbed->m_lQuads.add(n);\n\t\t}\n\t}\n\n\treturn pGrabbed->m_lQuads.size()?1:0;\n}\n\nvoid CLayerQuads::BrushPlace(CLayer *pBrush, float wx, float wy)\n{\n\tCLayerQuads *l = (CLayerQuads *)pBrush;\n\tfor(int i = 0; i < l->m_lQuads.size(); i++)\n\t{\n\t\tCQuad n = l->m_lQuads[i];\n\n\t\tfor(int p = 0; p < 5; p++)\n\t\t{\n\t\t\tn.m_aPoints[p].x += f2fx(wx);\n\t\t\tn.m_aPoints[p].y += f2fx(wy);\n\t\t}\n\n\t\tm_lQuads.add(n);\n\t}\n\tm_pEditor->m_Map.m_Modified = true;\n}\n\nvoid CLayerQuads::BrushFlipX()\n{\n}\n\nvoid CLayerQuads::BrushFlipY()\n{\n}\n\nvoid Rotate(vec2 *pCenter, vec2 *pPoint, float Rotation)\n{\n\tfloat x = pPoint->x - pCenter->x;\n\tfloat y = pPoint->y - pCenter->y;\n\tpPoint->x = x * cosf(Rotation) - y * sinf(Rotation) + pCenter->x;\n\tpPoint->y = x * sinf(Rotation) + y * cosf(Rotation) + pCenter->y;\n}\n\nvoid CLayerQuads::BrushRotate(float Amount)\n{\n\tvec2 Center;\n\tGetSize(&Center.x, &Center.y);\n\tCenter.x /= 2;\n\tCenter.y /= 2;\n\n\tfor(int i = 0; i < m_lQuads.size(); i++)\n\t{\n\t\tCQuad *q = &m_lQuads[i];\n\n\t\tfor(int p = 0; p < 5; p++)\n\t\t{\n\t\t\tvec2 Pos(fx2f(q->m_aPoints[p].x), fx2f(q->m_aPoints[p].y));\n\t\t\tRotate(&Center, &Pos, Amount);\n\t\t\tq->m_aPoints[p].x = f2fx(Pos.x);\n\t\t\tq->m_aPoints[p].y = f2fx(Pos.y);\n\t\t}\n\t}\n}\n\nvoid CLayerQuads::GetSize(float *w, float *h)\n{\n\t*w = 0; *h = 0;\n\n\tfor(int i = 0; i < m_lQuads.size(); i++)\n\t{\n\t\tfor(int p = 0; p < 5; p++)\n\t\t{\n\t\t\t*w = max(*w, fx2f(m_lQuads[i].m_aPoints[p].x));\n\t\t\t*h = max(*h, fx2f(m_lQuads[i].m_aPoints[p].y));\n\t\t}\n\t}\n}\n\nextern int gs_SelectedPoints;\n\nint CLayerQuads::RenderProperties(CUIRect *pToolBox)\n{\n\t// layer props\n\tenum\n\t{\n\t\tPROP_IMAGE=0,\n\t\tNUM_PROPS,\n\t};\n\n\tCProperty aProps[] = {\n\t\t{\"Image\", m_Image, PROPTYPE_IMAGE, -1, 0},\n\t\t{0},\n\t};\n\n\tstatic int s_aIds[NUM_PROPS] = {0};\n\tint NewVal = 0;\n\tint Prop = m_pEditor->DoProperties(pToolBox, aProps, s_aIds, &NewVal);\n\tif(Prop != -1)\n\t\tm_pEditor->m_Map.m_Modified = true;\n\n\tif(Prop == PROP_IMAGE)\n\t{\n\t\tif(NewVal >= 0)\n\t\t\tm_Image = NewVal%m_pEditor->m_Map.m_lImages.size();\n\t\telse\n\t\t\tm_Image = -1;\n\t}\n\n\treturn 0;\n}\n\n\nvoid CLayerQuads::ModifyImageIndex(INDEX_MODIFY_FUNC Func)\n{\n\tFunc(&m_Image);\n}\n\nvoid CLayerQuads::ModifyEnvelopeIndex(INDEX_MODIFY_FUNC Func)\n{\n\tfor(int i = 0; i < m_lQuads.size(); i++)\n\t{\n\t\tFunc(&m_lQuads[i].m_PosEnv);\n\t\tFunc(&m_lQuads[i].m_ColorEnv);\n\t}\n}\n"
  },
  {
    "path": "src/game/editor/layer_tiles.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/math.h>\n\n#include <engine/client.h>\n#include <engine/graphics.h>\n#include <engine/textrender.h>\n\n#include <game/generated/client_data.h>\n#include <game/client/localization.h>\n#include <game/client/render.h>\n#include \"editor.h\"\n\n\nCLayerTiles::CLayerTiles(int w, int h)\n{\n\tm_Type = LAYERTYPE_TILES;\n\tstr_copy(m_aName, \"Tiles\", sizeof(m_aName));\n\tm_Width = w;\n\tm_Height = h;\n\tm_Image = -1;\n\tm_Game = 0;\n\tm_Color.r = 255;\n\tm_Color.g = 255;\n\tm_Color.b = 255;\n\tm_Color.a = 255;\n\tm_ColorEnv = -1;\n\tm_ColorEnvOffset = 0;\n\n\tm_pTiles = new CTile[m_Width*m_Height];\n\tmem_zero(m_pTiles, m_Width*m_Height*sizeof(CTile));\n\n\tm_SelectedRuleSet = 0;\n\tm_SelectedAmount = 50;\n}\n\nCLayerTiles::~CLayerTiles()\n{\n\tdelete [] m_pTiles;\n}\n\nvoid CLayerTiles::PrepareForSave()\n{\n\tfor(int y = 0; y < m_Height; y++)\n\t\tfor(int x = 0; x < m_Width; x++)\n\t\t\tm_pTiles[y*m_Width+x].m_Flags &= TILEFLAG_VFLIP|TILEFLAG_HFLIP|TILEFLAG_ROTATE;\n\n\tif(m_Image != -1 && m_Color.a == 255)\n\t{\n\t\tfor(int y = 0; y < m_Height; y++)\n\t\t\tfor(int x = 0; x < m_Width; x++)\n\t\t\t\tm_pTiles[y*m_Width+x].m_Flags |= m_pEditor->m_Map.m_lImages[m_Image]->m_aTileFlags[m_pTiles[y*m_Width+x].m_Index];\n\t}\n}\n\nvoid CLayerTiles::MakePalette()\n{\n\tfor(int y = 0; y < m_Height; y++)\n\t\tfor(int x = 0; x < m_Width; x++)\n\t\t\tm_pTiles[y*m_Width+x].m_Index = y*16+x;\n}\n\nvoid CLayerTiles::Render()\n{\n\tif(m_Image >= 0 && m_Image < m_pEditor->m_Map.m_lImages.size())\n\t\tm_Texture = m_pEditor->m_Map.m_lImages[m_Image]->m_Texture;\n\tGraphics()->TextureSet(m_Texture);\n\tvec4 Color = vec4(m_Color.r/255.0f, m_Color.g/255.0f, m_Color.b/255.0f, m_Color.a/255.0f);\n\tGraphics()->BlendNone();\n\tm_pEditor->RenderTools()->RenderTilemap(m_pTiles, m_Width, m_Height, 32.0f, Color, LAYERRENDERFLAG_OPAQUE,\n\t\t\t\t\t\t\t\t\t\t\t\tm_pEditor->EnvelopeEval, m_pEditor, m_ColorEnv, m_ColorEnvOffset);\n\tGraphics()->BlendNormal();\n\tm_pEditor->RenderTools()->RenderTilemap(m_pTiles, m_Width, m_Height, 32.0f, Color, LAYERRENDERFLAG_TRANSPARENT,\n\t\t\t\t\t\t\t\t\t\t\t\tm_pEditor->EnvelopeEval, m_pEditor, m_ColorEnv, m_ColorEnvOffset);\n}\n\nint CLayerTiles::ConvertX(float x) const { return (int)(x/32.0f); }\nint CLayerTiles::ConvertY(float y) const { return (int)(y/32.0f); }\n\nvoid CLayerTiles::Convert(CUIRect Rect, RECTi *pOut)\n{\n\tpOut->x = ConvertX(Rect.x);\n\tpOut->y = ConvertY(Rect.y);\n\tpOut->w = ConvertX(Rect.x+Rect.w+31) - pOut->x;\n\tpOut->h = ConvertY(Rect.y+Rect.h+31) - pOut->y;\n}\n\nvoid CLayerTiles::Snap(CUIRect *pRect)\n{\n\tRECTi Out;\n\tConvert(*pRect, &Out);\n\tpRect->x = Out.x*32.0f;\n\tpRect->y = Out.y*32.0f;\n\tpRect->w = Out.w*32.0f;\n\tpRect->h = Out.h*32.0f;\n}\n\nvoid CLayerTiles::Clamp(RECTi *pRect)\n{\n\tif(pRect->x < 0)\n\t{\n\t\tpRect->w += pRect->x;\n\t\tpRect->x = 0;\n\t}\n\n\tif(pRect->y < 0)\n\t{\n\t\tpRect->h += pRect->y;\n\t\tpRect->y = 0;\n\t}\n\n\tif(pRect->x+pRect->w > m_Width)\n\t\tpRect->w = m_Width - pRect->x;\n\n\tif(pRect->y+pRect->h > m_Height)\n\t\tpRect->h = m_Height - pRect->y;\n\n\tif(pRect->h < 0)\n\t\tpRect->h = 0;\n\tif(pRect->w < 0)\n\t\tpRect->w = 0;\n}\n\nvoid CLayerTiles::BrushSelecting(CUIRect Rect)\n{\n\tGraphics()->TextureClear();\n\tm_pEditor->Graphics()->QuadsBegin();\n\tm_pEditor->Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.4f);\n\tSnap(&Rect);\n\tIGraphics::CQuadItem QuadItem(Rect.x, Rect.y, Rect.w, Rect.h);\n\tm_pEditor->Graphics()->QuadsDrawTL(&QuadItem, 1);\n\tm_pEditor->Graphics()->QuadsEnd();\n\tchar aBuf[16];\n\tstr_format(aBuf, sizeof(aBuf), \"%d,%d\", ConvertX(Rect.w), ConvertY(Rect.h));\n\tTextRender()->Text(0, Rect.x+3.0f, Rect.y+3.0f, m_pEditor->m_ShowPicker?15.0f:15.0f*m_pEditor->m_WorldZoom, aBuf, -1);\n}\n\nint CLayerTiles::BrushGrab(CLayerGroup *pBrush, CUIRect Rect)\n{\n\tRECTi r;\n\tConvert(Rect, &r);\n\tClamp(&r);\n\n\tif(!r.w || !r.h)\n\t\treturn 0;\n\n\t// create new layers\n\tCLayerTiles *pGrabbed = new CLayerTiles(r.w, r.h);\n\tpGrabbed->m_pEditor = m_pEditor;\n\tpGrabbed->m_Texture = m_Texture;\n\tpGrabbed->m_Image = m_Image;\n\tpGrabbed->m_Game = m_Game;\n\tpBrush->AddLayer(pGrabbed);\n\n\t// copy the tiles\n\tfor(int y = 0; y < r.h; y++)\n\t\tfor(int x = 0; x < r.w; x++)\n\t\t\tpGrabbed->m_pTiles[y*pGrabbed->m_Width+x] = m_pTiles[(r.y+y)*m_Width+(r.x+x)];\n\n\treturn 1;\n}\n\nvoid CLayerTiles::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect)\n{\n\tif(m_Readonly)\n\t\treturn;\n\n\tSnap(&Rect);\n\n\tint sx = ConvertX(Rect.x);\n\tint sy = ConvertY(Rect.y);\n\tint w = ConvertX(Rect.w);\n\tint h = ConvertY(Rect.h);\n\n\tCLayerTiles *pLt = static_cast<CLayerTiles*>(pBrush);\n\n\tfor(int y = 0; y < h; y++)\n\t{\n\t\tfor(int x = 0; x < w; x++)\n\t\t{\n\t\t\tint fx = x+sx;\n\t\t\tint fy = y+sy;\n\n\t\t\tif(fx < 0 || fx >= m_Width || fy < 0 || fy >= m_Height)\n\t\t\t\tcontinue;\n\n\t\t\tif(Empty)\n\t\t\t\tm_pTiles[fy*m_Width+fx].m_Index = 1;\n\t\t\telse\n\t\t\t\tm_pTiles[fy*m_Width+fx] = pLt->m_pTiles[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)];\n\t\t}\n\t}\n\tm_pEditor->m_Map.m_Modified = true;\n}\n\nvoid CLayerTiles::BrushDraw(CLayer *pBrush, float wx, float wy)\n{\n\tif(m_Readonly)\n\t\treturn;\n\n\t//\n\tCLayerTiles *l = (CLayerTiles *)pBrush;\n\tint sx = ConvertX(wx);\n\tint sy = ConvertY(wy);\n\n\tfor(int y = 0; y < l->m_Height; y++)\n\t\tfor(int x = 0; x < l->m_Width; x++)\n\t\t{\n\t\t\tint fx = x+sx;\n\t\t\tint fy = y+sy;\n\t\t\tif(fx<0 || fx >= m_Width || fy < 0 || fy >= m_Height)\n\t\t\t\tcontinue;\n\n\t\t\tm_pTiles[fy*m_Width+fx] = l->m_pTiles[y*l->m_Width+x];\n\t\t}\n\tm_pEditor->m_Map.m_Modified = true;\n}\n\nvoid CLayerTiles::BrushFlipX()\n{\n\tfor(int y = 0; y < m_Height; y++)\n\t\tfor(int x = 0; x < m_Width/2; x++)\n\t\t{\n\t\t\tCTile Tmp = m_pTiles[y*m_Width+x];\n\t\t\tm_pTiles[y*m_Width+x] = m_pTiles[y*m_Width+m_Width-1-x];\n\t\t\tm_pTiles[y*m_Width+m_Width-1-x] = Tmp;\n\t\t}\n\n\tif(!m_Game)\n\t\tfor(int y = 0; y < m_Height; y++)\n\t\t\tfor(int x = 0; x < m_Width; x++)\n\t\t\t\tm_pTiles[y*m_Width+x].m_Flags ^= m_pTiles[y*m_Width+x].m_Flags&TILEFLAG_ROTATE ? TILEFLAG_HFLIP : TILEFLAG_VFLIP;\n}\n\nvoid CLayerTiles::BrushFlipY()\n{\n\tfor(int y = 0; y < m_Height/2; y++)\n\t\tfor(int x = 0; x < m_Width; x++)\n\t\t{\n\t\t\tCTile Tmp = m_pTiles[y*m_Width+x];\n\t\t\tm_pTiles[y*m_Width+x] = m_pTiles[(m_Height-1-y)*m_Width+x];\n\t\t\tm_pTiles[(m_Height-1-y)*m_Width+x] = Tmp;\n\t\t}\n\n\tif(!m_Game)\n\t\tfor(int y = 0; y < m_Height; y++)\n\t\t\tfor(int x = 0; x < m_Width; x++)\n\t\t\t\tm_pTiles[y*m_Width+x].m_Flags ^= m_pTiles[y*m_Width+x].m_Flags&TILEFLAG_ROTATE ? TILEFLAG_VFLIP : TILEFLAG_HFLIP;\n}\n\nvoid CLayerTiles::BrushRotate(float Amount)\n{\n\tint Rotation = (round(360.0f*Amount/(pi*2))/90)%4;\t// 0=0, 1=90, 2=180, 3=270\n\tif(Rotation < 0)\n\t\tRotation +=4;\n\n\tif(Rotation == 1 || Rotation == 3)\n\t{\n\t\t// 90 rotation\n\t\tCTile *pTempData = new CTile[m_Width*m_Height];\n\t\tmem_copy(pTempData, m_pTiles, m_Width*m_Height*sizeof(CTile));\n\t\tCTile *pDst = m_pTiles;\n\t\tfor(int x = 0; x < m_Width; ++x)\n\t\t\tfor(int y = m_Height-1; y >= 0; --y, ++pDst)\n\t\t\t{\n\t\t\t\t*pDst = pTempData[y*m_Width+x];\n\t\t\t\tif(!m_Game)\n\t\t\t\t{\n\t\t\t\t\tif(pDst->m_Flags&TILEFLAG_ROTATE)\n\t\t\t\t\t\tpDst->m_Flags ^= (TILEFLAG_HFLIP|TILEFLAG_VFLIP);\n\t\t\t\t\tpDst->m_Flags ^= TILEFLAG_ROTATE;\n\t\t\t\t}\n\t\t\t}\n\n\t\tint Temp = m_Width;\n\t\tm_Width = m_Height;\n\t\tm_Height = Temp;\n\t\tdelete[] pTempData;\n\t}\n\n\tif(Rotation == 2 || Rotation == 3)\n\t{\n\t\tBrushFlipX();\n\t\tBrushFlipY();\n\t}\n}\n\nvoid CLayerTiles::Resize(int NewW, int NewH)\n{\n\tCTile *pNewData = new CTile[NewW*NewH];\n\tmem_zero(pNewData, NewW*NewH*sizeof(CTile));\n\n\t// copy old data\n\tfor(int y = 0; y < min(NewH, m_Height); y++)\n\t\tmem_copy(&pNewData[y*NewW], &m_pTiles[y*m_Width], min(m_Width, NewW)*sizeof(CTile));\n\n\t// replace old\n\tdelete [] m_pTiles;\n\tm_pTiles = pNewData;\n\tm_Width = NewW;\n\tm_Height = NewH;\n}\n\nvoid CLayerTiles::Shift(int Direction)\n{\n\tswitch(Direction)\n\t{\n\tcase 1:\n\t\t{\n\t\t\t// left\n\t\t\tfor(int y = 0; y < m_Height; ++y)\n\t\t\t\tmem_move(&m_pTiles[y*m_Width], &m_pTiles[y*m_Width+1], (m_Width-1)*sizeof(CTile));\n\t\t}\n\t\tbreak;\n\tcase 2:\n\t\t{\n\t\t\t// right\n\t\t\tfor(int y = 0; y < m_Height; ++y)\n\t\t\t\tmem_move(&m_pTiles[y*m_Width+1], &m_pTiles[y*m_Width], (m_Width-1)*sizeof(CTile));\n\t\t}\n\t\tbreak;\n\tcase 4:\n\t\t{\n\t\t\t// up\n\t\t\tfor(int y = 0; y < m_Height-1; ++y)\n\t\t\t\tmem_copy(&m_pTiles[y*m_Width], &m_pTiles[(y+1)*m_Width], m_Width*sizeof(CTile));\n\t\t}\n\t\tbreak;\n\tcase 8:\n\t\t{\n\t\t\t// down\n\t\t\tfor(int y = m_Height-1; y > 0; --y)\n\t\t\t\tmem_copy(&m_pTiles[y*m_Width], &m_pTiles[(y-1)*m_Width], m_Width*sizeof(CTile));\n\t\t}\n\t}\n}\n\nvoid CLayerTiles::ShowInfo()\n{\n\tfloat ScreenX0, ScreenY0, ScreenX1, ScreenY1;\n\tGraphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1);\n\tGraphics()->TextureSet(m_pEditor->Client()->GetDebugFont());\n\tGraphics()->QuadsBegin();\n\n\tint StartY = max(0, (int)(ScreenY0/32.0f)-1);\n\tint StartX = max(0, (int)(ScreenX0/32.0f)-1);\n\tint EndY = min((int)(ScreenY1/32.0f)+1, m_Height);\n\tint EndX = min((int)(ScreenX1/32.0f)+1, m_Width);\n\n\tfor(int y = StartY; y < EndY; y++)\n\t\tfor(int x = StartX; x < EndX; x++)\n\t\t{\n\t\t\tint c = x + y*m_Width;\n\t\t\tif(m_pTiles[c].m_Index)\n\t\t\t{\n\t\t\t\tchar aBuf[64];\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"%i\", m_pTiles[c].m_Index);\n\t\t\t\tm_pEditor->Graphics()->QuadsText(x*32, y*32, 16.0f, aBuf);\n\n\t\t\t\tchar aFlags[4] = {\tm_pTiles[c].m_Flags&TILEFLAG_VFLIP ? 'V' : ' ',\n\t\t\t\t\t\t\t\t\tm_pTiles[c].m_Flags&TILEFLAG_HFLIP ? 'H' : ' ',\n\t\t\t\t\t\t\t\t\tm_pTiles[c].m_Flags&TILEFLAG_ROTATE? 'R' : ' ',\n\t\t\t\t\t\t\t\t\t0};\n\t\t\t\tm_pEditor->Graphics()->QuadsText(x*32, y*32+16, 16.0f, aFlags);\n\t\t\t}\n\t\t\tx += m_pTiles[c].m_Skip;\n\t\t}\n\n\tGraphics()->QuadsEnd();\n\tGraphics()->MapScreen(ScreenX0, ScreenY0, ScreenX1, ScreenY1);\n}\n\nint CLayerTiles::RenderProperties(CUIRect *pToolBox)\n{\n\tCUIRect Button;\n\n\tbool InGameGroup = !find_linear(m_pEditor->m_Map.m_pGameGroup->m_lLayers.all(), this).empty();\n\tif(m_pEditor->m_Map.m_pGameLayer != this)\n\t{\n\t\tif(m_Image >= 0 && m_Image < m_pEditor->m_Map.m_lImages.size() && m_pEditor->m_Map.m_lImages[m_Image]->m_pAutoMapper)\n\t\t{\n\t\t\tstatic int s_AutoMapperButton = 0;\n\t\t\tpToolBox->HSplitBottom(12.0f, pToolBox, &Button);\n\t\t\tif(m_pEditor->DoButton_Editor(&s_AutoMapperButton, \"Auto map\", 0, &Button, 0, \"\"))\n\t\t\t\tm_pEditor->PopupSelectConfigAutoMapInvoke(m_pEditor->UI()->MouseX(), m_pEditor->UI()->MouseY());\n\n\t\t\tbool Proceed = m_pEditor->PopupAutoMapProceedOrder();\n\t\t\tif(Proceed)\n\t\t\t{\n\t\t\t\tif(m_pEditor->m_Map.m_lImages[m_Image]->m_pAutoMapper->GetType() == IAutoMapper::TYPE_TILESET)\n\t\t\t\t{\n\t\t\t\t\tm_pEditor->m_Map.m_lImages[m_Image]->m_pAutoMapper->Proceed(this, m_SelectedRuleSet);\n\t\t\t\t\treturn 1; // only close the popup when it's a tileset\n\t\t\t\t}\n\t\t\t\telse if(m_pEditor->m_Map.m_lImages[m_Image]->m_pAutoMapper->GetType() == IAutoMapper::TYPE_DOODADS)\n\t\t\t\t\tm_pEditor->m_Map.m_lImages[m_Image]->m_pAutoMapper->Proceed(this, m_SelectedRuleSet, m_SelectedAmount);\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t\tInGameGroup = false;\n\n\tif(InGameGroup)\n\t{\n\t\tpToolBox->HSplitBottom(2.0f, pToolBox, 0);\n\t\tpToolBox->HSplitBottom(12.0f, pToolBox, &Button);\n\t\tstatic int s_ColclButton = 0;\n\t\tif(m_pEditor->DoButton_Editor(&s_ColclButton, \"Game tiles\", 0, &Button, 0, \"Constructs game tiles from this layer\"))\n\t\t\tm_pEditor->PopupSelectGametileOpInvoke(m_pEditor->UI()->MouseX(), m_pEditor->UI()->MouseY());\n\n\t\tint Result = m_pEditor->PopupSelectGameTileOpResult();\n\t\tif(Result > -1)\n\t\t{\n\t\t\tCLayerTiles *gl = m_pEditor->m_Map.m_pGameLayer;\n\t\t\tint w = min(gl->m_Width, m_Width);\n\t\t\tint h = min(gl->m_Height, m_Height);\n\t\t\tfor(int y = 0; y < h; y++)\n\t\t\t\tfor(int x = 0; x < w; x++)\n\t\t\t\t\tif(m_pTiles[y*m_Width+x].m_Index)\n\t\t\t\t\t\tgl->m_pTiles[y*gl->m_Width+x].m_Index = TILE_AIR+Result;\n\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tenum\n\t{\n\t\tPROP_WIDTH=0,\n\t\tPROP_HEIGHT,\n\t\tPROP_SHIFT,\n\t\tPROP_IMAGE,\n\t\tPROP_COLOR,\n\t\tPROP_COLOR_ENV,\n\t\tPROP_COLOR_ENV_OFFSET,\n\t\tNUM_PROPS,\n\t};\n\n\tint Color = 0;\n\tColor |= m_Color.r<<24;\n\tColor |= m_Color.g<<16;\n\tColor |= m_Color.b<<8;\n\tColor |= m_Color.a;\n\n\tCProperty aProps[] = {\n\t\t{\"Width\", m_Width, PROPTYPE_INT_SCROLL, 1, 1000000000},\n\t\t{\"Height\", m_Height, PROPTYPE_INT_SCROLL, 1, 1000000000},\n\t\t{\"Shift\", 0, PROPTYPE_SHIFT, 0, 0},\n\t\t{\"Image\", m_Image, PROPTYPE_IMAGE, 0, 0},\n\t\t{\"Color\", Color, PROPTYPE_COLOR, 0, 0},\n\t\t{\"Color Env\", m_ColorEnv+1, PROPTYPE_INT_STEP, 0, m_pEditor->m_Map.m_lEnvelopes.size()+1},\n\t\t{\"Color TO\", m_ColorEnvOffset, PROPTYPE_INT_SCROLL, -1000000, 1000000},\n\t\t{0},\n\t};\n\n\tif(m_pEditor->m_Map.m_pGameLayer == this) // remove the image and color properties if this is the game layer\n\t{\n\t\taProps[3].m_pName = 0;\n\t\taProps[4].m_pName = 0;\n\t}\n\n\tstatic int s_aIds[NUM_PROPS] = {0};\n\tint NewVal = 0;\n\tint Prop = m_pEditor->DoProperties(pToolBox, aProps, s_aIds, &NewVal);\n\tif(Prop != -1)\n\t\tm_pEditor->m_Map.m_Modified = true;\n\n\tif(Prop == PROP_WIDTH && NewVal > 1)\n\t\tResize(NewVal, m_Height);\n\telse if(Prop == PROP_HEIGHT && NewVal > 1)\n\t\tResize(m_Width, NewVal);\n\telse if(Prop == PROP_SHIFT)\n\t\tShift(NewVal);\n\telse if(Prop == PROP_IMAGE)\n\t{\n\t\tif (NewVal == -1)\n\t\t{\n\t\t\tm_Texture = IGraphics::CTextureHandle();\n\t\t\tm_Image = -1;\n\t\t}\n\t\telse\n\t\t\tm_Image = NewVal%m_pEditor->m_Map.m_lImages.size();\n\t}\n\telse if(Prop == PROP_COLOR)\n\t{\n\t\tm_Color.r = (NewVal>>24)&0xff;\n\t\tm_Color.g = (NewVal>>16)&0xff;\n\t\tm_Color.b = (NewVal>>8)&0xff;\n\t\tm_Color.a = NewVal&0xff;\n\t}\n\tif(Prop == PROP_COLOR_ENV)\n\t{\n\t\tint Index = clamp(NewVal-1, -1, m_pEditor->m_Map.m_lEnvelopes.size()-1);\n\t\tint Step = (Index-m_ColorEnv)%2;\n\t\tif(Step != 0)\n\t\t{\n\t\t\tfor(; Index >= -1 && Index < m_pEditor->m_Map.m_lEnvelopes.size(); Index += Step)\n\t\t\t\tif(Index == -1 || m_pEditor->m_Map.m_lEnvelopes[Index]->m_Channels == 4)\n\t\t\t\t{\n\t\t\t\t\tm_ColorEnv = Index;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t}\n\t}\n\tif(Prop == PROP_COLOR_ENV_OFFSET)\n\t\tm_ColorEnvOffset = NewVal;\n\n\treturn 0;\n}\n\n\nvoid CLayerTiles::ModifyImageIndex(INDEX_MODIFY_FUNC Func)\n{\n\tFunc(&m_Image);\n}\n\nvoid CLayerTiles::ModifyEnvelopeIndex(INDEX_MODIFY_FUNC Func)\n{\n}\n"
  },
  {
    "path": "src/game/editor/popups.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n\n#include <base/tl/array.h>\n\n#include <engine/console.h>\n#include <engine/graphics.h>\n#include <engine/input.h>\n#include <engine/keys.h>\n#include <engine/storage.h>\n\n#include \"editor.h\"\n\n\n// popup menu handling\nstatic struct\n{\n\tCUIRect m_Rect;\n\tvoid *m_pId;\n\tint (*m_pfnFunc)(CEditor *pEditor, CUIRect Rect);\n\tint m_IsMenu;\n\tvoid *m_pExtra;\n} s_UiPopups[8];\n\nstatic int g_UiNumPopups = 0;\n\nvoid CEditor::UiInvokePopupMenu(void *pID, int Flags, float x, float y, float Width, float Height, int (*pfnFunc)(CEditor *pEditor, CUIRect Rect), void *pExtra)\n{\n\tConsole()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"editor\", \"invoked\");\n\tif(x + Width > UI()->Screen()->w)\n\t\tx -= Width;\n\tif(y + Height > UI()->Screen()->h)\n\t\ty -= Height;\n\ts_UiPopups[g_UiNumPopups].m_pId = pID;\n\ts_UiPopups[g_UiNumPopups].m_IsMenu = Flags;\n\ts_UiPopups[g_UiNumPopups].m_Rect.x = x;\n\ts_UiPopups[g_UiNumPopups].m_Rect.y = y;\n\ts_UiPopups[g_UiNumPopups].m_Rect.w = Width;\n\ts_UiPopups[g_UiNumPopups].m_Rect.h = Height;\n\ts_UiPopups[g_UiNumPopups].m_pfnFunc = pfnFunc;\n\ts_UiPopups[g_UiNumPopups].m_pExtra = pExtra;\n\tg_UiNumPopups++;\n}\n\nvoid CEditor::UiDoPopupMenu()\n{\n\tfor(int i = 0; i < g_UiNumPopups; i++)\n\t{\n\t\tbool Inside = UI()->MouseInside(&s_UiPopups[i].m_Rect);\n\t\tUI()->SetHotItem(&s_UiPopups[i].m_pId);\n\n\t\tif(UI()->ActiveItem() == &s_UiPopups[i].m_pId)\n\t\t{\n\t\t\tif(!UI()->MouseButton(0))\n\t\t\t{\n\t\t\t\tif(!Inside)\n\t\t\t\t\tg_UiNumPopups--;\n\t\t\t\tUI()->SetActiveItem(0);\n\t\t\t}\n\t\t}\n\t\telse if(UI()->HotItem() == &s_UiPopups[i].m_pId)\n\t\t{\n\t\t\tif(UI()->MouseButton(0))\n\t\t\t\tUI()->SetActiveItem(&s_UiPopups[i].m_pId);\n\t\t}\n\n\t\tint Corners = CUI::CORNER_ALL;\n\t\tif(s_UiPopups[i].m_IsMenu)\n\t\t\tCorners = CUI::CORNER_R|CUI::CORNER_B;\n\n\t\tCUIRect r = s_UiPopups[i].m_Rect;\n\t\tRenderTools()->DrawUIRect(&r, vec4(0.5f,0.5f,0.5f,0.75f), Corners, 3.0f);\n\t\tr.Margin(1.0f, &r);\n\t\tRenderTools()->DrawUIRect(&r, vec4(0,0,0,0.75f), Corners, 3.0f);\n\t\tr.Margin(4.0f, &r);\n\n\t\tif(s_UiPopups[i].m_pfnFunc(this, r))\n\t\t\tg_UiNumPopups--;\n\n\t\tif(Input()->KeyDown(KEY_ESCAPE))\n\t\t\tg_UiNumPopups--;\n\t}\n}\n\n\nint CEditor::PopupGroup(CEditor *pEditor, CUIRect View)\n{\n\t// remove group button\n\tCUIRect Button;\n\tView.HSplitBottom(12.0f, &View, &Button);\n\tstatic int s_DeleteButton = 0;\n\n\t// don't allow deletion of game group\n\tif(pEditor->m_Map.m_pGameGroup != pEditor->GetSelectedGroup())\n\t{\n\t\tif(pEditor->DoButton_Editor(&s_DeleteButton, \"Delete group\", 0, &Button, 0, \"Delete group\"))\n\t\t{\n\t\t\tpEditor->m_Map.DeleteGroup(pEditor->m_SelectedGroup);\n\t\t\tpEditor->m_SelectedGroup = max(0, pEditor->m_SelectedGroup-1);\n\t\t\treturn 1;\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(pEditor->DoButton_Editor(&s_DeleteButton, \"Clean-up game tiles\", 0, &Button, 0, \"Removes game tiles that aren't based on a layer\"))\n\t\t{\n\t\t\t// gather all tile layers\n\t\t\tarray<CLayerTiles*> Layers;\n\t\t\tfor(int i = 0; i < pEditor->m_Map.m_pGameGroup->m_lLayers.size(); ++i)\n\t\t\t{\n\t\t\t\tif(pEditor->m_Map.m_pGameGroup->m_lLayers[i] != pEditor->m_Map.m_pGameLayer && pEditor->m_Map.m_pGameGroup->m_lLayers[i]->m_Type == LAYERTYPE_TILES)\n\t\t\t\t\tLayers.add(static_cast<CLayerTiles *>(pEditor->m_Map.m_pGameGroup->m_lLayers[i]));\n\t\t\t}\n\n\t\t\t// search for unneeded game tiles\n\t\t\tCLayerTiles *gl = pEditor->m_Map.m_pGameLayer;\n\t\t\tfor(int y = 0; y < gl->m_Height; ++y)\n\t\t\t\tfor(int x = 0; x < gl->m_Width; ++x)\n\t\t\t\t{\n\t\t\t\t\tif(gl->m_pTiles[y*gl->m_Width+x].m_Index > static_cast<unsigned char>(TILE_NOHOOK))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tbool Found = false;\n\t\t\t\t\tfor(int i = 0; i < Layers.size(); ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(x < Layers[i]->m_Width && y < Layers[i]->m_Height && Layers[i]->m_pTiles[y*Layers[i]->m_Width+x].m_Index)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tFound = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif(!Found)\n\t\t\t\t\t{\n\t\t\t\t\t\tgl->m_pTiles[y*gl->m_Width+x].m_Index = TILE_AIR;\n\t\t\t\t\t\tpEditor->m_Map.m_Modified = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\t// new tile layer\n\tView.HSplitBottom(10.0f, &View, &Button);\n\tView.HSplitBottom(12.0f, &View, &Button);\n\tstatic int s_NewQuadLayerButton = 0;\n\tif(pEditor->DoButton_Editor(&s_NewQuadLayerButton, \"Add quads layer\", 0, &Button, 0, \"Creates a new quad layer\"))\n\t{\n\t\tCLayer *l = new CLayerQuads;\n\t\tl->m_pEditor = pEditor;\n\t\tpEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->AddLayer(l);\n\t\tpEditor->m_SelectedLayer = pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size()-1;\n\t\tpEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_Collapse = false;\n\t\treturn 1;\n\t}\n\n\t// new quad layer\n\tView.HSplitBottom(5.0f, &View, &Button);\n\tView.HSplitBottom(12.0f, &View, &Button);\n\tstatic int s_NewTileLayerButton = 0;\n\tif(pEditor->DoButton_Editor(&s_NewTileLayerButton, \"Add tile layer\", 0, &Button, 0, \"Creates a new tile layer\"))\n\t{\n\t\tCLayer *l = new CLayerTiles(50, 50);\n\t\tl->m_pEditor = pEditor;\n\t\tpEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->AddLayer(l);\n\t\tpEditor->m_SelectedLayer = pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size()-1;\n\t\tpEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_Collapse = false;\n\t\treturn 1;\n\t}\n\n\t// group name\n\tif(!pEditor->GetSelectedGroup()->m_GameGroup)\n\t{\n\t\tView.HSplitBottom(5.0f, &View, &Button);\n\t\tView.HSplitBottom(12.0f, &View, &Button);\n\t\tstatic float s_Name = 0;\n\t\tpEditor->UI()->DoLabel(&Button, \"Name:\", 10.0f, -1, -1);\n\t\tButton.VSplitLeft(40.0f, 0, &Button);\n\t\tif(pEditor->DoEditBox(&s_Name, &Button, pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_aName, sizeof(pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_aName), 10.0f, &s_Name))\n\t\t\tpEditor->m_Map.m_Modified = true;\n\t}\n\n\tenum\n\t{\n\t\tPROP_ORDER=0,\n\t\tPROP_POS_X,\n\t\tPROP_POS_Y,\n\t\tPROP_PARA_X,\n\t\tPROP_PARA_Y,\n\t\tPROP_USE_CLIPPING,\n\t\tPROP_CLIP_X,\n\t\tPROP_CLIP_Y,\n\t\tPROP_CLIP_W,\n\t\tPROP_CLIP_H,\n\t\tNUM_PROPS,\n\t};\n\n\tCProperty aProps[] = {\n\t\t{\"Order\", pEditor->m_SelectedGroup, PROPTYPE_INT_STEP, 0, pEditor->m_Map.m_lGroups.size()-1},\n\t\t{\"Pos X\", -pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_OffsetX, PROPTYPE_INT_SCROLL, -1000000, 1000000},\n\t\t{\"Pos Y\", -pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_OffsetY, PROPTYPE_INT_SCROLL, -1000000, 1000000},\n\t\t{\"Para X\", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ParallaxX, PROPTYPE_INT_SCROLL, -1000000, 1000000},\n\t\t{\"Para Y\", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ParallaxY, PROPTYPE_INT_SCROLL, -1000000, 1000000},\n\n\t\t{\"Use Clipping\", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_UseClipping, PROPTYPE_BOOL, 0, 1},\n\t\t{\"Clip X\", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipX, PROPTYPE_INT_SCROLL, -1000000, 1000000},\n\t\t{\"Clip Y\", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipY, PROPTYPE_INT_SCROLL, -1000000, 1000000},\n\t\t{\"Clip W\", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipW, PROPTYPE_INT_SCROLL, -1000000, 1000000},\n\t\t{\"Clip H\", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipH, PROPTYPE_INT_SCROLL, -1000000, 1000000},\n\t\t{0},\n\t};\n\n\tstatic int s_aIds[NUM_PROPS] = {0};\n\tint NewVal = 0;\n\n\t// cut the properties that isn't needed\n\tif(pEditor->GetSelectedGroup()->m_GameGroup)\n\t\taProps[PROP_POS_X].m_pName = 0;\n\n\tint Prop = pEditor->DoProperties(&View, aProps, s_aIds, &NewVal);\n\tif(Prop != -1)\n\t\tpEditor->m_Map.m_Modified = true;\n\n\tif(Prop == PROP_ORDER)\n\t\tpEditor->m_SelectedGroup = pEditor->m_Map.SwapGroups(pEditor->m_SelectedGroup, NewVal);\n\n\t// these can not be changed on the game group\n\tif(!pEditor->GetSelectedGroup()->m_GameGroup)\n\t{\n\t\tif(Prop == PROP_PARA_X) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ParallaxX = NewVal;\n\t\telse if(Prop == PROP_PARA_Y) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ParallaxY = NewVal;\n\t\telse if(Prop == PROP_POS_X) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_OffsetX = -NewVal;\n\t\telse if(Prop == PROP_POS_Y) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_OffsetY = -NewVal;\n\t\telse if(Prop == PROP_USE_CLIPPING) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_UseClipping = NewVal;\n\t\telse if(Prop == PROP_CLIP_X) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipX = NewVal;\n\t\telse if(Prop == PROP_CLIP_Y) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipY = NewVal;\n\t\telse if(Prop == PROP_CLIP_W) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipW = NewVal;\n\t\telse if(Prop == PROP_CLIP_H) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipH = NewVal;\n\t}\n\n\treturn 0;\n}\n\nint CEditor::PopupLayer(CEditor *pEditor, CUIRect View)\n{\n\t// remove layer button\n\tCUIRect Button;\n\tView.HSplitBottom(12.0f, &View, &Button);\n\tstatic int s_DeleteButton = 0;\n\n\t// don't allow deletion of game layer\n\tif(pEditor->m_Map.m_pGameLayer != pEditor->GetSelectedLayer(0) &&\n\t\tpEditor->DoButton_Editor(&s_DeleteButton, \"Delete layer\", 0, &Button, 0, \"Deletes the layer\"))\n\t{\n\t\tpEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->DeleteLayer(pEditor->m_SelectedLayer);\n\t\treturn 1;\n\t}\n\n\t// layer name\n\tif(pEditor->m_Map.m_pGameLayer != pEditor->GetSelectedLayer(0))\n\t{\n\t\tView.HSplitBottom(5.0f, &View, &Button);\n\t\tView.HSplitBottom(12.0f, &View, &Button);\n\t\tstatic float s_Name = 0;\n\t\tpEditor->UI()->DoLabel(&Button, \"Name:\", 10.0f, -1, -1);\n\t\tButton.VSplitLeft(40.0f, 0, &Button);\n\t\tif(pEditor->DoEditBox(&s_Name, &Button, pEditor->GetSelectedLayer(0)->m_aName, sizeof(pEditor->GetSelectedLayer(0)->m_aName), 10.0f, &s_Name))\n\t\t\tpEditor->m_Map.m_Modified = true;\n\t}\n\n\tView.HSplitBottom(10.0f, &View, 0);\n\n\tCLayerGroup *pCurrentGroup = pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup];\n\tCLayer *pCurrentLayer = pEditor->GetSelectedLayer(0);\n\n\tenum\n\t{\n\t\tPROP_GROUP=0,\n\t\tPROP_ORDER,\n\t\tPROP_HQ,\n\t\tNUM_PROPS,\n\t};\n\n\tCProperty aProps[] = {\n\t\t{\"Group\", pEditor->m_SelectedGroup, PROPTYPE_INT_STEP, 0, pEditor->m_Map.m_lGroups.size()-1},\n\t\t{\"Order\", pEditor->m_SelectedLayer, PROPTYPE_INT_STEP, 0, pCurrentGroup->m_lLayers.size()},\n\t\t{\"Detail\", pCurrentLayer->m_Flags&LAYERFLAG_DETAIL, PROPTYPE_BOOL, 0, 1},\n\t\t{0},\n\t};\n\n\tif(pEditor->m_Map.m_pGameLayer == pEditor->GetSelectedLayer(0)) // dont use Group and Detail from the selection if this is the game layer\n\t{\n\t\taProps[0].m_Type = PROPTYPE_NULL;\n\t\taProps[2].m_Type = PROPTYPE_NULL;\n\t}\n\n\tstatic int s_aIds[NUM_PROPS] = {0};\n\tint NewVal = 0;\n\tint Prop = pEditor->DoProperties(&View, aProps, s_aIds, &NewVal);\n\tif(Prop != -1)\n\t\tpEditor->m_Map.m_Modified = true;\n\n\tif(Prop == PROP_ORDER)\n\t\tpEditor->m_SelectedLayer = pCurrentGroup->SwapLayers(pEditor->m_SelectedLayer, NewVal);\n\telse if(Prop == PROP_GROUP && pCurrentLayer->m_Type != LAYERTYPE_GAME)\n\t{\n\t\tif(NewVal >= 0 && NewVal < pEditor->m_Map.m_lGroups.size())\n\t\t{\n\t\t\tpCurrentGroup->m_lLayers.remove(pCurrentLayer);\n\t\t\tpEditor->m_Map.m_lGroups[NewVal]->m_lLayers.add(pCurrentLayer);\n\t\t\tpEditor->m_SelectedGroup = NewVal;\n\t\t\tpEditor->m_SelectedLayer = pEditor->m_Map.m_lGroups[NewVal]->m_lLayers.size()-1;\n\t\t}\n\t}\n\telse if(Prop == PROP_HQ)\n\t{\n\t\tpCurrentLayer->m_Flags &= ~LAYERFLAG_DETAIL;\n\t\tif(NewVal)\n\t\t\tpCurrentLayer->m_Flags |= LAYERFLAG_DETAIL;\n\t}\n\n\treturn pCurrentLayer->RenderProperties(&View);\n}\n\nint CEditor::PopupQuad(CEditor *pEditor, CUIRect View)\n{\n\tCQuad *pQuad = pEditor->GetSelectedQuad();\n\n\tCUIRect Button;\n\n\t// delete button\n\tView.HSplitBottom(12.0f, &View, &Button);\n\tstatic int s_DeleteButton = 0;\n\tif(pEditor->DoButton_Editor(&s_DeleteButton, \"Delete\", 0, &Button, 0, \"Deletes the current quad\"))\n\t{\n\t\tCLayerQuads *pLayer = (CLayerQuads *)pEditor->GetSelectedLayerType(0, LAYERTYPE_QUADS);\n\t\tif(pLayer)\n\t\t{\n\t\t\tpEditor->m_Map.m_Modified = true;\n\t\t\tpLayer->m_lQuads.remove_index(pEditor->m_SelectedQuad);\n\t\t\tpEditor->m_SelectedQuad--;\n\t\t}\n\t\treturn 1;\n\t}\n\n\t// aspect ratio button\n\tView.HSplitBottom(10.0f, &View, &Button);\n\tView.HSplitBottom(12.0f, &View, &Button);\n\tCLayerQuads *pLayer = (CLayerQuads *)pEditor->GetSelectedLayerType(0, LAYERTYPE_QUADS);\n\tif(pLayer && pLayer->m_Image >= 0 && pLayer->m_Image < pEditor->m_Map.m_lImages.size())\n\t{\n\t\tstatic int s_AspectRatioButton = 0;\n\t\tif(pEditor->DoButton_Editor(&s_AspectRatioButton, \"Aspect ratio\", 0, &Button, 0, \"Resizes the current Quad based on the aspect ratio of the image\"))\n\t\t{\n\t\t\tint Top = pQuad->m_aPoints[0].y;\n\t\t\tint Left = pQuad->m_aPoints[0].x;\n\t\t\tint Right = pQuad->m_aPoints[0].x;\n\n\t\t\tfor(int k = 1; k < 4; k++)\n\t\t\t{\n\t\t\t\tif(pQuad->m_aPoints[k].y < Top) Top = pQuad->m_aPoints[k].y;\n\t\t\t\tif(pQuad->m_aPoints[k].x < Left) Left = pQuad->m_aPoints[k].x;\n\t\t\t\tif(pQuad->m_aPoints[k].x > Right) Right = pQuad->m_aPoints[k].x;\n\t\t\t}\n\n\t\t\tint Height = (Right-Left)*pEditor->m_Map.m_lImages[pLayer->m_Image]->m_Height/pEditor->m_Map.m_lImages[pLayer->m_Image]->m_Width;\n\n\t\t\tpQuad->m_aPoints[0].x = Left; pQuad->m_aPoints[0].y = Top;\n\t\t\tpQuad->m_aPoints[1].x = Right; pQuad->m_aPoints[1].y = Top;\n\t\t\tpQuad->m_aPoints[2].x = Left; pQuad->m_aPoints[2].y = Top+Height;\n\t\t\tpQuad->m_aPoints[3].x = Right; pQuad->m_aPoints[3].y = Top+Height;\n\t\t\tpEditor->m_Map.m_Modified = true;\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\t// align button\n\tView.HSplitBottom(6.0f, &View, &Button);\n\tView.HSplitBottom(12.0f, &View, &Button);\n\tstatic int s_AlignButton = 0;\n\tif(pEditor->DoButton_Editor(&s_AlignButton, \"Align\", 0, &Button, 0, \"Aligns coordinates of the quad points\"))\n\t{\n\t\tfor(int k = 1; k < 4; k++)\n\t\t{\n\t\t\tpQuad->m_aPoints[k].x = 1000.0f * (int(pQuad->m_aPoints[k].x) / 1000);\n\t\t\tpQuad->m_aPoints[k].y = 1000.0f * (int(pQuad->m_aPoints[k].y) / 1000);\n\t\t}\n\t\tpEditor->m_Map.m_Modified = true;\n\t\treturn 1;\n\t}\n\n\t// square button\n\tView.HSplitBottom(6.0f, &View, &Button);\n\tView.HSplitBottom(12.0f, &View, &Button);\n\tstatic int s_SquareButton = 0;\n\tif(pEditor->DoButton_Editor(&s_SquareButton, \"Square\", 0, &Button, 0, \"Squares the current quad\"))\n\t{\n\t\tint Top = pQuad->m_aPoints[0].y;\n\t\tint Left = pQuad->m_aPoints[0].x;\n\t\tint Bottom = pQuad->m_aPoints[0].y;\n\t\tint Right = pQuad->m_aPoints[0].x;\n\n\t\tfor(int k = 1; k < 4; k++)\n\t\t{\n\t\t\tif(pQuad->m_aPoints[k].y < Top) Top = pQuad->m_aPoints[k].y;\n\t\t\tif(pQuad->m_aPoints[k].x < Left) Left = pQuad->m_aPoints[k].x;\n\t\t\tif(pQuad->m_aPoints[k].y > Bottom) Bottom = pQuad->m_aPoints[k].y;\n\t\t\tif(pQuad->m_aPoints[k].x > Right) Right = pQuad->m_aPoints[k].x;\n\t\t}\n\n\t\tpQuad->m_aPoints[0].x = Left; pQuad->m_aPoints[0].y = Top;\n\t\tpQuad->m_aPoints[1].x = Right; pQuad->m_aPoints[1].y = Top;\n\t\tpQuad->m_aPoints[2].x = Left; pQuad->m_aPoints[2].y = Bottom;\n\t\tpQuad->m_aPoints[3].x = Right; pQuad->m_aPoints[3].y = Bottom;\n\t\tpEditor->m_Map.m_Modified = true;\n\t\treturn 1;\n\t}\n\n\t// center pivot button\n\tView.HSplitBottom(6.0f, &View, &Button);\n\tView.HSplitBottom(12.0f, &View, &Button);\n\tstatic int s_CenterButton = 0;\n\tif(pEditor->DoButton_Editor(&s_CenterButton, \"Center pivot\", 0, &Button, 0, \"Centers the pivot of the current quad\"))\n\t{\n\t\tint Top = pQuad->m_aPoints[0].y;\n\t\tint Left = pQuad->m_aPoints[0].x;\n\t\tint Bottom = pQuad->m_aPoints[0].y;\n\t\tint Right = pQuad->m_aPoints[0].x;\n\n\t\tfor(int k = 1; k < 4; k++)\n\t\t{\n\t\t\tif(pQuad->m_aPoints[k].y < Top) Top = pQuad->m_aPoints[k].y;\n\t\t\tif(pQuad->m_aPoints[k].x < Left) Left = pQuad->m_aPoints[k].x;\n\t\t\tif(pQuad->m_aPoints[k].y > Bottom) Bottom = pQuad->m_aPoints[k].y;\n\t\t\tif(pQuad->m_aPoints[k].x > Right) Right = pQuad->m_aPoints[k].x;\n\t\t}\n\n\t\tpQuad->m_aPoints[4].x = Left+int((Right-Left)/2);\n\t\tpQuad->m_aPoints[4].y = Top+int((Bottom-Top)/2);\n\t\tpEditor->m_Map.m_Modified = true;\n\t\treturn 1;\n\t}\n\n\tenum\n\t{\n\t\tPROP_POS_X=0,\n\t\tPROP_POS_Y,\n\t\tPROP_POS_ENV,\n\t\tPROP_POS_ENV_OFFSET,\n\t\tPROP_COLOR_ENV,\n\t\tPROP_COLOR_ENV_OFFSET,\n\t\tNUM_PROPS,\n\t};\n\n\tCProperty aProps[] = {\n\t\t{\"Pos X\", pQuad->m_aPoints[4].x/1000, PROPTYPE_INT_SCROLL, -1000000, 1000000},\n\t\t{\"Pos Y\", pQuad->m_aPoints[4].y/1000, PROPTYPE_INT_SCROLL, -1000000, 1000000},\n\t\t{\"Pos. Env\", pQuad->m_PosEnv+1, PROPTYPE_INT_STEP, 0, pEditor->m_Map.m_lEnvelopes.size()+1},\n\t\t{\"Pos. TO\", pQuad->m_PosEnvOffset, PROPTYPE_INT_SCROLL, -1000000, 1000000},\n\t\t{\"Color Env\", pQuad->m_ColorEnv+1, PROPTYPE_INT_STEP, 0, pEditor->m_Map.m_lEnvelopes.size()+1},\n\t\t{\"Color TO\", pQuad->m_ColorEnvOffset, PROPTYPE_INT_SCROLL, -1000000, 1000000},\n\n\t\t{0},\n\t};\n\n\tstatic int s_aIds[NUM_PROPS] = {0};\n\tint NewVal = 0;\n\tint Prop = pEditor->DoProperties(&View, aProps, s_aIds, &NewVal);\n\tif(Prop != -1)\n\t\tpEditor->m_Map.m_Modified = true;\n\n\tif(Prop == PROP_POS_X)\n\t{\n\t\tfloat Offset = NewVal*1000-pQuad->m_aPoints[4].x;\n\t\tfor(int k = 0; k < 5; ++k)\n\t\t\tpQuad->m_aPoints[k].x += Offset;\n\t}\n\tif(Prop == PROP_POS_Y)\n\t{\n\t\tfloat Offset = NewVal*1000-pQuad->m_aPoints[4].y;\n\t\tfor(int k = 0; k < 5; ++k)\n\t\t\tpQuad->m_aPoints[k].y += Offset;\n\t}\n\tif(Prop == PROP_POS_ENV)\n\t{\n\t\tint Index = clamp(NewVal-1, -1, pEditor->m_Map.m_lEnvelopes.size()-1);\n\t\tint Step = (Index-pQuad->m_PosEnv)%2;\n\t\tif(Step != 0)\n\t\t{\n\t\t\tfor(; Index >= -1 && Index < pEditor->m_Map.m_lEnvelopes.size(); Index += Step)\n\t\t\t\tif(Index == -1 || pEditor->m_Map.m_lEnvelopes[Index]->m_Channels == 3)\n\t\t\t\t{\n\t\t\t\t\tpQuad->m_PosEnv = Index;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t}\n\t}\n\tif(Prop == PROP_POS_ENV_OFFSET) pQuad->m_PosEnvOffset = NewVal;\n\tif(Prop == PROP_COLOR_ENV)\n\t{\n\t\tint Index = clamp(NewVal-1, -1, pEditor->m_Map.m_lEnvelopes.size()-1);\n\t\tint Step = (Index-pQuad->m_ColorEnv)%2;\n\t\tif(Step != 0)\n\t\t{\n\t\t\tfor(; Index >= -1 && Index < pEditor->m_Map.m_lEnvelopes.size(); Index += Step)\n\t\t\t\tif(Index == -1 || pEditor->m_Map.m_lEnvelopes[Index]->m_Channels == 4)\n\t\t\t\t{\n\t\t\t\t\tpQuad->m_ColorEnv = Index;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t}\n\t}\n\tif(Prop == PROP_COLOR_ENV_OFFSET) pQuad->m_ColorEnvOffset = NewVal;\n\n\treturn 0;\n}\n\nint CEditor::PopupPoint(CEditor *pEditor, CUIRect View)\n{\n\tCQuad *pQuad = pEditor->GetSelectedQuad();\n\n\tenum\n\t{\n\t\tPROP_POS_X=0,\n\t\tPROP_POS_Y,\n\t\tPROP_COLOR,\n\t\tNUM_PROPS,\n\t};\n\n\tint Color = 0;\n\tint x = 0, y = 0;\n\n\tfor(int v = 0; v < 4; v++)\n\t{\n\t\tif(pEditor->m_SelectedPoints&(1<<v))\n\t\t{\n\t\t\tColor = 0;\n\t\t\tColor |= pQuad->m_aColors[v].r<<24;\n\t\t\tColor |= pQuad->m_aColors[v].g<<16;\n\t\t\tColor |= pQuad->m_aColors[v].b<<8;\n\t\t\tColor |= pQuad->m_aColors[v].a;\n\n\t\t\tx = pQuad->m_aPoints[v].x/1000;\n\t\t\ty = pQuad->m_aPoints[v].y/1000;\n\t\t}\n\t}\n\n\n\tCProperty aProps[] = {\n\t\t{\"Pos X\", x, PROPTYPE_INT_SCROLL, -1000000, 1000000},\n\t\t{\"Pos Y\", y, PROPTYPE_INT_SCROLL, -1000000, 1000000},\n\t\t{\"Color\", Color, PROPTYPE_COLOR, -1, pEditor->m_Map.m_lEnvelopes.size()},\n\t\t{0},\n\t};\n\n\tstatic int s_aIds[NUM_PROPS] = {0};\n\tint NewVal = 0;\n\tint Prop = pEditor->DoProperties(&View, aProps, s_aIds, &NewVal);\n\tif(Prop != -1)\n\t\tpEditor->m_Map.m_Modified = true;\n\n\tif(Prop == PROP_POS_X)\n\t{\n\t\tfor(int v = 0; v < 4; v++)\n\t\t\tif(pEditor->m_SelectedPoints&(1<<v))\n\t\t\t\tpQuad->m_aPoints[v].x = NewVal*1000;\n\t}\n\tif(Prop == PROP_POS_Y)\n\t{\n\t\tfor(int v = 0; v < 4; v++)\n\t\t\tif(pEditor->m_SelectedPoints&(1<<v))\n\t\t\t\tpQuad->m_aPoints[v].y = NewVal*1000;\n\t}\n\tif(Prop == PROP_COLOR)\n\t{\n\t\tfor(int v = 0; v < 4; v++)\n\t\t{\n\t\t\tif(pEditor->m_SelectedPoints&(1<<v))\n\t\t\t{\n\t\t\t\tpQuad->m_aColors[v].r = (NewVal>>24)&0xff;\n\t\t\t\tpQuad->m_aColors[v].g = (NewVal>>16)&0xff;\n\t\t\t\tpQuad->m_aColors[v].b = (NewVal>>8)&0xff;\n\t\t\t\tpQuad->m_aColors[v].a = NewVal&0xff;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nint CEditor::PopupNewFolder(CEditor *pEditor, CUIRect View)\n{\n\tCUIRect Label, ButtonBar;\n\n\t// title\n\tView.HSplitTop(10.0f, 0, &View);\n\tView.HSplitTop(30.0f, &Label, &View);\n\tpEditor->UI()->DoLabel(&Label, \"Create new folder\", 20.0f, 0);\n\n\tView.HSplitBottom(10.0f, &View, 0);\n\tView.HSplitBottom(20.0f, &View, &ButtonBar);\n\n\tif(pEditor->m_FileDialogErrString[0] == 0)\n\t{\n\t\t// interaction box\n\t\tView.HSplitBottom(40.0f, &View, 0);\n\t\tView.VMargin(40.0f, &View);\n\t\tView.HSplitBottom(20.0f, &View, &Label);\n\t\tstatic float s_FolderBox = 0;\n\t\tpEditor->DoEditBox(&s_FolderBox, &Label, pEditor->m_FileDialogNewFolderName, sizeof(pEditor->m_FileDialogNewFolderName), 15.0f, &s_FolderBox);\n\t\tView.HSplitBottom(20.0f, &View, &Label);\n\t\tpEditor->UI()->DoLabel(&Label, \"Name:\", 10.0f, -1);\n\n\t\t// button bar\n\t\tButtonBar.VSplitLeft(30.0f, 0, &ButtonBar);\n\t\tButtonBar.VSplitLeft(110.0f, &Label, &ButtonBar);\n\t\tstatic int s_CreateButton = 0;\n\t\tif(pEditor->DoButton_Editor(&s_CreateButton, \"Create\", 0, &Label, 0, 0))\n\t\t{\n\t\t\t// create the folder\n\t\t\tif(*pEditor->m_FileDialogNewFolderName)\n\t\t\t{\n\t\t\t\tchar aBuf[512];\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"%s/%s\", pEditor->m_pFileDialogPath, pEditor->m_FileDialogNewFolderName);\n\t\t\t\tif(pEditor->Storage()->CreateFolder(aBuf, IStorage::TYPE_SAVE))\n\t\t\t\t{\n\t\t\t\t\tpEditor->FilelistPopulate(IStorage::TYPE_SAVE);\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tstr_copy(pEditor->m_FileDialogErrString, \"Unable to create the folder\", sizeof(pEditor->m_FileDialogErrString));\n\t\t\t}\n\t\t}\n\t\tButtonBar.VSplitRight(30.0f, &ButtonBar, 0);\n\t\tButtonBar.VSplitRight(110.0f, &ButtonBar, &Label);\n\t\tstatic int s_AbortButton = 0;\n\t\tif(pEditor->DoButton_Editor(&s_AbortButton, \"Abort\", 0, &Label, 0, 0))\n\t\t\treturn 1;\n\t}\n\telse\n\t{\n\t\t// error text\n\t\tView.HSplitTop(30.0f, 0, &View);\n\t\tView.VMargin(40.0f, &View);\n\t\tView.HSplitTop(20.0f, &Label, &View);\n\t\tpEditor->UI()->DoLabel(&Label, \"Error:\", 10.0f, -1);\n\t\tView.HSplitTop(20.0f, &Label, &View);\n\t\tpEditor->UI()->DoLabel(&Label, \"Unable to create the folder\", 10.0f, -1, View.w);\n\n\t\t// button\n\t\tButtonBar.VMargin(ButtonBar.w/2.0f-55.0f, &ButtonBar);\n\t\tstatic int s_CreateButton = 0;\n\t\tif(pEditor->DoButton_Editor(&s_CreateButton, \"Ok\", 0, &ButtonBar, 0, 0))\n\t\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n\nint CEditor::PopupMapInfo(CEditor *pEditor, CUIRect View)\n{\n\tCUIRect Label, ButtonBar, Button;\n\n\t// title\n\tView.HSplitTop(10.0f, 0, &View);\n\tView.HSplitTop(30.0f, &Label, &View);\n\tpEditor->UI()->DoLabel(&Label, \"Map details\", 20.0f, 0);\n\n\tView.HSplitBottom(10.0f, &View, 0);\n\tView.HSplitBottom(20.0f, &View, &ButtonBar);\n\n\tView.VMargin(40.0f, &View);\n\n\t// author box\n\tView.HSplitTop(20.0f, &Label, &View);\n\tpEditor->UI()->DoLabel(&Label, \"Author:\", 10.0f, -1);\n\tLabel.VSplitLeft(40.0f, 0, &Button);\n\tButton.HSplitTop(12.0f, &Button, 0);\n\tstatic float s_AuthorBox = 0;\n\tpEditor->DoEditBox(&s_AuthorBox, &Button, pEditor->m_Map.m_MapInfo.m_aAuthorTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aAuthorTmp), 10.0f, &s_AuthorBox);\n\n\t// version box\n\tView.HSplitTop(20.0f, &Label, &View);\n\tpEditor->UI()->DoLabel(&Label, \"Version:\", 10.0f, -1);\n\tLabel.VSplitLeft(40.0f, 0, &Button);\n\tButton.HSplitTop(12.0f, &Button, 0);\n\tstatic float s_VersionBox = 0;\n\tpEditor->DoEditBox(&s_VersionBox, &Button, pEditor->m_Map.m_MapInfo.m_aVersionTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aVersionTmp), 10.0f, &s_VersionBox);\n\n\t// credits box\n\tView.HSplitTop(20.0f, &Label, &View);\n\tpEditor->UI()->DoLabel(&Label, \"Credits:\", 10.0f, -1);\n\tLabel.VSplitLeft(40.0f, 0, &Button);\n\tButton.HSplitTop(12.0f, &Button, 0);\n\tstatic float s_CreditsBox = 0;\n\tpEditor->DoEditBox(&s_CreditsBox, &Button, pEditor->m_Map.m_MapInfo.m_aCreditsTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aCreditsTmp), 10.0f, &s_CreditsBox);\n\n\t// license box\n\tView.HSplitTop(20.0f, &Label, &View);\n\tpEditor->UI()->DoLabel(&Label, \"License:\", 10.0f, -1);\n\tLabel.VSplitLeft(40.0f, 0, &Button);\n\tButton.HSplitTop(12.0f, &Button, 0);\n\tstatic float s_LicenseBox = 0;\n\tpEditor->DoEditBox(&s_LicenseBox, &Button, pEditor->m_Map.m_MapInfo.m_aLicenseTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aLicenseTmp), 10.0f, &s_LicenseBox);\n\n\t// button bar\n\tButtonBar.VSplitLeft(30.0f, 0, &ButtonBar);\n\tButtonBar.VSplitLeft(110.0f, &Label, &ButtonBar);\n\tstatic int s_CreateButton = 0;\n\tif(pEditor->DoButton_Editor(&s_CreateButton, \"Save\", 0, &Label, 0, 0))\n\t{\n\t\tstr_copy(pEditor->m_Map.m_MapInfo.m_aAuthor, pEditor->m_Map.m_MapInfo.m_aAuthorTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aAuthor));\n\t\tstr_copy(pEditor->m_Map.m_MapInfo.m_aVersion, pEditor->m_Map.m_MapInfo.m_aVersionTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aVersion));\n\t\tstr_copy(pEditor->m_Map.m_MapInfo.m_aCredits, pEditor->m_Map.m_MapInfo.m_aCreditsTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aCredits));\n\t\tstr_copy(pEditor->m_Map.m_MapInfo.m_aLicense, pEditor->m_Map.m_MapInfo.m_aLicenseTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aLicense));\n\t\treturn 1;\n\t}\n\n\tButtonBar.VSplitRight(30.0f, &ButtonBar, 0);\n\tButtonBar.VSplitRight(110.0f, &ButtonBar, &Label);\n\tstatic int s_AbortButton = 0;\n\tif(pEditor->DoButton_Editor(&s_AbortButton, \"Abort\", 0, &Label, 0, 0))\n\t\treturn 1;\n\n\treturn 0;\n}\n\nint CEditor::PopupEvent(CEditor *pEditor, CUIRect View)\n{\n\tCUIRect Label, ButtonBar;\n\n\t// title\n\tView.HSplitTop(10.0f, 0, &View);\n\tView.HSplitTop(30.0f, &Label, &View);\n\tif(pEditor->m_PopupEventType == POPEVENT_EXIT)\n\t\tpEditor->UI()->DoLabel(&Label, \"Exit the editor\", 20.0f, 0);\n\telse if(pEditor->m_PopupEventType == POPEVENT_LOAD)\n\t\tpEditor->UI()->DoLabel(&Label, \"Load map\", 20.0f, 0);\n\telse if(pEditor->m_PopupEventType == POPEVENT_NEW)\n\t\tpEditor->UI()->DoLabel(&Label, \"New map\", 20.0f, 0);\n\telse if(pEditor->m_PopupEventType == POPEVENT_SAVE)\n\t\tpEditor->UI()->DoLabel(&Label, \"Save map\", 20.0f, 0);\n\n\tView.HSplitBottom(10.0f, &View, 0);\n\tView.HSplitBottom(20.0f, &View, &ButtonBar);\n\n\t// notification text\n\tView.HSplitTop(30.0f, 0, &View);\n\tView.VMargin(40.0f, &View);\n\tView.HSplitTop(20.0f, &Label, &View);\n\tif(pEditor->m_PopupEventType == POPEVENT_EXIT)\n\t\tpEditor->UI()->DoLabel(&Label, \"The map contains unsaved data, you might want to save it before you exit the editor.\\nContinue anyway?\", 10.0f, -1, Label.w-10.0f);\n\telse if(pEditor->m_PopupEventType == POPEVENT_LOAD)\n\t\tpEditor->UI()->DoLabel(&Label, \"The map contains unsaved data, you might want to save it before you load a new map.\\nContinue anyway?\", 10.0f, -1, Label.w-10.0f);\n\telse if(pEditor->m_PopupEventType == POPEVENT_NEW)\n\t\tpEditor->UI()->DoLabel(&Label, \"The map contains unsaved data, you might want to save it before you create a new map.\\nContinue anyway?\", 10.0f, -1, Label.w-10.0f);\n\telse if(pEditor->m_PopupEventType == POPEVENT_SAVE)\n\t\tpEditor->UI()->DoLabel(&Label, \"The file already exists.\\nDo you want to overwrite the map?\", 10.0f, -1);\n\n\t// button bar\n\tButtonBar.VSplitLeft(30.0f, 0, &ButtonBar);\n\tButtonBar.VSplitLeft(110.0f, &Label, &ButtonBar);\n\tstatic int s_OkButton = 0;\n\tif(pEditor->DoButton_Editor(&s_OkButton, \"Ok\", 0, &Label, 0, 0))\n\t{\n\t\tif(pEditor->m_PopupEventType == POPEVENT_EXIT)\n\t\t\tg_Config.m_ClEditor = 0;\n\t\telse if(pEditor->m_PopupEventType == POPEVENT_LOAD)\n\t\t\tpEditor->InvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_MAP, \"Load map\", \"Load\", \"maps\", \"\", pEditor->CallbackOpenMap, pEditor);\n\t\telse if(pEditor->m_PopupEventType == POPEVENT_NEW)\n\t\t{\n\t\t\tpEditor->Reset();\n\t\t\tpEditor->m_aFileName[0] = 0;\n\t\t}\n\t\telse if(pEditor->m_PopupEventType == POPEVENT_SAVE)\n\t\t\tpEditor->CallbackSaveMap(pEditor->m_aFileSaveName, IStorage::TYPE_SAVE, pEditor);\n\t\tpEditor->m_PopupEventWasActivated = false;\n\t\treturn 1;\n\t}\n\tButtonBar.VSplitRight(30.0f, &ButtonBar, 0);\n\tButtonBar.VSplitRight(110.0f, &ButtonBar, &Label);\n\tstatic int s_AbortButton = 0;\n\tif(pEditor->DoButton_Editor(&s_AbortButton, \"Abort\", 0, &Label, 0, 0))\n\t{\n\t\tpEditor->m_PopupEventWasActivated = false;\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n\n\nstatic int g_SelectImageSelected = -100;\nstatic int g_SelectImageCurrent = -100;\n\nint CEditor::PopupSelectImage(CEditor *pEditor, CUIRect View)\n{\n\tCUIRect ButtonBar, ImageView;\n\tView.VSplitLeft(80.0f, &ButtonBar, &View);\n\tView.Margin(10.0f, &ImageView);\n\n\tint ShowImage = g_SelectImageCurrent;\n\n\tfor(int i = -1; i < pEditor->m_Map.m_lImages.size(); i++)\n\t{\n\t\tCUIRect Button;\n\t\tButtonBar.HSplitTop(12.0f, &Button, &ButtonBar);\n\t\tButtonBar.HSplitTop(2.0f, 0, &ButtonBar);\n\n\t\tif(pEditor->UI()->MouseInside(&Button))\n\t\t\tShowImage = i;\n\n\t\tif(i == -1)\n\t\t{\n\t\t\tif(pEditor->DoButton_MenuItem(&pEditor->m_Map.m_lImages[i], \"None\", i==g_SelectImageCurrent, &Button))\n\t\t\t\tg_SelectImageSelected = -1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(pEditor->DoButton_MenuItem(&pEditor->m_Map.m_lImages[i], pEditor->m_Map.m_lImages[i]->m_aName, i==g_SelectImageCurrent, &Button))\n\t\t\t\tg_SelectImageSelected = i;\n\t\t}\n\t}\n\n\tif(ShowImage >= 0 && ShowImage < pEditor->m_Map.m_lImages.size())\n\t{\n\t\tif(ImageView.h < ImageView.w)\n\t\t\tImageView.w = ImageView.h;\n\t\telse\n\t\t\tImageView.h = ImageView.w;\n\t\tfloat Max = (float)(max(pEditor->m_Map.m_lImages[ShowImage]->m_Width, pEditor->m_Map.m_lImages[ShowImage]->m_Height));\n\t\tImageView.w *= pEditor->m_Map.m_lImages[ShowImage]->m_Width/Max;\n\t\tImageView.h *= pEditor->m_Map.m_lImages[ShowImage]->m_Height/Max;\n\t\tpEditor->Graphics()->TextureSet(pEditor->m_Map.m_lImages[ShowImage]->m_Texture);\n\t\tpEditor->Graphics()->BlendNormal();\n\t\tpEditor->Graphics()->WrapClamp();\n\t\tpEditor->Graphics()->QuadsBegin();\n\t\tIGraphics::CQuadItem QuadItem(ImageView.x, ImageView.y, ImageView.w, ImageView.h);\n\t\tpEditor->Graphics()->QuadsDrawTL(&QuadItem, 1);\n\t\tpEditor->Graphics()->QuadsEnd();\n\t\tpEditor->Graphics()->WrapNormal();\n\t}\n\n\treturn 0;\n}\n\nvoid CEditor::PopupSelectImageInvoke(int Current, float x, float y)\n{\n\tstatic int s_SelectImagePopupId = 0;\n\tg_SelectImageSelected = -100;\n\tg_SelectImageCurrent = Current;\n\tUiInvokePopupMenu(&s_SelectImagePopupId, 0, x, y, 400, 300, PopupSelectImage);\n}\n\nint CEditor::PopupSelectImageResult()\n{\n\tif(g_SelectImageSelected == -100)\n\t\treturn -100;\n\n\tg_SelectImageCurrent = g_SelectImageSelected;\n\tg_SelectImageSelected = -100;\n\treturn g_SelectImageCurrent;\n}\n\nstatic int s_GametileOpSelected = -1;\n\nint CEditor::PopupSelectGametileOp(CEditor *pEditor, CUIRect View)\n{\n\tstatic const char *s_pButtonNames[] = { \"Clear\", \"Collision\", \"Death\", \"Unhookable\" };\n\tstatic unsigned s_NumButtons = sizeof(s_pButtonNames) / sizeof(char*);\n\tCUIRect Button;\n\n\tfor(unsigned i = 0; i < s_NumButtons; ++i)\n\t{\n\t\tView.HSplitTop(2.0f, 0, &View);\n\t\tView.HSplitTop(12.0f, &Button, &View);\n\t\tif(pEditor->DoButton_Editor(&s_pButtonNames[i], s_pButtonNames[i], 0, &Button, 0, 0))\n\t\t\ts_GametileOpSelected = i;\n\t}\n\n\treturn 0;\n}\n\nvoid CEditor::PopupSelectGametileOpInvoke(float x, float y)\n{\n\tstatic int s_SelectGametileOpPopupId = 0;\n\ts_GametileOpSelected = -1;\n\tUiInvokePopupMenu(&s_SelectGametileOpPopupId, 0, x, y, 120.0f, 70.0f, PopupSelectGametileOp);\n}\n\nint CEditor::PopupSelectGameTileOpResult()\n{\n\tif(s_GametileOpSelected < 0)\n\t\treturn -1;\n\n\tint Result = s_GametileOpSelected;\n\ts_GametileOpSelected = -1;\n\treturn Result;\n}\n\nstatic bool s_AutoMapProceedOrder = false;\n\nint CEditor::PopupDoodadAutoMap(CEditor *pEditor, CUIRect View)\n{\n\tCLayerTiles *pLayer = static_cast<CLayerTiles*>(pEditor->GetSelectedLayer(0));\n\tIAutoMapper *pMapper = pEditor->m_Map.m_lImages[pLayer->m_Image]->m_pAutoMapper;\n\tCUIRect Rect;\n\n\tView.HSplitTop(15.0f, &Rect, &View);\n\n\t// ruleset selection\n\tstatic int s_ChooseDoodadRuleset = 0;\n\tif(pEditor->DoButton_Editor(&s_ChooseDoodadRuleset, pMapper->GetRuleSetName(pLayer->m_SelectedRuleSet), 0, &Rect, 0, 0))\n\t\tpEditor->UiInvokePopupMenu(&s_ChooseDoodadRuleset, 0, pEditor->UI()->MouseX(), pEditor->UI()->MouseY(),\n\t\t\t\t\t\t\t\t\t120.0f, 12.0f+14.0f*pMapper->RuleSetNum(), PopupSelectDoodadRuleSet);\n\n\tView.HMargin(3.f, &View);\n\tView.HSplitTop(15.0f, &Rect, &View);\n\n\t// Amount\n\tint s_DoodadSelectAmountButton = 0;\n\tint NewValue = pEditor->UiDoValueSelector(&s_DoodadSelectAmountButton, &Rect, \"\", pLayer->m_SelectedAmount, 1, 100, 1, 1.0f, \"Use left mouse button to drag and change the value. Hold shift to be more precise.\");\n\tif(NewValue != pLayer->m_SelectedAmount)\n\t{\n\t\tpLayer->m_SelectedAmount = NewValue;\n\t}\n\n\tView.HMargin(3.f, &View);\n\tView.HSplitTop(15.0f, &Rect, &View);\n\n\t// Generate button\n\tstatic int s_ButtonDoodadGenerate = 0;\n\tif(pEditor->DoButton_Editor(&s_ButtonDoodadGenerate, \"Generate\", 0, &Rect, 0, 0))\n\t\ts_AutoMapProceedOrder = true;\n\n\treturn 0;\n}\n\nint CEditor::PopupSelectDoodadRuleSet(CEditor *pEditor, CUIRect View)\n{\n\tCLayerTiles *pLayer = static_cast<CLayerTiles*>(pEditor->GetSelectedLayer(0));\n\tCUIRect Button;\n\tstatic int s_AutoMapperDoodadButtons[IAutoMapper::MAX_RULES];\n\tIAutoMapper *pMapper = pEditor->m_Map.m_lImages[pLayer->m_Image]->m_pAutoMapper;\n\n\tfor(int i = 0; i < pMapper->RuleSetNum(); ++i)\n\t{\n\t\tView.HSplitTop(2.0f, 0, &View);\n\t\tView.HSplitTop(12.0f, &Button, &View);\n\t\tif(pEditor->DoButton_Editor(&s_AutoMapperDoodadButtons[i], pMapper->GetRuleSetName(i), 0, &Button, 0, 0))\n\t\t{\n\t\t\tpLayer->m_SelectedRuleSet = i;\n\t\t\treturn 1; // close the popup\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nint CEditor::PopupSelectConfigAutoMap(CEditor *pEditor, CUIRect View)\n{\n\tCLayerTiles *pLayer = static_cast<CLayerTiles*>(pEditor->GetSelectedLayer(0));\n\tCUIRect Button;\n\tstatic int s_AutoMapperConfigButtons[IAutoMapper::MAX_RULES];\n\n\tfor(int i = 0; i < pEditor->m_Map.m_lImages[pLayer->m_Image]->m_pAutoMapper->RuleSetNum(); ++i)\n\t{\n\t\tView.HSplitTop(2.0f, 0, &View);\n\t\tView.HSplitTop(12.0f, &Button, &View);\n\t\tif(pEditor->DoButton_Editor(&s_AutoMapperConfigButtons[i], pEditor->m_Map.m_lImages[pLayer->m_Image]->m_pAutoMapper->GetRuleSetName(i), 0, &Button, 0, 0))\n\t\t{\n\t\t\tpLayer->m_SelectedRuleSet = i;\n\t\t\ts_AutoMapProceedOrder = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nvoid CEditor::PopupSelectConfigAutoMapInvoke(float x, float y)\n{\n\tstatic int s_AutoMapConfigSelectID = 0;\n\tCLayerTiles *pLayer = static_cast<CLayerTiles*>(GetSelectedLayer(0));\n\n\tif(pLayer && pLayer->m_Image >= 0 && pLayer->m_Image < m_Map.m_lImages.size() &&\n\t\tm_Map.m_lImages[pLayer->m_Image]->m_pAutoMapper->RuleSetNum())\n\t{\n\t\tif(m_Map.m_lImages[pLayer->m_Image]->m_pAutoMapper->GetType() == IAutoMapper::TYPE_TILESET)\n\t\t\tUiInvokePopupMenu(&s_AutoMapConfigSelectID, 0, x, y, 120.0f, 12.0f+14.0f*m_Map.m_lImages[pLayer->m_Image]->m_pAutoMapper->RuleSetNum(), PopupSelectConfigAutoMap);\n\t\telse if(m_Map.m_lImages[pLayer->m_Image]->m_pAutoMapper->GetType() == IAutoMapper::TYPE_DOODADS)\n\t\t\tUiInvokePopupMenu(&s_AutoMapConfigSelectID, 0, x, y, 120.0f, 60.0f, PopupDoodadAutoMap);\n\t}\n}\n\nbool CEditor::PopupAutoMapProceedOrder()\n{\n\tif(s_AutoMapProceedOrder)\n\t{\n\t\t// reset\n\t\ts_AutoMapProceedOrder = false;\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n"
  },
  {
    "path": "src/game/gamecore.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include \"gamecore.h\"\n\nconst char *CTuningParams::m_apNames[] =\n{\n\t#define MACRO_TUNING_PARAM(Name,ScriptName,Value) #ScriptName,\n\t#include \"tuning.h\"\n\t#undef MACRO_TUNING_PARAM\n};\n\n\nbool CTuningParams::Set(int Index, float Value)\n{\n\tif(Index < 0 || Index >= Num())\n\t\treturn false;\n\t((CTuneParam *)this)[Index] = Value;\n\treturn true;\n}\n\nbool CTuningParams::Get(int Index, float *pValue)\n{\n\tif(Index < 0 || Index >= Num())\n\t\treturn false;\n\t*pValue = (float)((CTuneParam *)this)[Index];\n\treturn true;\n}\n\nbool CTuningParams::Set(const char *pName, float Value)\n{\n\tfor(int i = 0; i < Num(); i++)\n\t\tif(str_comp_nocase(pName, m_apNames[i]) == 0)\n\t\t\treturn Set(i, Value);\n\treturn false;\n}\n\nbool CTuningParams::Get(const char *pName, float *pValue)\n{\n\tfor(int i = 0; i < Num(); i++)\n\t\tif(str_comp_nocase(pName, m_apNames[i]) == 0)\n\t\t\treturn Get(i, pValue);\n\n\treturn false;\n}\n\nfloat HermiteBasis1(float v)\n{\n\treturn 2*v*v*v - 3*v*v+1;\n}\n\nfloat VelocityRamp(float Value, float Start, float Range, float Curvature)\n{\n\tif(Value < Start)\n\t\treturn 1.0f;\n\treturn 1.0f/powf(Curvature, (Value-Start)/Range);\n}\n\nvoid CCharacterCore::Init(CWorldCore *pWorld, CCollision *pCollision)\n{\n\tm_pWorld = pWorld;\n\tm_pCollision = pCollision;\n}\n\nvoid CCharacterCore::Reset()\n{\n\tm_Pos = vec2(0,0);\n\tm_Vel = vec2(0,0);\n\tm_HookPos = vec2(0,0);\n\tm_HookDir = vec2(0,0);\n\tm_HookTick = 0;\n\tm_HookState = HOOK_IDLE;\n\tm_HookedPlayer = -1;\n\tm_Jumped = 0;\n\tm_TriggeredEvents = 0;\n}\n\nvoid CCharacterCore::Tick(bool UseInput)\n{\n\tfloat PhysSize = 28.0f;\n\tm_TriggeredEvents = 0;\n\n\t// get ground state\n\tbool Grounded = false;\n\tif(m_pCollision->CheckPoint(m_Pos.x+PhysSize/2, m_Pos.y+PhysSize/2+5))\n\t\tGrounded = true;\n\tif(m_pCollision->CheckPoint(m_Pos.x-PhysSize/2, m_Pos.y+PhysSize/2+5))\n\t\tGrounded = true;\n\n\tvec2 TargetDirection = normalize(vec2(m_Input.m_TargetX, m_Input.m_TargetY));\n\n\tm_Vel.y += m_pWorld->m_Tuning.m_Gravity;\n\n\tfloat MaxSpeed = Grounded ? m_pWorld->m_Tuning.m_GroundControlSpeed : m_pWorld->m_Tuning.m_AirControlSpeed;\n\tfloat Accel = Grounded ? m_pWorld->m_Tuning.m_GroundControlAccel : m_pWorld->m_Tuning.m_AirControlAccel;\n\tfloat Friction = Grounded ? m_pWorld->m_Tuning.m_GroundFriction : m_pWorld->m_Tuning.m_AirFriction;\n\n\t// handle input\n\tif(UseInput)\n\t{\n\t\tm_Direction = m_Input.m_Direction;\n\n\t\t// setup angle\n\t\tfloat a = 0;\n\t\tif(m_Input.m_TargetX == 0)\n\t\t\ta = atanf((float)m_Input.m_TargetY);\n\t\telse\n\t\t\ta = atanf((float)m_Input.m_TargetY/(float)m_Input.m_TargetX);\n\n\t\tif(m_Input.m_TargetX < 0)\n\t\t\ta = a+pi;\n\n\t\tm_Angle = (int)(a*256.0f);\n\n\t\t// handle jump\n\t\tif(m_Input.m_Jump)\n\t\t{\n\t\t\tif(!(m_Jumped&1))\n\t\t\t{\n\t\t\t\tif(Grounded)\n\t\t\t\t{\n\t\t\t\t\tm_TriggeredEvents |= COREEVENTFLAG_GROUND_JUMP;\n\t\t\t\t\tm_Vel.y = -m_pWorld->m_Tuning.m_GroundJumpImpulse;\n\t\t\t\t\tm_Jumped |= 1;\n\t\t\t\t}\n\t\t\t\telse if(!(m_Jumped&2))\n\t\t\t\t{\n\t\t\t\t\tm_TriggeredEvents |= COREEVENTFLAG_AIR_JUMP;\n\t\t\t\t\tm_Vel.y = -m_pWorld->m_Tuning.m_AirJumpImpulse;\n\t\t\t\t\tm_Jumped |= 3;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tm_Jumped &= ~1;\n\n\t\t// handle hook\n\t\tif(m_Input.m_Hook)\n\t\t{\n\t\t\tif(m_HookState == HOOK_IDLE)\n\t\t\t{\n\t\t\t\tm_HookState = HOOK_FLYING;\n\t\t\t\tm_HookPos = m_Pos+TargetDirection*PhysSize*1.5f;\n\t\t\t\tm_HookDir = TargetDirection;\n\t\t\t\tm_HookedPlayer = -1;\n\t\t\t\tm_HookTick = 0;\n\t\t\t\t//m_TriggeredEvents |= COREEVENTFLAG_HOOK_LAUNCH;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_HookedPlayer = -1;\n\t\t\tm_HookState = HOOK_IDLE;\n\t\t\tm_HookPos = vec2(0,0);\n\t\t\tm_HookDir = vec2(0,0);\n\t\t\tm_HookTick = 0;\n\t\t}\n\t}\n\n\t// add the speed modification according to players wanted direction\n\tif(m_Direction < 0)\n\t\tm_Vel.x = SaturatedAdd(-MaxSpeed, MaxSpeed, m_Vel.x, -Accel);\n\tif(m_Direction > 0)\n\t\tm_Vel.x = SaturatedAdd(-MaxSpeed, MaxSpeed, m_Vel.x, Accel);\n\tif(m_Direction == 0)\n\t\tm_Vel.x *= Friction;\n\n\t// handle jumping\n\t// 1 bit = to keep track if a jump has been made on this input\n\t// 2 bit = to keep track if a air-jump has been made\n\tif(Grounded)\n\t\tm_Jumped &= ~2;\n\n\t// do hook\n\tif(m_HookState == HOOK_IDLE)\n\t{\n\t\tm_HookedPlayer = -1;\n\t\tm_HookState = HOOK_IDLE;\n\t\tm_HookPos = m_Pos;\n\t}\n\telse if(m_HookState >= HOOK_RETRACT_START && m_HookState < HOOK_RETRACT_END)\n\t{\n\t\tm_HookState++;\n\t}\n\telse if(m_HookState == HOOK_RETRACT_END)\n\t{\n\t\tm_HookState = HOOK_RETRACTED;\n\t\t//m_TriggeredEvents |= COREEVENTFLAG_HOOK_RETRACT;\n\t\tm_HookState = HOOK_RETRACTED;\n\t}\n\telse if(m_HookState == HOOK_FLYING)\n\t{\n\t\tvec2 NewPos = m_HookPos+m_HookDir*m_pWorld->m_Tuning.m_HookFireSpeed;\n\t\tif(distance(m_Pos, NewPos) > m_pWorld->m_Tuning.m_HookLength)\n\t\t{\n\t\t\tm_HookState = HOOK_RETRACT_START;\n\t\t\tNewPos = m_Pos + normalize(NewPos-m_Pos) * m_pWorld->m_Tuning.m_HookLength;\n\t\t}\n\n\t\t// make sure that the hook doesn't go though the ground\n\t\tbool GoingToHitGround = false;\n\t\tbool GoingToRetract = false;\n\t\tint Hit = m_pCollision->IntersectLine(m_HookPos, NewPos, &NewPos, 0);\n\t\tif(Hit)\n\t\t{\n\t\t\tif(Hit&CCollision::COLFLAG_NOHOOK)\n\t\t\t\tGoingToRetract = true;\n\t\t\telse\n\t\t\t\tGoingToHitGround = true;\n\t\t}\n\n\t\t// Check against other players first\n\t\tif(m_pWorld && m_pWorld->m_Tuning.m_PlayerHooking)\n\t\t{\n\t\t\tfloat Distance = 0.0f;\n\t\t\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t\t\t{\n\t\t\t\tCCharacterCore *pCharCore = m_pWorld->m_apCharacters[i];\n\t\t\t\tif(!pCharCore || pCharCore == this)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tvec2 ClosestPoint = closest_point_on_line(m_HookPos, NewPos, pCharCore->m_Pos);\n\t\t\t\tif(distance(pCharCore->m_Pos, ClosestPoint) < PhysSize+2.0f)\n\t\t\t\t{\n\t\t\t\t\tif (m_HookedPlayer == -1 || distance(m_HookPos, pCharCore->m_Pos) < Distance)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_TriggeredEvents |= COREEVENTFLAG_HOOK_ATTACH_PLAYER;\n\t\t\t\t\t\tm_HookState = HOOK_GRABBED;\n\t\t\t\t\t\tm_HookedPlayer = i;\n\t\t\t\t\t\tDistance = distance(m_HookPos, pCharCore->m_Pos);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif(m_HookState == HOOK_FLYING)\n\t\t{\n\t\t\t// check against ground\n\t\t\tif(GoingToHitGround)\n\t\t\t{\n\t\t\t\tm_TriggeredEvents |= COREEVENTFLAG_HOOK_ATTACH_GROUND;\n\t\t\t\tm_HookState = HOOK_GRABBED;\n\t\t\t}\n\t\t\telse if(GoingToRetract)\n\t\t\t{\n\t\t\t\tm_TriggeredEvents |= COREEVENTFLAG_HOOK_HIT_NOHOOK;\n\t\t\t\tm_HookState = HOOK_RETRACT_START;\n\t\t\t}\n\n\t\t\tm_HookPos = NewPos;\n\t\t}\n\t}\n\n\tif(m_HookState == HOOK_GRABBED)\n\t{\n\t\tif(m_HookedPlayer != -1)\n\t\t{\n\t\t\tCCharacterCore *pCharCore = m_pWorld->m_apCharacters[m_HookedPlayer];\n\t\t\tif(pCharCore)\n\t\t\t\tm_HookPos = pCharCore->m_Pos;\n\t\t\telse\n\t\t\t{\n\t\t\t\t// release hook\n\t\t\t\tm_HookedPlayer = -1;\n\t\t\t\tm_HookState = HOOK_RETRACTED;\n\t\t\t\tm_HookPos = m_Pos;\n\t\t\t}\n\n\t\t\t// keep players hooked for a max of 1.5sec\n\t\t\t//if(Server()->Tick() > hook_tick+(Server()->TickSpeed()*3)/2)\n\t\t\t\t//release_hooked();\n\t\t}\n\n\t\t// don't do this hook rutine when we are hook to a player\n\t\tif(m_HookedPlayer == -1 && distance(m_HookPos, m_Pos) > 46.0f)\n\t\t{\n\t\t\tvec2 HookVel = normalize(m_HookPos-m_Pos)*m_pWorld->m_Tuning.m_HookDragAccel;\n\t\t\t// the hook as more power to drag you up then down.\n\t\t\t// this makes it easier to get on top of an platform\n\t\t\tif(HookVel.y > 0)\n\t\t\t\tHookVel.y *= 0.3f;\n\n\t\t\t// the hook will boost it's power if the player wants to move\n\t\t\t// in that direction. otherwise it will dampen everything abit\n\t\t\tif((HookVel.x < 0 && m_Direction < 0) || (HookVel.x > 0 && m_Direction > 0))\n\t\t\t\tHookVel.x *= 0.95f;\n\t\t\telse\n\t\t\t\tHookVel.x *= 0.75f;\n\n\t\t\tvec2 NewVel = m_Vel+HookVel;\n\n\t\t\t// check if we are under the legal limit for the hook\n\t\t\tif(length(NewVel) < m_pWorld->m_Tuning.m_HookDragSpeed || length(NewVel) < length(m_Vel))\n\t\t\t\tm_Vel = NewVel; // no problem. apply\n\n\t\t}\n\n\t\t// release hook (max hook time is 1.25\n\t\tm_HookTick++;\n\t\tif(m_HookedPlayer != -1 && (m_HookTick > SERVER_TICK_SPEED+SERVER_TICK_SPEED/5 || !m_pWorld->m_apCharacters[m_HookedPlayer]))\n\t\t{\n\t\t\tm_HookedPlayer = -1;\n\t\t\tm_HookState = HOOK_RETRACTED;\n\t\t\tm_HookPos = m_Pos;\n\t\t}\n\t}\n\n\tif(m_pWorld)\n\t{\n\t\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t\t{\n\t\t\tCCharacterCore *pCharCore = m_pWorld->m_apCharacters[i];\n\t\t\tif(!pCharCore)\n\t\t\t\tcontinue;\n\n\t\t\t//player *p = (player*)ent;\n\t\t\tif(pCharCore == this) // || !(p->flags&FLAG_ALIVE)\n\t\t\t\tcontinue; // make sure that we don't nudge our self\n\n\t\t\t// handle player <-> player collision\n\t\t\tfloat Distance = distance(m_Pos, pCharCore->m_Pos);\n\t\t\tvec2 Dir = normalize(m_Pos - pCharCore->m_Pos);\n\t\t\tif(m_pWorld->m_Tuning.m_PlayerCollision && Distance < PhysSize*1.25f && Distance > 0.0f)\n\t\t\t{\n\t\t\t\tfloat a = (PhysSize*1.45f - Distance);\n\t\t\t\tfloat Velocity = 0.5f;\n\n\t\t\t\t// make sure that we don't add excess force by checking the\n\t\t\t\t// direction against the current velocity. if not zero.\n\t\t\t\tif (length(m_Vel) > 0.0001)\n\t\t\t\t\tVelocity = 1-(dot(normalize(m_Vel), Dir)+1)/2;\n\n\t\t\t\tm_Vel += Dir*a*(Velocity*0.75f);\n\t\t\t\tm_Vel *= 0.85f;\n\t\t\t}\n\n\t\t\t// handle hook influence\n\t\t\tif(m_HookedPlayer == i && m_pWorld->m_Tuning.m_PlayerHooking)\n\t\t\t{\n\t\t\t\tif(Distance > PhysSize*1.50f) // TODO: fix tweakable variable\n\t\t\t\t{\n\t\t\t\t\tfloat Accel = m_pWorld->m_Tuning.m_HookDragAccel * (Distance/m_pWorld->m_Tuning.m_HookLength);\n\t\t\t\t\tfloat DragSpeed = m_pWorld->m_Tuning.m_HookDragSpeed;\n\n\t\t\t\t\t// add force to the hooked player\n\t\t\t\t\tpCharCore->m_Vel.x = SaturatedAdd(-DragSpeed, DragSpeed, pCharCore->m_Vel.x, Accel*Dir.x*1.5f);\n\t\t\t\t\tpCharCore->m_Vel.y = SaturatedAdd(-DragSpeed, DragSpeed, pCharCore->m_Vel.y, Accel*Dir.y*1.5f);\n\n\t\t\t\t\t// add a little bit force to the guy who has the grip\n\t\t\t\t\tm_Vel.x = SaturatedAdd(-DragSpeed, DragSpeed, m_Vel.x, -Accel*Dir.x*0.25f);\n\t\t\t\t\tm_Vel.y = SaturatedAdd(-DragSpeed, DragSpeed, m_Vel.y, -Accel*Dir.y*0.25f);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// clamp the velocity to something sane\n\tif(length(m_Vel) > 6000)\n\t\tm_Vel = normalize(m_Vel) * 6000;\n}\n\nvoid CCharacterCore::Move()\n{\n\tfloat RampValue = VelocityRamp(length(m_Vel)*50, m_pWorld->m_Tuning.m_VelrampStart, m_pWorld->m_Tuning.m_VelrampRange, m_pWorld->m_Tuning.m_VelrampCurvature);\n\n\tm_Vel.x = m_Vel.x*RampValue;\n\n\tvec2 NewPos = m_Pos;\n\tm_pCollision->MoveBox(&NewPos, &m_Vel, vec2(28.0f, 28.0f), 0);\n\n\tm_Vel.x = m_Vel.x*(1.0f/RampValue);\n\n\tif(m_pWorld && m_pWorld->m_Tuning.m_PlayerCollision)\n\t{\n\t\t// check player collision\n\t\tfloat Distance = distance(m_Pos, NewPos);\n\t\tint End = Distance+1;\n\t\tvec2 LastPos = m_Pos;\n\t\tfor(int i = 0; i < End; i++)\n\t\t{\n\t\t\tfloat a = i/Distance;\n\t\t\tvec2 Pos = mix(m_Pos, NewPos, a);\n\t\t\tfor(int p = 0; p < MAX_CLIENTS; p++)\n\t\t\t{\n\t\t\t\tCCharacterCore *pCharCore = m_pWorld->m_apCharacters[p];\n\t\t\t\tif(!pCharCore || pCharCore == this)\n\t\t\t\t\tcontinue;\n\t\t\t\tfloat D = distance(Pos, pCharCore->m_Pos);\n\t\t\t\tif(D < 28.0f && D > 0.0f)\n\t\t\t\t{\n\t\t\t\t\tif(a > 0.0f)\n\t\t\t\t\t\tm_Pos = LastPos;\n\t\t\t\t\telse if(distance(NewPos, pCharCore->m_Pos) > D)\n\t\t\t\t\t\tm_Pos = NewPos;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tLastPos = Pos;\n\t\t}\n\t}\n\n\tm_Pos = NewPos;\n}\n\nvoid CCharacterCore::Write(CNetObj_CharacterCore *pObjCore)\n{\n\tpObjCore->m_X = round(m_Pos.x);\n\tpObjCore->m_Y = round(m_Pos.y);\n\n\tpObjCore->m_VelX = round(m_Vel.x*256.0f);\n\tpObjCore->m_VelY = round(m_Vel.y*256.0f);\n\tpObjCore->m_HookState = m_HookState;\n\tpObjCore->m_HookTick = m_HookTick;\n\tpObjCore->m_HookX = round(m_HookPos.x);\n\tpObjCore->m_HookY = round(m_HookPos.y);\n\tpObjCore->m_HookedPlayer = m_HookedPlayer;\n\tpObjCore->m_Jumped = m_Jumped;\n\tpObjCore->m_Direction = m_Direction;\n\tpObjCore->m_Angle = m_Angle;\n}\n\nvoid CCharacterCore::Read(const CNetObj_CharacterCore *pObjCore)\n{\n\tm_Pos.x = pObjCore->m_X;\n\tm_Pos.y = pObjCore->m_Y;\n\tm_Vel.x = pObjCore->m_VelX/256.0f;\n\tm_Vel.y = pObjCore->m_VelY/256.0f;\n\tm_HookState = pObjCore->m_HookState;\n\tm_HookTick = pObjCore->m_HookTick;\n\tm_HookPos.x = pObjCore->m_HookX;\n\tm_HookPos.y = pObjCore->m_HookY;\n\tm_HookDir = normalize(m_HookPos-m_Pos);\n\tm_HookedPlayer = pObjCore->m_HookedPlayer;\n\tm_Jumped = pObjCore->m_Jumped;\n\tm_Direction = pObjCore->m_Direction;\n\tm_Angle = pObjCore->m_Angle;\n}\n\nvoid CCharacterCore::Quantize()\n{\n\tCNetObj_CharacterCore Core;\n\tWrite(&Core);\n\tRead(&Core);\n}\n\n"
  },
  {
    "path": "src/game/gamecore.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_GAMECORE_H\n#define GAME_GAMECORE_H\n\n#include <base/system.h>\n#include <base/math.h>\n\n#include <math.h>\n#include \"collision.h\"\n#include <engine/shared/protocol.h>\n#include <game/generated/protocol.h>\n\n\nclass CTuneParam\n{\n\tint m_Value;\npublic:\n\tvoid Set(int v) { m_Value = v; }\n\tint Get() const { return m_Value; }\n\tCTuneParam &operator = (int v) { m_Value = (int)(v*100.0f); return *this; }\n\tCTuneParam &operator = (float v) { m_Value = (int)(v*100.0f); return *this; }\n\toperator float() const { return m_Value/100.0f; }\n};\n\nclass CTuningParams\n{\npublic:\n\tCTuningParams()\n\t{\n\t\tconst float TicksPerSecond = 50.0f;\n\t\t#define MACRO_TUNING_PARAM(Name,ScriptName,Value) m_##Name.Set((int)(Value*100.0f));\n\t\t#include \"tuning.h\"\n\t\t#undef MACRO_TUNING_PARAM\n\t}\n\n\tstatic const char *m_apNames[];\n\n\t#define MACRO_TUNING_PARAM(Name,ScriptName,Value) CTuneParam m_##Name;\n\t#include \"tuning.h\"\n\t#undef MACRO_TUNING_PARAM\n\n\tstatic int Num() { return sizeof(CTuningParams)/sizeof(int); }\n\tbool Set(int Index, float Value);\n\tbool Set(const char *pName, float Value);\n\tbool Get(int Index, float *pValue);\n\tbool Get(const char *pName, float *pValue);\n};\n\n\ninline vec2 GetDirection(int Angle)\n{\n\tfloat a = Angle/256.0f;\n\treturn vec2(cosf(a), sinf(a));\n}\n\ninline vec2 GetDir(float Angle)\n{\n\treturn vec2(cosf(Angle), sinf(Angle));\n}\n\ninline float GetAngle(vec2 Dir)\n{\n\tif(Dir.x == 0 && Dir.y == 0)\n\t\treturn 0.0f;\n\tfloat a = atanf(Dir.y/Dir.x);\n\tif(Dir.x < 0)\n\t\ta = a+pi;\n\treturn a;\n}\n\ninline void StrToInts(int *pInts, int Num, const char *pStr)\n{\n\tint Index = 0;\n\twhile(Num)\n\t{\n\t\tchar aBuf[4] = {0,0,0,0};\n\t\tfor(int c = 0; c < 4 && pStr[Index]; c++, Index++)\n\t\t\taBuf[c] = pStr[Index];\n\t\t*pInts = ((aBuf[0]+128)<<24)|((aBuf[1]+128)<<16)|((aBuf[2]+128)<<8)|(aBuf[3]+128);\n\t\tpInts++;\n\t\tNum--;\n\t}\n\n\t// null terminate\n\tpInts[-1] &= 0xffffff00;\n}\n\ninline void IntsToStr(const int *pInts, int Num, char *pStr)\n{\n\twhile(Num)\n\t{\n\t\tpStr[0] = (((*pInts)>>24)&0xff)-128;\n\t\tpStr[1] = (((*pInts)>>16)&0xff)-128;\n\t\tpStr[2] = (((*pInts)>>8)&0xff)-128;\n\t\tpStr[3] = ((*pInts)&0xff)-128;\n\t\tpStr += 4;\n\t\tpInts++;\n\t\tNum--;\n\t}\n\n\t// null terminate\n\tpStr[-1] = 0;\n}\n\n\n\ninline vec2 CalcPos(vec2 Pos, vec2 Velocity, float Curvature, float Speed, float Time)\n{\n\tvec2 n;\n\tTime *= Speed;\n\tn.x = Pos.x + Velocity.x*Time;\n\tn.y = Pos.y + Velocity.y*Time + Curvature/10000*(Time*Time);\n\treturn n;\n}\n\n\ntemplate<typename T>\ninline T SaturatedAdd(T Min, T Max, T Current, T Modifier)\n{\n\tif(Modifier < 0)\n\t{\n\t\tif(Current < Min)\n\t\t\treturn Current;\n\t\tCurrent += Modifier;\n\t\tif(Current < Min)\n\t\t\tCurrent = Min;\n\t\treturn Current;\n\t}\n\telse\n\t{\n\t\tif(Current > Max)\n\t\t\treturn Current;\n\t\tCurrent += Modifier;\n\t\tif(Current > Max)\n\t\t\tCurrent = Max;\n\t\treturn Current;\n\t}\n}\n\n\nfloat VelocityRamp(float Value, float Start, float Range, float Curvature);\n\n// hooking stuff\nenum\n{\n\tHOOK_RETRACTED=-1,\n\tHOOK_IDLE=0,\n\tHOOK_RETRACT_START=1,\n\tHOOK_RETRACT_END=3,\n\tHOOK_FLYING,\n\tHOOK_GRABBED,\n};\n\nclass CWorldCore\n{\npublic:\n\tCWorldCore()\n\t{\n\t\tmem_zero(m_apCharacters, sizeof(m_apCharacters));\n\t}\n\n\tCTuningParams m_Tuning;\n\tclass CCharacterCore *m_apCharacters[MAX_CLIENTS];\n};\n\nclass CCharacterCore\n{\n\tCWorldCore *m_pWorld;\n\tCCollision *m_pCollision;\npublic:\n\tvec2 m_Pos;\n\tvec2 m_Vel;\n\n\tvec2 m_HookPos;\n\tvec2 m_HookDir;\n\tint m_HookTick;\n\tint m_HookState;\n\tint m_HookedPlayer;\n\n\tint m_Jumped;\n\n\tint m_Direction;\n\tint m_Angle;\n\tCNetObj_PlayerInput m_Input;\n\n\tint m_TriggeredEvents;\n\n\tvoid Init(CWorldCore *pWorld, CCollision *pCollision);\n\tvoid Reset();\n\tvoid Tick(bool UseInput);\n\tvoid Move();\n\n\tvoid Read(const CNetObj_CharacterCore *pObjCore);\n\tvoid Write(CNetObj_CharacterCore *pObjCore);\n\tvoid Quantize();\n};\n\n#endif\n"
  },
  {
    "path": "src/game/layers.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include \"layers.h\"\n\nCLayers::CLayers()\n{\n\tm_GroupsNum = 0;\n\tm_GroupsStart = 0;\n\tm_LayersNum = 0;\n\tm_LayersStart = 0;\n\tm_pGameGroup = 0;\n\tm_pGameLayer = 0;\n\tm_pMap = 0;\n}\n\nvoid CLayers::Init(class IKernel *pKernel, IMap *pMap)\n{\n\tm_pMap = pMap ? pMap : pKernel->RequestInterface<IMap>();\n\tm_pMap->GetType(MAPITEMTYPE_GROUP, &m_GroupsStart, &m_GroupsNum);\n\tm_pMap->GetType(MAPITEMTYPE_LAYER, &m_LayersStart, &m_LayersNum);\n\n\tfor(int g = 0; g < NumGroups(); g++)\n\t{\n\t\tCMapItemGroup *pGroup = GetGroup(g);\n\t\tfor(int l = 0; l < pGroup->m_NumLayers; l++)\n\t\t{\n\t\t\tCMapItemLayer *pLayer = GetLayer(pGroup->m_StartLayer+l);\n\n\t\t\tif(pLayer->m_Type == LAYERTYPE_TILES)\n\t\t\t{\n\t\t\t\tCMapItemLayerTilemap *pTilemap = reinterpret_cast<CMapItemLayerTilemap *>(pLayer);\n\t\t\t\tif(pTilemap->m_Flags&TILESLAYERFLAG_GAME)\n\t\t\t\t{\n\t\t\t\t\tm_pGameLayer = pTilemap;\n\t\t\t\t\tm_pGameGroup = pGroup;\n\n\t\t\t\t\t// make sure the game group has standard settings\n\t\t\t\t\tm_pGameGroup->m_OffsetX = 0;\n\t\t\t\t\tm_pGameGroup->m_OffsetY = 0;\n\t\t\t\t\tm_pGameGroup->m_ParallaxX = 100;\n\t\t\t\t\tm_pGameGroup->m_ParallaxY = 100;\n\n\t\t\t\t\tif(m_pGameGroup->m_Version >= 2)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_pGameGroup->m_UseClipping = 0;\n\t\t\t\t\t\tm_pGameGroup->m_ClipX = 0;\n\t\t\t\t\t\tm_pGameGroup->m_ClipY = 0;\n\t\t\t\t\t\tm_pGameGroup->m_ClipW = 0;\n\t\t\t\t\t\tm_pGameGroup->m_ClipH = 0;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nCMapItemGroup *CLayers::GetGroup(int Index) const\n{\n\treturn static_cast<CMapItemGroup *>(m_pMap->GetItem(m_GroupsStart+Index, 0, 0));\n}\n\nCMapItemLayer *CLayers::GetLayer(int Index) const\n{\n\treturn static_cast<CMapItemLayer *>(m_pMap->GetItem(m_LayersStart+Index, 0, 0));\n}\n"
  },
  {
    "path": "src/game/layers.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_LAYERS_H\n#define GAME_LAYERS_H\n\n#include <engine/map.h>\n#include <game/mapitems.h>\n\nclass CLayers\n{\n\tint m_GroupsNum;\n\tint m_GroupsStart;\n\tint m_LayersNum;\n\tint m_LayersStart;\n\tCMapItemGroup *m_pGameGroup;\n\tCMapItemLayerTilemap *m_pGameLayer;\n\tclass IMap *m_pMap;\n\npublic:\n\tCLayers();\n\tvoid Init(class IKernel *pKernel, class IMap *pMap=0);\n\tint NumGroups() const { return m_GroupsNum; };\n\tclass IMap *Map() const { return m_pMap; };\n\tCMapItemGroup *GameGroup() const { return m_pGameGroup; };\n\tCMapItemLayerTilemap *GameLayer() const { return m_pGameLayer; };\n\tCMapItemGroup *GetGroup(int Index) const;\n\tCMapItemLayer *GetLayer(int Index) const;\n};\n\n#endif\n"
  },
  {
    "path": "src/game/mapitems.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_MAPITEMS_H\n#define GAME_MAPITEMS_H\n\n// layer types\nenum\n{\n\tLAYERTYPE_INVALID=0,\n\tLAYERTYPE_GAME,\n\tLAYERTYPE_TILES,\n\tLAYERTYPE_QUADS,\n\n\tMAPITEMTYPE_VERSION=0,\n\tMAPITEMTYPE_INFO,\n\tMAPITEMTYPE_IMAGE,\n\tMAPITEMTYPE_ENVELOPE,\n\tMAPITEMTYPE_GROUP,\n\tMAPITEMTYPE_LAYER,\n\tMAPITEMTYPE_ENVPOINTS,\n\n\n\tCURVETYPE_STEP=0,\n\tCURVETYPE_LINEAR,\n\tCURVETYPE_SLOW,\n\tCURVETYPE_FAST,\n\tCURVETYPE_SMOOTH,\n\tNUM_CURVETYPES,\n\n\t// game layer tiles\n\tENTITY_NULL=0,\n\tENTITY_SPAWN,\n\tENTITY_SPAWN_RED,\n\tENTITY_SPAWN_BLUE,\n\tENTITY_FLAGSTAND_RED,\n\tENTITY_FLAGSTAND_BLUE,\n\tENTITY_ARMOR_1,\n\tENTITY_HEALTH_1,\n\tENTITY_WEAPON_SHOTGUN,\n\tENTITY_WEAPON_GRENADE,\n\tENTITY_POWERUP_NINJA,\n\tENTITY_WEAPON_LASER,\n\tNUM_ENTITIES,\n\n\tTILE_AIR=0,\n\tTILE_SOLID,\n\tTILE_DEATH,\n\tTILE_NOHOOK,\n\n\tTILEFLAG_VFLIP=1,\n\tTILEFLAG_HFLIP=2,\n\tTILEFLAG_OPAQUE=4,\n\tTILEFLAG_ROTATE=8,\n\n\tLAYERFLAG_DETAIL=1,\n\tTILESLAYERFLAG_GAME=1,\n\n\tENTITY_OFFSET=255-16*4,\n};\n\nstruct CPoint\n{\n\tint x, y; // 22.10 fixed point\n};\n\nstruct CColor\n{\n\tint r, g, b, a;\n};\n\nstruct CQuad\n{\n\tCPoint m_aPoints[5];\n\tCColor m_aColors[4];\n\tCPoint m_aTexcoords[4];\n\n\tint m_PosEnv;\n\tint m_PosEnvOffset;\n\n\tint m_ColorEnv;\n\tint m_ColorEnvOffset;\n};\n\nclass CTile\n{\npublic:\n\tunsigned char m_Index;\n\tunsigned char m_Flags;\n\tunsigned char m_Skip;\n\tunsigned char m_Reserved;\n};\n\nstruct CMapItemInfo\n{\n\tint m_Version;\n\tint m_Author;\n\tint m_MapVersion;\n\tint m_Credits;\n\tint m_License;\n} ;\n\nstruct CMapItemImage_v1\n{\n\tint m_Version;\n\tint m_Width;\n\tint m_Height;\n\tint m_External;\n\tint m_ImageName;\n\tint m_ImageData;\n} ;\n\nstruct CMapItemImage : public CMapItemImage_v1\n{\n\tenum { CURRENT_VERSION=2 };\n\tint m_Format;\n};\n\nstruct CMapItemGroup_v1\n{\n\tint m_Version;\n\tint m_OffsetX;\n\tint m_OffsetY;\n\tint m_ParallaxX;\n\tint m_ParallaxY;\n\n\tint m_StartLayer;\n\tint m_NumLayers;\n} ;\n\n\nstruct CMapItemGroup : public CMapItemGroup_v1\n{\n\tenum { CURRENT_VERSION=3 };\n\n\tint m_UseClipping;\n\tint m_ClipX;\n\tint m_ClipY;\n\tint m_ClipW;\n\tint m_ClipH;\n\n\tint m_aName[3];\n} ;\n\nstruct CMapItemLayer\n{\n\tint m_Version;\n\tint m_Type;\n\tint m_Flags;\n} ;\n\nstruct CMapItemLayerTilemap\n{\n\tCMapItemLayer m_Layer;\n\tint m_Version;\n\n\tint m_Width;\n\tint m_Height;\n\tint m_Flags;\n\n\tCColor m_Color;\n\tint m_ColorEnv;\n\tint m_ColorEnvOffset;\n\n\tint m_Image;\n\tint m_Data;\n\n\tint m_aName[3];\n} ;\n\nstruct CMapItemLayerQuads\n{\n\tCMapItemLayer m_Layer;\n\tint m_Version;\n\n\tint m_NumQuads;\n\tint m_Data;\n\tint m_Image;\n\n\tint m_aName[3];\n} ;\n\nstruct CMapItemVersion\n{\n\tenum { CURRENT_VERSION=1 };\n\n\tint m_Version;\n} ;\n\nstruct CEnvPoint\n{\n\tint m_Time; // in ms\n\tint m_Curvetype;\n\tint m_aValues[4]; // 1-4 depending on envelope (22.10 fixed point)\n\n\tbool operator<(const CEnvPoint &Other) { return m_Time < Other.m_Time; }\n} ;\n\nstruct CMapItemEnvelope_v1\n{\n\tint m_Version;\n\tint m_Channels;\n\tint m_StartPoint;\n\tint m_NumPoints;\n\tint m_aName[8];\n} ;\n\nstruct CMapItemEnvelope : public CMapItemEnvelope_v1\n{\n\tenum { CURRENT_VERSION=2 };\n\tint m_Synchronized;\n};\n\n#endif\n"
  },
  {
    "path": "src/game/server/alloc.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_SERVER_ALLOC_H\n#define GAME_SERVER_ALLOC_H\n\n#include <new>\n\n#define MACRO_ALLOC_HEAP() \\\n\tpublic: \\\n\tvoid *operator new(size_t Size) \\\n\t{ \\\n\t\tvoid *p = mem_alloc(Size, 1); \\\n\t\t/*dbg_msg(\"\", \"++ %p %d\", p, size);*/ \\\n\t\tmem_zero(p, Size); \\\n\t\treturn p; \\\n\t} \\\n\tvoid operator delete(void *pPtr) \\\n\t{ \\\n\t\t/*dbg_msg(\"\", \"-- %p\", p);*/ \\\n\t\tmem_free(pPtr); \\\n\t} \\\n\tprivate:\n\n#define MACRO_ALLOC_POOL_ID() \\\n\tpublic: \\\n\tvoid *operator new(size_t Size, int id); \\\n\tvoid operator delete(void *p); \\\n\tprivate:\n\n#define MACRO_ALLOC_POOL_ID_IMPL(POOLTYPE, PoolSize) \\\n\tstatic char ms_PoolData##POOLTYPE[PoolSize][sizeof(POOLTYPE)] = {{0}}; \\\n\tstatic int ms_PoolUsed##POOLTYPE[PoolSize] = {0}; \\\n\tvoid *POOLTYPE::operator new(size_t Size, int id) \\\n\t{ \\\n\t\tdbg_assert(sizeof(POOLTYPE) == Size, \"size error\"); \\\n\t\tdbg_assert(!ms_PoolUsed##POOLTYPE[id], \"already used\"); \\\n\t\t/*dbg_msg(\"pool\", \"++ %s %d\", #POOLTYPE, id);*/ \\\n\t\tms_PoolUsed##POOLTYPE[id] = 1; \\\n\t\tmem_zero(ms_PoolData##POOLTYPE[id], Size); \\\n\t\treturn ms_PoolData##POOLTYPE[id]; \\\n\t} \\\n\tvoid POOLTYPE::operator delete(void *p) \\\n\t{ \\\n\t\tint id = (POOLTYPE*)p - (POOLTYPE*)ms_PoolData##POOLTYPE; \\\n\t\tdbg_assert(ms_PoolUsed##POOLTYPE[id], \"not used\"); \\\n\t\t/*dbg_msg(\"pool\", \"-- %s %d\", #POOLTYPE, id);*/ \\\n\t\tms_PoolUsed##POOLTYPE[id] = 0; \\\n\t\tmem_zero(ms_PoolData##POOLTYPE[id], sizeof(POOLTYPE)); \\\n\t}\n\n#endif\n"
  },
  {
    "path": "src/game/server/entities/character.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/shared/config.h>\n\n#include <game/generated/server_data.h>\n#include <game/server/gamecontext.h>\n#include <game/server/gamecontroller.h>\n#include <game/server/player.h>\n\n#include \"character.h\"\n#include \"laser.h\"\n#include \"projectile.h\"\n\n//input count\nstruct CInputCount\n{\n\tint m_Presses;\n\tint m_Releases;\n};\n\nCInputCount CountInput(int Prev, int Cur)\n{\n\tCInputCount c = {0, 0};\n\tPrev &= INPUT_STATE_MASK;\n\tCur &= INPUT_STATE_MASK;\n\tint i = Prev;\n\n\twhile(i != Cur)\n\t{\n\t\ti = (i+1)&INPUT_STATE_MASK;\n\t\tif(i&1)\n\t\t\tc.m_Presses++;\n\t\telse\n\t\t\tc.m_Releases++;\n\t}\n\n\treturn c;\n}\n\n\nMACRO_ALLOC_POOL_ID_IMPL(CCharacter, MAX_CLIENTS)\n\n// Character, \"physical\" player's part\nCCharacter::CCharacter(CGameWorld *pWorld)\n: CEntity(pWorld, CGameWorld::ENTTYPE_CHARACTER)\n{\n\tm_ProximityRadius = ms_PhysSize;\n\tm_Health = 0;\n\tm_Armor = 0;\n\tm_TriggeredEvents = 0;\n}\n\nvoid CCharacter::Reset()\n{\n\tDestroy();\n}\n\nbool CCharacter::Spawn(CPlayer *pPlayer, vec2 Pos)\n{\n\tm_EmoteStop = -1;\n\tm_LastAction = -1;\n\tm_LastNoAmmoSound = -1;\n\tm_ActiveWeapon = WEAPON_GUN;\n\tm_LastWeapon = WEAPON_HAMMER;\n\tm_QueuedWeapon = -1;\n\n\tm_pPlayer = pPlayer;\n\tm_Pos = Pos;\n\n\tm_Core.Reset();\n\tm_Core.Init(&GameServer()->m_World.m_Core, GameServer()->Collision());\n\tm_Core.m_Pos = m_Pos;\n\tGameServer()->m_World.m_Core.m_apCharacters[m_pPlayer->GetCID()] = &m_Core;\n\n\tm_ReckoningTick = 0;\n\tmem_zero(&m_SendCore, sizeof(m_SendCore));\n\tmem_zero(&m_ReckoningCore, sizeof(m_ReckoningCore));\n\n\tGameServer()->m_World.InsertEntity(this);\n\tm_Alive = true;\n\n\tGameServer()->m_pController->OnCharacterSpawn(this);\n\n\treturn true;\n}\n\nvoid CCharacter::Destroy()\n{\n\tGameServer()->m_World.m_Core.m_apCharacters[m_pPlayer->GetCID()] = 0;\n\tm_Alive = false;\n}\n\nvoid CCharacter::SetWeapon(int W)\n{\n\tif(W == m_ActiveWeapon)\n\t\treturn;\n\n\tm_LastWeapon = m_ActiveWeapon;\n\tm_QueuedWeapon = -1;\n\tm_ActiveWeapon = W;\n\tGameServer()->CreateSound(m_Pos, SOUND_WEAPON_SWITCH);\n\n\tif(m_ActiveWeapon < 0 || m_ActiveWeapon >= NUM_WEAPONS)\n\t\tm_ActiveWeapon = 0;\n}\n\nbool CCharacter::IsGrounded()\n{\n\tif(GameServer()->Collision()->CheckPoint(m_Pos.x+m_ProximityRadius/2, m_Pos.y+m_ProximityRadius/2+5))\n\t\treturn true;\n\tif(GameServer()->Collision()->CheckPoint(m_Pos.x-m_ProximityRadius/2, m_Pos.y+m_ProximityRadius/2+5))\n\t\treturn true;\n\treturn false;\n}\n\n\nvoid CCharacter::HandleNinja()\n{\n\tif(m_ActiveWeapon != WEAPON_NINJA)\n\t\treturn;\n\n\tif ((Server()->Tick() - m_Ninja.m_ActivationTick) > (g_pData->m_Weapons.m_Ninja.m_Duration * Server()->TickSpeed() / 1000))\n\t{\n\t\t// time's up, return\n\t\tm_aWeapons[WEAPON_NINJA].m_Got = false;\n\t\tm_ActiveWeapon = m_LastWeapon;\n\n\t\tSetWeapon(m_ActiveWeapon);\n\t\treturn;\n\t}\n\n\t// force ninja Weapon\n\tSetWeapon(WEAPON_NINJA);\n\n\tm_Ninja.m_CurrentMoveTime--;\n\n\tif (m_Ninja.m_CurrentMoveTime == 0)\n\t{\n\t\t// reset velocity\n\t\tm_Core.m_Vel = m_Ninja.m_ActivationDir*m_Ninja.m_OldVelAmount;\n\t}\n\n\tif (m_Ninja.m_CurrentMoveTime > 0)\n\t{\n\t\t// Set velocity\n\t\tm_Core.m_Vel = m_Ninja.m_ActivationDir * g_pData->m_Weapons.m_Ninja.m_Velocity;\n\t\tvec2 OldPos = m_Pos;\n\t\tGameServer()->Collision()->MoveBox(&m_Core.m_Pos, &m_Core.m_Vel, vec2(m_ProximityRadius, m_ProximityRadius), 0.f);\n\n\t\t// reset velocity so the client doesn't predict stuff\n\t\tm_Core.m_Vel = vec2(0.f, 0.f);\n\n\t\t// check if we Hit anything along the way\n\t\t{\n\t\t\tCCharacter *aEnts[MAX_CLIENTS];\n\t\t\tvec2 Dir = m_Pos - OldPos;\n\t\t\tfloat Radius = m_ProximityRadius * 2.0f;\n\t\t\tvec2 Center = OldPos + Dir * 0.5f;\n\t\t\tint Num = GameServer()->m_World.FindEntities(Center, Radius, (CEntity**)aEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER);\n\n\t\t\tfor (int i = 0; i < Num; ++i)\n\t\t\t{\n\t\t\t\tif (aEnts[i] == this)\n\t\t\t\t\tcontinue;\n\n\t\t\t\t// make sure we haven't Hit this object before\n\t\t\t\tbool bAlreadyHit = false;\n\t\t\t\tfor (int j = 0; j < m_NumObjectsHit; j++)\n\t\t\t\t{\n\t\t\t\t\tif (m_apHitObjects[j] == aEnts[i])\n\t\t\t\t\t\tbAlreadyHit = true;\n\t\t\t\t}\n\t\t\t\tif (bAlreadyHit)\n\t\t\t\t\tcontinue;\n\n\t\t\t\t// check so we are sufficiently close\n\t\t\t\tif (distance(aEnts[i]->m_Pos, m_Pos) > (m_ProximityRadius * 2.0f))\n\t\t\t\t\tcontinue;\n\n\t\t\t\t// Hit a player, give him damage and stuffs...\n\t\t\t\tGameServer()->CreateSound(aEnts[i]->m_Pos, SOUND_NINJA_HIT);\n\t\t\t\t// set his velocity to fast upward (for now)\n\t\t\t\tif(m_NumObjectsHit < 10)\n\t\t\t\t\tm_apHitObjects[m_NumObjectsHit++] = aEnts[i];\n\n\t\t\t\taEnts[i]->TakeDamage(vec2(0, -10.0f), g_pData->m_Weapons.m_Ninja.m_pBase->m_Damage, m_pPlayer->GetCID(), WEAPON_NINJA);\n\t\t\t}\n\t\t}\n\n\t\treturn;\n\t}\n\n\treturn;\n}\n\n\nvoid CCharacter::DoWeaponSwitch()\n{\n\t// make sure we can switch\n\tif(m_ReloadTimer != 0 || m_QueuedWeapon == -1 || m_aWeapons[WEAPON_NINJA].m_Got)\n\t\treturn;\n\n\t// switch Weapon\n\tSetWeapon(m_QueuedWeapon);\n}\n\nvoid CCharacter::HandleWeaponSwitch()\n{\n\tint WantedWeapon = m_ActiveWeapon;\n\tif(m_QueuedWeapon != -1)\n\t\tWantedWeapon = m_QueuedWeapon;\n\n\t// select Weapon\n\tint Next = CountInput(m_LatestPrevInput.m_NextWeapon, m_LatestInput.m_NextWeapon).m_Presses;\n\tint Prev = CountInput(m_LatestPrevInput.m_PrevWeapon, m_LatestInput.m_PrevWeapon).m_Presses;\n\n\tif(Next < 128) // make sure we only try sane stuff\n\t{\n\t\twhile(Next) // Next Weapon selection\n\t\t{\n\t\t\tWantedWeapon = (WantedWeapon+1)%NUM_WEAPONS;\n\t\t\tif(m_aWeapons[WantedWeapon].m_Got)\n\t\t\t\tNext--;\n\t\t}\n\t}\n\n\tif(Prev < 128) // make sure we only try sane stuff\n\t{\n\t\twhile(Prev) // Prev Weapon selection\n\t\t{\n\t\t\tWantedWeapon = (WantedWeapon-1)<0?NUM_WEAPONS-1:WantedWeapon-1;\n\t\t\tif(m_aWeapons[WantedWeapon].m_Got)\n\t\t\t\tPrev--;\n\t\t}\n\t}\n\n\t// Direct Weapon selection\n\tif(m_LatestInput.m_WantedWeapon)\n\t\tWantedWeapon = m_Input.m_WantedWeapon-1;\n\n\t// check for insane values\n\tif(WantedWeapon >= 0 && WantedWeapon < NUM_WEAPONS && WantedWeapon != m_ActiveWeapon && m_aWeapons[WantedWeapon].m_Got)\n\t\tm_QueuedWeapon = WantedWeapon;\n\n\tDoWeaponSwitch();\n}\n\nvoid CCharacter::FireWeapon()\n{\n\tif(m_ReloadTimer != 0)\n\t\treturn;\n\n\tDoWeaponSwitch();\n\tvec2 Direction = normalize(vec2(m_LatestInput.m_TargetX, m_LatestInput.m_TargetY));\n\n\tbool FullAuto = false;\n\tif(m_ActiveWeapon == WEAPON_GRENADE || m_ActiveWeapon == WEAPON_SHOTGUN || m_ActiveWeapon == WEAPON_LASER)\n\t\tFullAuto = true;\n\n\n\t// check if we gonna fire\n\tbool WillFire = false;\n\tif(CountInput(m_LatestPrevInput.m_Fire, m_LatestInput.m_Fire).m_Presses)\n\t\tWillFire = true;\n\n\tif(FullAuto && (m_LatestInput.m_Fire&1) && m_aWeapons[m_ActiveWeapon].m_Ammo)\n\t\tWillFire = true;\n\n\tif(!WillFire)\n\t\treturn;\n\n\t// check for ammo\n\tif(!m_aWeapons[m_ActiveWeapon].m_Ammo)\n\t{\n\t\t// 125ms is a magical limit of how fast a human can click\n\t\tm_ReloadTimer = 125 * Server()->TickSpeed() / 1000;\n\t\tif(m_LastNoAmmoSound+Server()->TickSpeed() <= Server()->Tick())\n\t\t{\n\t\t\tGameServer()->CreateSound(m_Pos, SOUND_WEAPON_NOAMMO);\n\t\t\tm_LastNoAmmoSound = Server()->Tick();\n\t\t}\n\t\treturn;\n\t}\n\n\tvec2 ProjStartPos = m_Pos+Direction*m_ProximityRadius*0.75f;\n\n\tswitch(m_ActiveWeapon)\n\t{\n\t\tcase WEAPON_HAMMER:\n\t\t{\n\t\t\t// reset objects Hit\n\t\t\tm_NumObjectsHit = 0;\n\t\t\tGameServer()->CreateSound(m_Pos, SOUND_HAMMER_FIRE);\n\n\t\t\tCCharacter *apEnts[MAX_CLIENTS];\n\t\t\tint Hits = 0;\n\t\t\tint Num = GameServer()->m_World.FindEntities(ProjStartPos, m_ProximityRadius*0.5f, (CEntity**)apEnts,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tMAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER);\n\n\t\t\tfor (int i = 0; i < Num; ++i)\n\t\t\t{\n\t\t\t\tCCharacter *pTarget = apEnts[i];\n\n\t\t\t\tif ((pTarget == this) || GameServer()->Collision()->IntersectLine(ProjStartPos, pTarget->m_Pos, NULL, NULL))\n\t\t\t\t\tcontinue;\n\n\t\t\t\t// set his velocity to fast upward (for now)\n\t\t\t\tif(length(pTarget->m_Pos-ProjStartPos) > 0.0f)\n\t\t\t\t\tGameServer()->CreateHammerHit(pTarget->m_Pos-normalize(pTarget->m_Pos-ProjStartPos)*m_ProximityRadius*0.5f);\n\t\t\t\telse\n\t\t\t\t\tGameServer()->CreateHammerHit(ProjStartPos);\n\n\t\t\t\tvec2 Dir;\n\t\t\t\tif (length(pTarget->m_Pos - m_Pos) > 0.0f)\n\t\t\t\t\tDir = normalize(pTarget->m_Pos - m_Pos);\n\t\t\t\telse\n\t\t\t\t\tDir = vec2(0.f, -1.f);\n\n\t\t\t\tpTarget->TakeDamage(vec2(0.f, -1.f) + normalize(Dir + vec2(0.f, -1.1f)) * 10.0f, g_pData->m_Weapons.m_Hammer.m_pBase->m_Damage,\n\t\t\t\t\tm_pPlayer->GetCID(), m_ActiveWeapon);\n\t\t\t\tHits++;\n\t\t\t}\n\n\t\t\t// if we Hit anything, we have to wait for the reload\n\t\t\tif(Hits)\n\t\t\t\tm_ReloadTimer = Server()->TickSpeed()/3;\n\n\t\t} break;\n\n\t\tcase WEAPON_GUN:\n\t\t{\n\t\t\tCProjectile *pProj = new CProjectile(GameWorld(), WEAPON_GUN,\n\t\t\t\tm_pPlayer->GetCID(),\n\t\t\t\tProjStartPos,\n\t\t\t\tDirection,\n\t\t\t\t(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GunLifetime),\n\t\t\t\t1, 0, 0, -1, WEAPON_GUN);\n\n\t\t\t// pack the Projectile and send it to the client Directly\n\t\t\tCNetObj_Projectile p;\n\t\t\tpProj->FillInfo(&p);\n\n\t\t\tCMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE);\n\t\t\tMsg.AddInt(1);\n\t\t\tfor(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++)\n\t\t\t\tMsg.AddInt(((int *)&p)[i]);\n\n\t\t\tServer()->SendMsg(&Msg, 0, m_pPlayer->GetCID());\n\n\t\t\tGameServer()->CreateSound(m_Pos, SOUND_GUN_FIRE);\n\t\t} break;\n\n\t\tcase WEAPON_SHOTGUN:\n\t\t{\n\t\t\tint ShotSpread = 2;\n\n\t\t\tCMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE);\n\t\t\tMsg.AddInt(ShotSpread*2+1);\n\n\t\t\tfor(int i = -ShotSpread; i <= ShotSpread; ++i)\n\t\t\t{\n\t\t\t\tfloat Spreading[] = {-0.185f, -0.070f, 0, 0.070f, 0.185f};\n\t\t\t\tfloat a = GetAngle(Direction);\n\t\t\t\ta += Spreading[i+2];\n\t\t\t\tfloat v = 1-(absolute(i)/(float)ShotSpread);\n\t\t\t\tfloat Speed = mix((float)GameServer()->Tuning()->m_ShotgunSpeeddiff, 1.0f, v);\n\t\t\t\tCProjectile *pProj = new CProjectile(GameWorld(), WEAPON_SHOTGUN,\n\t\t\t\t\tm_pPlayer->GetCID(),\n\t\t\t\t\tProjStartPos,\n\t\t\t\t\tvec2(cosf(a), sinf(a))*Speed,\n\t\t\t\t\t(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_ShotgunLifetime),\n\t\t\t\t\t1, 0, 0, -1, WEAPON_SHOTGUN);\n\n\t\t\t\t// pack the Projectile and send it to the client Directly\n\t\t\t\tCNetObj_Projectile p;\n\t\t\t\tpProj->FillInfo(&p);\n\n\t\t\t\tfor(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++)\n\t\t\t\t\tMsg.AddInt(((int *)&p)[i]);\n\t\t\t}\n\n\t\t\tServer()->SendMsg(&Msg, 0,m_pPlayer->GetCID());\n\n\t\t\tGameServer()->CreateSound(m_Pos, SOUND_SHOTGUN_FIRE);\n\t\t} break;\n\n\t\tcase WEAPON_GRENADE:\n\t\t{\n\t\t\tCProjectile *pProj = new CProjectile(GameWorld(), WEAPON_GRENADE,\n\t\t\t\tm_pPlayer->GetCID(),\n\t\t\t\tProjStartPos,\n\t\t\t\tDirection,\n\t\t\t\t(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GrenadeLifetime),\n\t\t\t\t1, true, 0, SOUND_GRENADE_EXPLODE, WEAPON_GRENADE);\n\n\t\t\t// pack the Projectile and send it to the client Directly\n\t\t\tCNetObj_Projectile p;\n\t\t\tpProj->FillInfo(&p);\n\n\t\t\tCMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE);\n\t\t\tMsg.AddInt(1);\n\t\t\tfor(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++)\n\t\t\t\tMsg.AddInt(((int *)&p)[i]);\n\t\t\tServer()->SendMsg(&Msg, 0, m_pPlayer->GetCID());\n\n\t\t\tGameServer()->CreateSound(m_Pos, SOUND_GRENADE_FIRE);\n\t\t} break;\n\n\t\tcase WEAPON_LASER:\n\t\t{\n\t\t\tnew CLaser(GameWorld(), m_Pos, Direction, GameServer()->Tuning()->m_LaserReach, m_pPlayer->GetCID());\n\t\t\tGameServer()->CreateSound(m_Pos, SOUND_LASER_FIRE);\n\t\t} break;\n\n\t\tcase WEAPON_NINJA:\n\t\t{\n\t\t\t// reset Hit objects\n\t\t\tm_NumObjectsHit = 0;\n\n\t\t\tm_Ninja.m_ActivationDir = Direction;\n\t\t\tm_Ninja.m_CurrentMoveTime = g_pData->m_Weapons.m_Ninja.m_Movetime * Server()->TickSpeed() / 1000;\n\t\t\tm_Ninja.m_OldVelAmount = length(m_Core.m_Vel);\n\n\t\t\tGameServer()->CreateSound(m_Pos, SOUND_NINJA_FIRE);\n\t\t} break;\n\n\t}\n\n\tm_AttackTick = Server()->Tick();\n\n\tif(m_aWeapons[m_ActiveWeapon].m_Ammo > 0) // -1 == unlimited\n\t\tm_aWeapons[m_ActiveWeapon].m_Ammo--;\n\n\tif(!m_ReloadTimer)\n\t\tm_ReloadTimer = g_pData->m_Weapons.m_aId[m_ActiveWeapon].m_Firedelay * Server()->TickSpeed() / 1000;\n}\n\nvoid CCharacter::HandleWeapons()\n{\n\t//ninja\n\tHandleNinja();\n\n\t// check reload timer\n\tif(m_ReloadTimer)\n\t{\n\t\tm_ReloadTimer--;\n\t\treturn;\n\t}\n\n\t// fire Weapon, if wanted\n\tFireWeapon();\n\n\t// ammo regen\n\tint AmmoRegenTime = g_pData->m_Weapons.m_aId[m_ActiveWeapon].m_Ammoregentime;\n\tif(AmmoRegenTime)\n\t{\n\t\t// If equipped and not active, regen ammo?\n\t\tif (m_ReloadTimer <= 0)\n\t\t{\n\t\t\tif (m_aWeapons[m_ActiveWeapon].m_AmmoRegenStart < 0)\n\t\t\t\tm_aWeapons[m_ActiveWeapon].m_AmmoRegenStart = Server()->Tick();\n\n\t\t\tif ((Server()->Tick() - m_aWeapons[m_ActiveWeapon].m_AmmoRegenStart) >= AmmoRegenTime * Server()->TickSpeed() / 1000)\n\t\t\t{\n\t\t\t\t// Add some ammo\n\t\t\t\tm_aWeapons[m_ActiveWeapon].m_Ammo = min(m_aWeapons[m_ActiveWeapon].m_Ammo + 1, 10);\n\t\t\t\tm_aWeapons[m_ActiveWeapon].m_AmmoRegenStart = -1;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_aWeapons[m_ActiveWeapon].m_AmmoRegenStart = -1;\n\t\t}\n\t}\n\n\treturn;\n}\n\nbool CCharacter::GiveWeapon(int Weapon, int Ammo)\n{\n\tif(m_aWeapons[Weapon].m_Ammo < g_pData->m_Weapons.m_aId[Weapon].m_Maxammo || !m_aWeapons[Weapon].m_Got)\n\t{\n\t\tm_aWeapons[Weapon].m_Got = true;\n\t\tm_aWeapons[Weapon].m_Ammo = min(g_pData->m_Weapons.m_aId[Weapon].m_Maxammo, Ammo);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid CCharacter::GiveNinja()\n{\n\tm_Ninja.m_ActivationTick = Server()->Tick();\n\tm_aWeapons[WEAPON_NINJA].m_Got = true;\n\tm_aWeapons[WEAPON_NINJA].m_Ammo = -1;\n\tif (m_ActiveWeapon != WEAPON_NINJA)\n\t\tm_LastWeapon = m_ActiveWeapon;\n\tm_ActiveWeapon = WEAPON_NINJA;\n\n\tGameServer()->CreateSound(m_Pos, SOUND_PICKUP_NINJA);\n}\n\nvoid CCharacter::SetEmote(int Emote, int Tick)\n{\n\tm_EmoteType = Emote;\n\tm_EmoteStop = Tick;\n}\n\nvoid CCharacter::OnPredictedInput(CNetObj_PlayerInput *pNewInput)\n{\n\t// check for changes\n\tif(mem_comp(&m_Input, pNewInput, sizeof(CNetObj_PlayerInput)) != 0)\n\t\tm_LastAction = Server()->Tick();\n\n\t// copy new input\n\tmem_copy(&m_Input, pNewInput, sizeof(m_Input));\n\tm_NumInputs++;\n\n\t// it is not allowed to aim in the center\n\tif(m_Input.m_TargetX == 0 && m_Input.m_TargetY == 0)\n\t\tm_Input.m_TargetY = -1;\n}\n\nvoid CCharacter::OnDirectInput(CNetObj_PlayerInput *pNewInput)\n{\n\tmem_copy(&m_LatestPrevInput, &m_LatestInput, sizeof(m_LatestInput));\n\tmem_copy(&m_LatestInput, pNewInput, sizeof(m_LatestInput));\n\n\t// it is not allowed to aim in the center\n\tif(m_LatestInput.m_TargetX == 0 && m_LatestInput.m_TargetY == 0)\n\t\tm_LatestInput.m_TargetY = -1;\n\n\tif(m_NumInputs > 2 && m_pPlayer->GetTeam() != TEAM_SPECTATORS)\n\t{\n\t\tHandleWeaponSwitch();\n\t\tFireWeapon();\n\t}\n\n\tmem_copy(&m_LatestPrevInput, &m_LatestInput, sizeof(m_LatestInput));\n}\n\nvoid CCharacter::ResetInput()\n{\n\tm_Input.m_Direction = 0;\n\tm_Input.m_Hook = 0;\n\t// simulate releasing the fire button\n\tif((m_Input.m_Fire&1) != 0)\n\t\tm_Input.m_Fire++;\n\tm_Input.m_Fire &= INPUT_STATE_MASK;\n\tm_Input.m_Jump = 0;\n\tm_LatestPrevInput = m_LatestInput = m_Input;\n}\n\nvoid CCharacter::Tick()\n{\n\tm_Core.m_Input = m_Input;\n\tm_Core.Tick(true);\n\n\t// handle death-tiles and leaving gamelayer\n\tif(GameServer()->Collision()->GetCollisionAt(m_Pos.x+m_ProximityRadius/3.f, m_Pos.y-m_ProximityRadius/3.f)&CCollision::COLFLAG_DEATH ||\n\t\tGameServer()->Collision()->GetCollisionAt(m_Pos.x+m_ProximityRadius/3.f, m_Pos.y+m_ProximityRadius/3.f)&CCollision::COLFLAG_DEATH ||\n\t\tGameServer()->Collision()->GetCollisionAt(m_Pos.x-m_ProximityRadius/3.f, m_Pos.y-m_ProximityRadius/3.f)&CCollision::COLFLAG_DEATH ||\n\t\tGameServer()->Collision()->GetCollisionAt(m_Pos.x-m_ProximityRadius/3.f, m_Pos.y+m_ProximityRadius/3.f)&CCollision::COLFLAG_DEATH ||\n\t\tGameLayerClipped(m_Pos))\n\t{\n\t\tDie(m_pPlayer->GetCID(), WEAPON_WORLD);\n\t}\n\n\t// handle Weapons\n\tHandleWeapons();\n\n\t// Previnput\n\tm_PrevInput = m_Input;\n\treturn;\n}\n\nvoid CCharacter::TickDefered()\n{\n\t// advance the dummy\n\t{\n\t\tCWorldCore TempWorld;\n\t\tm_ReckoningCore.Init(&TempWorld, GameServer()->Collision());\n\t\tm_ReckoningCore.Tick(false);\n\t\tm_ReckoningCore.Move();\n\t\tm_ReckoningCore.Quantize();\n\t}\n\n\t//lastsentcore\n\tvec2 StartPos = m_Core.m_Pos;\n\tvec2 StartVel = m_Core.m_Vel;\n\tbool StuckBefore = GameServer()->Collision()->TestBox(m_Core.m_Pos, vec2(28.0f, 28.0f));\n\n\tm_Core.Move();\n\tbool StuckAfterMove = GameServer()->Collision()->TestBox(m_Core.m_Pos, vec2(28.0f, 28.0f));\n\tm_Core.Quantize();\n\tbool StuckAfterQuant = GameServer()->Collision()->TestBox(m_Core.m_Pos, vec2(28.0f, 28.0f));\n\tm_Pos = m_Core.m_Pos;\n\n\tif(!StuckBefore && (StuckAfterMove || StuckAfterQuant))\n\t{\n\t\t// Hackish solution to get rid of strict-aliasing warning\n\t\tunion\n\t\t{\n\t\t\tfloat f;\n\t\t\tunsigned u;\n\t\t}StartPosX, StartPosY, StartVelX, StartVelY;\n\n\t\tStartPosX.f = StartPos.x;\n\t\tStartPosY.f = StartPos.y;\n\t\tStartVelX.f = StartVel.x;\n\t\tStartVelY.f = StartVel.y;\n\n\t\tchar aBuf[256];\n\t\tstr_format(aBuf, sizeof(aBuf), \"STUCK!!! %d %d %d %f %f %f %f %x %x %x %x\",\n\t\t\tStuckBefore,\n\t\t\tStuckAfterMove,\n\t\t\tStuckAfterQuant,\n\t\t\tStartPos.x, StartPos.y,\n\t\t\tStartVel.x, StartVel.y,\n\t\t\tStartPosX.u, StartPosY.u,\n\t\t\tStartVelX.u, StartVelY.u);\n\t\tGameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"game\", aBuf);\n\t}\n\t\n\tm_TriggeredEvents |= m_Core.m_TriggeredEvents;\n\n\tif(m_pPlayer->GetTeam() == TEAM_SPECTATORS)\n\t{\n\t\tm_Pos.x = m_Input.m_TargetX;\n\t\tm_Pos.y = m_Input.m_TargetY;\n\t}\n\n\t// update the m_SendCore if needed\n\t{\n\t\tCNetObj_Character Predicted;\n\t\tCNetObj_Character Current;\n\t\tmem_zero(&Predicted, sizeof(Predicted));\n\t\tmem_zero(&Current, sizeof(Current));\n\t\tm_ReckoningCore.Write(&Predicted);\n\t\tm_Core.Write(&Current);\n\n\t\t// only allow dead reackoning for a top of 3 seconds\n\t\tif(m_ReckoningTick+Server()->TickSpeed()*3 < Server()->Tick() || mem_comp(&Predicted, &Current, sizeof(CNetObj_Character)) != 0)\n\t\t{\n\t\t\tm_ReckoningTick = Server()->Tick();\n\t\t\tm_SendCore = m_Core;\n\t\t\tm_ReckoningCore = m_Core;\n\t\t}\n\t}\n}\n\nvoid CCharacter::TickPaused()\n{\n\t++m_AttackTick;\n\t++m_DamageTakenTick;\n\t++m_Ninja.m_ActivationTick;\n\t++m_ReckoningTick;\n\tif(m_LastAction != -1)\n\t\t++m_LastAction;\n\tif(m_aWeapons[m_ActiveWeapon].m_AmmoRegenStart > -1)\n\t\t++m_aWeapons[m_ActiveWeapon].m_AmmoRegenStart;\n\tif(m_EmoteStop > -1)\n\t\t++m_EmoteStop;\n}\n\nbool CCharacter::IncreaseHealth(int Amount)\n{\n\tif(m_Health >= 10)\n\t\treturn false;\n\tm_Health = clamp(m_Health+Amount, 0, 10);\n\treturn true;\n}\n\nbool CCharacter::IncreaseArmor(int Amount)\n{\n\tif(m_Armor >= 10)\n\t\treturn false;\n\tm_Armor = clamp(m_Armor+Amount, 0, 10);\n\treturn true;\n}\n\nvoid CCharacter::Die(int Killer, int Weapon)\n{\n\t// we got to wait 0.5 secs before respawning\n\tm_Alive = false;\n\tm_pPlayer->m_RespawnTick = Server()->Tick()+Server()->TickSpeed()/2;\n\tint ModeSpecial = GameServer()->m_pController->OnCharacterDeath(this, GameServer()->m_apPlayers[Killer], Weapon);\n\n\tchar aBuf[256];\n\tstr_format(aBuf, sizeof(aBuf), \"kill killer='%d:%s' victim='%d:%s' weapon=%d special=%d\",\n\t\tKiller, Server()->ClientName(Killer),\n\t\tm_pPlayer->GetCID(), Server()->ClientName(m_pPlayer->GetCID()), Weapon, ModeSpecial);\n\tGameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"game\", aBuf);\n\n\t// send the kill message\n\tCNetMsg_Sv_KillMsg Msg;\n\tMsg.m_Killer = Killer;\n\tMsg.m_Victim = m_pPlayer->GetCID();\n\tMsg.m_Weapon = Weapon;\n\tMsg.m_ModeSpecial = ModeSpecial;\n\tServer()->SendPackMsg(&Msg, MSGFLAG_VITAL, -1);\n\n\t// a nice sound\n\tGameServer()->CreateSound(m_Pos, SOUND_PLAYER_DIE);\n\n\t// this is for auto respawn after 3 secs\n\tm_pPlayer->m_DieTick = Server()->Tick();\n\n\tGameServer()->m_World.RemoveEntity(this);\n\tGameServer()->m_World.m_Core.m_apCharacters[m_pPlayer->GetCID()] = 0;\n\tGameServer()->CreateDeath(m_Pos, m_pPlayer->GetCID());\n}\n\nbool CCharacter::TakeDamage(vec2 Force, int Dmg, int From, int Weapon)\n{\n\tm_Core.m_Vel += Force;\n\n\tif(GameServer()->m_pController->IsFriendlyFire(m_pPlayer->GetCID(), From))\n\t\treturn false;\n\n\t// m_pPlayer only inflicts half damage on self\n\tif(From == m_pPlayer->GetCID())\n\t\tDmg = max(1, Dmg/2);\n\n\tm_DamageTaken++;\n\n\t// create healthmod indicator\n\tif(Server()->Tick() < m_DamageTakenTick+25)\n\t{\n\t\t// make sure that the damage indicators doesn't group together\n\t\tGameServer()->CreateDamageInd(m_Pos, m_DamageTaken*0.25f, Dmg);\n\t}\n\telse\n\t{\n\t\tm_DamageTaken = 0;\n\t\tGameServer()->CreateDamageInd(m_Pos, 0, Dmg);\n\t}\n\n\tif(Dmg)\n\t{\n\t\tif(m_Armor)\n\t\t{\n\t\t\tif(Dmg > 1)\n\t\t\t{\n\t\t\t\tm_Health--;\n\t\t\t\tDmg--;\n\t\t\t}\n\n\t\t\tif(Dmg > m_Armor)\n\t\t\t{\n\t\t\t\tDmg -= m_Armor;\n\t\t\t\tm_Armor = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_Armor -= Dmg;\n\t\t\t\tDmg = 0;\n\t\t\t}\n\t\t}\n\n\t\tm_Health -= Dmg;\n\t}\n\n\tm_DamageTakenTick = Server()->Tick();\n\n\t// do damage Hit sound\n\tif(From >= 0 && From != m_pPlayer->GetCID() && GameServer()->m_apPlayers[From])\n\t{\n\t\tint Mask = CmaskOne(From);\n\t\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t\t{\n\t\t\tif(GameServer()->m_apPlayers[i] && (GameServer()->m_apPlayers[i]->GetTeam() == TEAM_SPECTATORS ||  GameServer()->m_apPlayers[i]->m_DeadSpecMode) &&\n\t\t\t\tGameServer()->m_apPlayers[i]->GetSpectatorID() == From)\n\t\t\t\tMask |= CmaskOne(i);\n\t\t}\n\t\tGameServer()->CreateSound(GameServer()->m_apPlayers[From]->m_ViewPos, SOUND_HIT, Mask);\n\t}\n\n\t// check for death\n\tif(m_Health <= 0)\n\t{\n\t\tDie(From, Weapon);\n\n\t\t// set attacker's face to happy (taunt!)\n\t\tif (From >= 0 && From != m_pPlayer->GetCID() && GameServer()->m_apPlayers[From])\n\t\t{\n\t\t\tCCharacter *pChr = GameServer()->m_apPlayers[From]->GetCharacter();\n\t\t\tif (pChr)\n\t\t\t{\n\t\t\t\tpChr->m_EmoteType = EMOTE_HAPPY;\n\t\t\t\tpChr->m_EmoteStop = Server()->Tick() + Server()->TickSpeed();\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tif (Dmg > 2)\n\t\tGameServer()->CreateSound(m_Pos, SOUND_PLAYER_PAIN_LONG);\n\telse\n\t\tGameServer()->CreateSound(m_Pos, SOUND_PLAYER_PAIN_SHORT);\n\n\tm_EmoteType = EMOTE_PAIN;\n\tm_EmoteStop = Server()->Tick() + 500 * Server()->TickSpeed() / 1000;\n\n\treturn true;\n}\n\nvoid CCharacter::Snap(int SnappingClient)\n{\n\tif(NetworkClipped(SnappingClient))\n\t\treturn;\n\n\tCNetObj_Character *pCharacter = static_cast<CNetObj_Character *>(Server()->SnapNewItem(NETOBJTYPE_CHARACTER, m_pPlayer->GetCID(), sizeof(CNetObj_Character)));\n\tif(!pCharacter)\n\t\treturn;\n\n\t// write down the m_Core\n\tif(!m_ReckoningTick || GameServer()->m_World.m_Paused)\n\t{\n\t\t// no dead reckoning when paused because the client doesn't know\n\t\t// how far to perform the reckoning\n\t\tpCharacter->m_Tick = 0;\n\t\tm_Core.Write(pCharacter);\n\t}\n\telse\n\t{\n\t\tpCharacter->m_Tick = m_ReckoningTick;\n\t\tm_SendCore.Write(pCharacter);\n\t}\n\n\t// set emote\n\tif (m_EmoteStop < Server()->Tick())\n\t{\n\t\tm_EmoteType = EMOTE_NORMAL;\n\t\tm_EmoteStop = -1;\n\t}\n\n\tpCharacter->m_Emote = m_EmoteType;\n\n\tpCharacter->m_AmmoCount = 0;\n\tpCharacter->m_Health = 0;\n\tpCharacter->m_Armor = 0;\n\tpCharacter->m_TriggeredEvents = m_TriggeredEvents;\n\n\tpCharacter->m_Weapon = m_ActiveWeapon;\n\tpCharacter->m_AttackTick = m_AttackTick;\n\n\tpCharacter->m_Direction = m_Input.m_Direction;\n\n\tif(m_pPlayer->GetCID() == SnappingClient || SnappingClient == -1 ||\n\t\t(!g_Config.m_SvStrictSpectateMode && m_pPlayer->GetCID() == GameServer()->m_apPlayers[SnappingClient]->GetSpectatorID()))\n\t{\n\t\tpCharacter->m_Health = m_Health;\n\t\tpCharacter->m_Armor = m_Armor;\n\t\tif(m_ActiveWeapon == WEAPON_NINJA)\n\t\t\tpCharacter->m_AmmoCount = m_Ninja.m_ActivationTick + g_pData->m_Weapons.m_Ninja.m_Duration * Server()->TickSpeed() / 1000;\n\t\telse if(m_aWeapons[m_ActiveWeapon].m_Ammo > 0)\n\t\t\tpCharacter->m_AmmoCount = m_aWeapons[m_ActiveWeapon].m_Ammo;\n\t}\n\n\tif(pCharacter->m_Emote == EMOTE_NORMAL)\n\t{\n\t\tif(250 - ((Server()->Tick() - m_LastAction)%(250)) < 5)\n\t\t\tpCharacter->m_Emote = EMOTE_BLINK;\n\t}\n}\n\nvoid CCharacter::PostSnap()\n{\n\tm_TriggeredEvents = 0;\n}\n"
  },
  {
    "path": "src/game/server/entities/character.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_SERVER_ENTITIES_CHARACTER_H\n#define GAME_SERVER_ENTITIES_CHARACTER_H\n\n#include <game/server/entity.h>\n\n\nclass CCharacter : public CEntity\n{\n\tMACRO_ALLOC_POOL_ID()\n\npublic:\n\t//character's size\n\tstatic const int ms_PhysSize = 28;\n\n\tCCharacter(CGameWorld *pWorld);\n\n\tvirtual void Reset();\n\tvirtual void Destroy();\n\tvirtual void Tick();\n\tvirtual void TickDefered();\n\tvirtual void TickPaused();\n\tvirtual void Snap(int SnappingClient);\n\tvirtual void PostSnap();\n\n\tbool IsGrounded();\n\n\tvoid SetWeapon(int W);\n\tvoid HandleWeaponSwitch();\n\tvoid DoWeaponSwitch();\n\n\tvoid HandleWeapons();\n\tvoid HandleNinja();\n\n\tvoid OnPredictedInput(CNetObj_PlayerInput *pNewInput);\n\tvoid OnDirectInput(CNetObj_PlayerInput *pNewInput);\n\tvoid ResetInput();\n\tvoid FireWeapon();\n\n\tvoid Die(int Killer, int Weapon);\n\tbool TakeDamage(vec2 Force, int Dmg, int From, int Weapon);\n\n\tbool Spawn(class CPlayer *pPlayer, vec2 Pos);\n\tbool Remove();\n\n\tbool IncreaseHealth(int Amount);\n\tbool IncreaseArmor(int Amount);\n\n\tbool GiveWeapon(int Weapon, int Ammo);\n\tvoid GiveNinja();\n\n\tvoid SetEmote(int Emote, int Tick);\n\n\tbool IsAlive() const { return m_Alive; }\n\tclass CPlayer *GetPlayer() { return m_pPlayer; }\n\nprivate:\n\t// player controlling this character\n\tclass CPlayer *m_pPlayer;\n\n\tbool m_Alive;\n\n\t// weapon info\n\tCEntity *m_apHitObjects[10];\n\tint m_NumObjectsHit;\n\n\tstruct WeaponStat\n\t{\n\t\tint m_AmmoRegenStart;\n\t\tint m_Ammo;\n\t\tint m_Ammocost;\n\t\tbool m_Got;\n\n\t} m_aWeapons[NUM_WEAPONS];\n\n\tint m_ActiveWeapon;\n\tint m_LastWeapon;\n\tint m_QueuedWeapon;\n\n\tint m_ReloadTimer;\n\tint m_AttackTick;\n\n\tint m_DamageTaken;\n\n\tint m_EmoteType;\n\tint m_EmoteStop;\n\n\t// last tick that the player took any action ie some input\n\tint m_LastAction;\n\tint m_LastNoAmmoSound;\n\n\t// these are non-heldback inputs\n\tCNetObj_PlayerInput m_LatestPrevInput;\n\tCNetObj_PlayerInput m_LatestInput;\n\n\t// input\n\tCNetObj_PlayerInput m_PrevInput;\n\tCNetObj_PlayerInput m_Input;\n\tint m_NumInputs;\n\tint m_Jumped;\n\n\tint m_DamageTakenTick;\n\n\tint m_Health;\n\tint m_Armor;\n\n\tint m_TriggeredEvents;\n\n\t// ninja\n\tstruct\n\t{\n\t\tvec2 m_ActivationDir;\n\t\tint m_ActivationTick;\n\t\tint m_CurrentMoveTime;\n\t\tint m_OldVelAmount;\n\t} m_Ninja;\n\n\t// the player core for the physics\n\tCCharacterCore m_Core;\n\n\t// info for dead reckoning\n\tint m_ReckoningTick; // tick that we are performing dead reckoning From\n\tCCharacterCore m_SendCore; // core that we should send\n\tCCharacterCore m_ReckoningCore; // the dead reckoning core\n\n};\n\n#endif\n"
  },
  {
    "path": "src/game/server/entities/flag.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <game/server/gamecontext.h>\n\n#include \"character.h\"\n#include \"flag.h\"\n\nCFlag::CFlag(CGameWorld *pGameWorld, int Team)\n: CEntity(pGameWorld, CGameWorld::ENTTYPE_FLAG)\n{\n\tm_Team = Team;\n\tm_ProximityRadius = ms_PhysSize;\n\tm_pCarryingCharacter = NULL;\n\tm_GrabTick = 0;\n\n\tReset();\n}\n\nvoid CFlag::Reset()\n{\n\tm_pCarryingCharacter = NULL;\n\tm_AtStand = 1;\n\tm_Pos = m_StandPos;\n\tm_Vel = vec2(0,0);\n\tm_GrabTick = 0;\n}\n\nvoid CFlag::TickPaused()\n{\n\t++m_DropTick;\n\tif(m_GrabTick)\n\t\t++m_GrabTick;\n}\n\nvoid CFlag::Snap(int SnappingClient)\n{\n\tif(NetworkClipped(SnappingClient))\n\t\treturn;\n\n\tCNetObj_Flag *pFlag = (CNetObj_Flag *)Server()->SnapNewItem(NETOBJTYPE_FLAG, m_Team, sizeof(CNetObj_Flag));\n\tif(!pFlag)\n\t\treturn;\n\n\tpFlag->m_X = (int)m_Pos.x;\n\tpFlag->m_Y = (int)m_Pos.y;\n\tpFlag->m_Team = m_Team;\n}\n"
  },
  {
    "path": "src/game/server/entities/flag.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_SERVER_ENTITIES_FLAG_H\n#define GAME_SERVER_ENTITIES_FLAG_H\n\n#include <game/server/entity.h>\n\nclass CFlag : public CEntity\n{\npublic:\n\tstatic const int ms_PhysSize = 14;\n\tCCharacter *m_pCarryingCharacter;\n\tvec2 m_Vel;\n\tvec2 m_StandPos;\n\n\tint m_Team;\n\tint m_AtStand;\n\tint m_DropTick;\n\tint m_GrabTick;\n\n\tCFlag(CGameWorld *pGameWorld, int Team);\n\n\tvirtual void Reset();\n\tvirtual void TickPaused();\n\tvirtual void Snap(int SnappingClient);\n};\n\n#endif\n"
  },
  {
    "path": "src/game/server/entities/laser.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <game/server/gamecontext.h>\n\n#include \"character.h\"\n#include \"laser.h\"\n\nCLaser::CLaser(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEnergy, int Owner)\n: CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER)\n{\n\tm_Pos = Pos;\n\tm_Owner = Owner;\n\tm_Energy = StartEnergy;\n\tm_Dir = Direction;\n\tm_Bounces = 0;\n\tm_EvalTick = 0;\n\tGameWorld()->InsertEntity(this);\n\tDoBounce();\n}\n\n\nbool CLaser::HitCharacter(vec2 From, vec2 To)\n{\n\tvec2 At;\n\tCCharacter *pOwnerChar = GameServer()->GetPlayerChar(m_Owner);\n\tCCharacter *pHit = GameServer()->m_World.IntersectCharacter(m_Pos, To, 0.f, At, pOwnerChar);\n\tif(!pHit)\n\t\treturn false;\n\n\tm_From = From;\n\tm_Pos = At;\n\tm_Energy = -1;\n\tpHit->TakeDamage(vec2(0.f, 0.f), GameServer()->Tuning()->m_LaserDamage, m_Owner, WEAPON_LASER);\n\treturn true;\n}\n\nvoid CLaser::DoBounce()\n{\n\tm_EvalTick = Server()->Tick();\n\n\tif(m_Energy < 0)\n\t{\n\t\tGameServer()->m_World.DestroyEntity(this);\n\t\treturn;\n\t}\n\n\tvec2 To = m_Pos + m_Dir * m_Energy;\n\n\tif(GameServer()->Collision()->IntersectLine(m_Pos, To, 0x0, &To))\n\t{\n\t\tif(!HitCharacter(m_Pos, To))\n\t\t{\n\t\t\t// intersected\n\t\t\tm_From = m_Pos;\n\t\t\tm_Pos = To;\n\n\t\t\tvec2 TempPos = m_Pos;\n\t\t\tvec2 TempDir = m_Dir * 4.0f;\n\n\t\t\tGameServer()->Collision()->MovePoint(&TempPos, &TempDir, 1.0f, 0);\n\t\t\tm_Pos = TempPos;\n\t\t\tm_Dir = normalize(TempDir);\n\n\t\t\tm_Energy -= distance(m_From, m_Pos) + GameServer()->Tuning()->m_LaserBounceCost;\n\t\t\tm_Bounces++;\n\n\t\t\tif(m_Bounces > GameServer()->Tuning()->m_LaserBounceNum)\n\t\t\t\tm_Energy = -1;\n\n\t\t\tGameServer()->CreateSound(m_Pos, SOUND_LASER_BOUNCE);\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(!HitCharacter(m_Pos, To))\n\t\t{\n\t\t\tm_From = m_Pos;\n\t\t\tm_Pos = To;\n\t\t\tm_Energy = -1;\n\t\t}\n\t}\n}\n\nvoid CLaser::Reset()\n{\n\tGameServer()->m_World.DestroyEntity(this);\n}\n\nvoid CLaser::Tick()\n{\n\tif(Server()->Tick() > m_EvalTick+(Server()->TickSpeed()*GameServer()->Tuning()->m_LaserBounceDelay)/1000.0f)\n\t\tDoBounce();\n}\n\nvoid CLaser::TickPaused()\n{\n\t++m_EvalTick;\n}\n\nvoid CLaser::Snap(int SnappingClient)\n{\n\tif(NetworkClipped(SnappingClient))\n\t\treturn;\n\n\tCNetObj_Laser *pObj = static_cast<CNetObj_Laser *>(Server()->SnapNewItem(NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser)));\n\tif(!pObj)\n\t\treturn;\n\n\tpObj->m_X = (int)m_Pos.x;\n\tpObj->m_Y = (int)m_Pos.y;\n\tpObj->m_FromX = (int)m_From.x;\n\tpObj->m_FromY = (int)m_From.y;\n\tpObj->m_StartTick = m_EvalTick;\n}\n"
  },
  {
    "path": "src/game/server/entities/laser.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_SERVER_ENTITIES_LASER_H\n#define GAME_SERVER_ENTITIES_LASER_H\n\n#include <game/server/entity.h>\n\nclass CLaser : public CEntity\n{\npublic:\n\tCLaser(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEnergy, int Owner);\n\n\tvirtual void Reset();\n\tvirtual void Tick();\n\tvirtual void TickPaused();\n\tvirtual void Snap(int SnappingClient);\n\nprotected:\n\tbool HitCharacter(vec2 From, vec2 To);\n\tvoid DoBounce();\n\nprivate:\n\tvec2 m_From;\n\tvec2 m_Dir;\n\tfloat m_Energy;\n\tint m_Bounces;\n\tint m_EvalTick;\n\tint m_Owner;\n};\n\n#endif\n"
  },
  {
    "path": "src/game/server/entities/pickup.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <game/generated/server_data.h>\n#include <game/server/gamecontext.h>\n#include <game/server/player.h>\n\n#include \"character.h\"\n#include \"pickup.h\"\n\nCPickup::CPickup(CGameWorld *pGameWorld, int Type)\n: CEntity(pGameWorld, CGameWorld::ENTTYPE_PICKUP)\n{\n\tm_Type = Type;\n\tm_ProximityRadius = PickupPhysSize;\n\n\tReset();\n\n\tGameWorld()->InsertEntity(this);\n}\n\nvoid CPickup::Reset()\n{\n\tif (g_pData->m_aPickups[m_Type].m_Spawndelay > 0)\n\t\tm_SpawnTick = Server()->Tick() + Server()->TickSpeed() * g_pData->m_aPickups[m_Type].m_Spawndelay;\n\telse\n\t\tm_SpawnTick = -1;\n}\n\nvoid CPickup::Tick()\n{\n\t// wait for respawn\n\tif(m_SpawnTick > 0)\n\t{\n\t\tif(Server()->Tick() > m_SpawnTick)\n\t\t{\n\t\t\t// respawn\n\t\t\tm_SpawnTick = -1;\n\n\t\t\tif(m_Type == PICKUP_GRENADE || m_Type == PICKUP_SHOTGUN || m_Type == PICKUP_LASER)\n\t\t\t\tGameServer()->CreateSound(m_Pos, SOUND_WEAPON_SPAWN);\n\t\t}\n\t\telse\n\t\t\treturn;\n\t}\n\t// Check if a player intersected us\n\tCCharacter *pChr = GameServer()->m_World.ClosestCharacter(m_Pos, 20.0f, 0);\n\tif(pChr && pChr->IsAlive())\n\t{\n\t\t// player picked us up, is someone was hooking us, let them go\n\t\tint RespawnTime = -1;\n\t\tswitch (m_Type)\n\t\t{\n\t\t\tcase PICKUP_HEALTH:\n\t\t\t\tif(pChr->IncreaseHealth(1))\n\t\t\t\t{\n\t\t\t\t\tGameServer()->CreateSound(m_Pos, SOUND_PICKUP_HEALTH);\n\t\t\t\t\tRespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase PICKUP_ARMOR:\n\t\t\t\tif(pChr->IncreaseArmor(1))\n\t\t\t\t{\n\t\t\t\t\tGameServer()->CreateSound(m_Pos, SOUND_PICKUP_ARMOR);\n\t\t\t\t\tRespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase PICKUP_GRENADE:\n\t\t\t\tif(pChr->GiveWeapon(WEAPON_GRENADE, 10))\n\t\t\t\t{\n\t\t\t\t\tRespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime;\n\t\t\t\t\tGameServer()->CreateSound(m_Pos, SOUND_PICKUP_GRENADE);\n\t\t\t\t\tif(pChr->GetPlayer())\n\t\t\t\t\t\tGameServer()->SendWeaponPickup(pChr->GetPlayer()->GetCID(), WEAPON_GRENADE);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase PICKUP_SHOTGUN:\n\t\t\t\tif(pChr->GiveWeapon(WEAPON_SHOTGUN, 10))\n\t\t\t\t{\n\t\t\t\t\tRespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime;\n\t\t\t\t\tGameServer()->CreateSound(m_Pos, SOUND_PICKUP_SHOTGUN);\n\t\t\t\t\tif(pChr->GetPlayer())\n\t\t\t\t\t\tGameServer()->SendWeaponPickup(pChr->GetPlayer()->GetCID(), WEAPON_SHOTGUN);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase PICKUP_LASER:\n\t\t\t\tif(pChr->GiveWeapon(WEAPON_LASER, 10))\n\t\t\t\t{\n\t\t\t\t\tRespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime;\n\t\t\t\t\tGameServer()->CreateSound(m_Pos, SOUND_PICKUP_SHOTGUN);\n\t\t\t\t\tif(pChr->GetPlayer())\n\t\t\t\t\t\tGameServer()->SendWeaponPickup(pChr->GetPlayer()->GetCID(), WEAPON_LASER);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase PICKUP_NINJA:\n\t\t\t\t{\n\t\t\t\t\t// activate ninja on target player\n\t\t\t\t\tpChr->GiveNinja();\n\t\t\t\t\tRespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime;\n\n\t\t\t\t\t// loop through all players, setting their emotes\n\t\t\t\t\tCCharacter *pC = static_cast<CCharacter *>(GameServer()->m_World.FindFirst(CGameWorld::ENTTYPE_CHARACTER));\n\t\t\t\t\tfor(; pC; pC = (CCharacter *)pC->TypeNext())\n\t\t\t\t\t{\n\t\t\t\t\t\tif (pC != pChr)\n\t\t\t\t\t\t\tpC->SetEmote(EMOTE_SURPRISE, Server()->Tick() + Server()->TickSpeed());\n\t\t\t\t\t}\n\n\t\t\t\t\tpChr->SetEmote(EMOTE_ANGRY, Server()->Tick() + 1200 * Server()->TickSpeed() / 1000);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t};\n\n\t\tif(RespawnTime >= 0)\n\t\t{\n\t\t\tchar aBuf[256];\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"pickup player='%d:%s' item=%d/%d\",\n\t\t\t\tpChr->GetPlayer()->GetCID(), Server()->ClientName(pChr->GetPlayer()->GetCID()), m_Type);\n\t\t\tGameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"game\", aBuf);\n\t\t\tm_SpawnTick = Server()->Tick() + Server()->TickSpeed() * RespawnTime;\n\t\t}\n\t}\n}\n\nvoid CPickup::TickPaused()\n{\n\tif(m_SpawnTick != -1)\n\t\t++m_SpawnTick;\n}\n\nvoid CPickup::Snap(int SnappingClient)\n{\n\tif(m_SpawnTick != -1 || NetworkClipped(SnappingClient))\n\t\treturn;\n\n\tCNetObj_Pickup *pP = static_cast<CNetObj_Pickup *>(Server()->SnapNewItem(NETOBJTYPE_PICKUP, m_ID, sizeof(CNetObj_Pickup)));\n\tif(!pP)\n\t\treturn;\n\n\tpP->m_X = (int)m_Pos.x;\n\tpP->m_Y = (int)m_Pos.y;\n\tpP->m_Type = m_Type;\n}\n"
  },
  {
    "path": "src/game/server/entities/pickup.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_SERVER_ENTITIES_PICKUP_H\n#define GAME_SERVER_ENTITIES_PICKUP_H\n\n#include <game/server/entity.h>\n\nconst int PickupPhysSize = 14;\n\nclass CPickup : public CEntity\n{\npublic:\n\tCPickup(CGameWorld *pGameWorld, int Type);\n\n\tvirtual void Reset();\n\tvirtual void Tick();\n\tvirtual void TickPaused();\n\tvirtual void Snap(int SnappingClient);\n\nprivate:\n\tint m_Type;\n\tint m_SpawnTick;\n};\n\n#endif\n"
  },
  {
    "path": "src/game/server/entities/projectile.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <game/server/gamecontext.h>\n\n#include \"character.h\"\n#include \"projectile.h\"\n\nCProjectile::CProjectile(CGameWorld *pGameWorld, int Type, int Owner, vec2 Pos, vec2 Dir, int Span,\n\t\tint Damage, bool Explosive, float Force, int SoundImpact, int Weapon)\n: CEntity(pGameWorld, CGameWorld::ENTTYPE_PROJECTILE)\n{\n\tm_Type = Type;\n\tm_Pos = Pos;\n\tm_Direction = Dir;\n\tm_LifeSpan = Span;\n\tm_Owner = Owner;\n\tm_Force = Force;\n\tm_Damage = Damage;\n\tm_SoundImpact = SoundImpact;\n\tm_Weapon = Weapon;\n\tm_StartTick = Server()->Tick();\n\tm_Explosive = Explosive;\n\n\tGameWorld()->InsertEntity(this);\n}\n\nvoid CProjectile::Reset()\n{\n\tGameServer()->m_World.DestroyEntity(this);\n}\n\nvec2 CProjectile::GetPos(float Time)\n{\n\tfloat Curvature = 0;\n\tfloat Speed = 0;\n\n\tswitch(m_Type)\n\t{\n\t\tcase WEAPON_GRENADE:\n\t\t\tCurvature = GameServer()->Tuning()->m_GrenadeCurvature;\n\t\t\tSpeed = GameServer()->Tuning()->m_GrenadeSpeed;\n\t\t\tbreak;\n\n\t\tcase WEAPON_SHOTGUN:\n\t\t\tCurvature = GameServer()->Tuning()->m_ShotgunCurvature;\n\t\t\tSpeed = GameServer()->Tuning()->m_ShotgunSpeed;\n\t\t\tbreak;\n\n\t\tcase WEAPON_GUN:\n\t\t\tCurvature = GameServer()->Tuning()->m_GunCurvature;\n\t\t\tSpeed = GameServer()->Tuning()->m_GunSpeed;\n\t\t\tbreak;\n\t}\n\n\treturn CalcPos(m_Pos, m_Direction, Curvature, Speed, Time);\n}\n\n\nvoid CProjectile::Tick()\n{\n\tfloat Pt = (Server()->Tick()-m_StartTick-1)/(float)Server()->TickSpeed();\n\tfloat Ct = (Server()->Tick()-m_StartTick)/(float)Server()->TickSpeed();\n\tvec2 PrevPos = GetPos(Pt);\n\tvec2 CurPos = GetPos(Ct);\n\tint Collide = GameServer()->Collision()->IntersectLine(PrevPos, CurPos, &CurPos, 0);\n\tCCharacter *OwnerChar = GameServer()->GetPlayerChar(m_Owner);\n\tCCharacter *TargetChr = GameServer()->m_World.IntersectCharacter(PrevPos, CurPos, 6.0f, CurPos, OwnerChar);\n\n\tm_LifeSpan--;\n\n\tif(TargetChr || Collide || m_LifeSpan < 0 || GameLayerClipped(CurPos))\n\t{\n\t\tif(m_LifeSpan >= 0 || m_Weapon == WEAPON_GRENADE)\n\t\t\tGameServer()->CreateSound(CurPos, m_SoundImpact);\n\n\t\tif(m_Explosive)\n\t\t\tGameServer()->CreateExplosion(CurPos, m_Owner, m_Weapon, false);\n\n\t\telse if(TargetChr)\n\t\t\tTargetChr->TakeDamage(m_Direction * max(0.001f, m_Force), m_Damage, m_Owner, m_Weapon);\n\n\t\tGameServer()->m_World.DestroyEntity(this);\n\t}\n}\n\nvoid CProjectile::TickPaused()\n{\n\t++m_StartTick;\n}\n\nvoid CProjectile::FillInfo(CNetObj_Projectile *pProj)\n{\n\tpProj->m_X = (int)m_Pos.x;\n\tpProj->m_Y = (int)m_Pos.y;\n\tpProj->m_VelX = (int)(m_Direction.x*100.0f);\n\tpProj->m_VelY = (int)(m_Direction.y*100.0f);\n\tpProj->m_StartTick = m_StartTick;\n\tpProj->m_Type = m_Type;\n}\n\nvoid CProjectile::Snap(int SnappingClient)\n{\n\tfloat Ct = (Server()->Tick()-m_StartTick)/(float)Server()->TickSpeed();\n\n\tif(NetworkClipped(SnappingClient, GetPos(Ct)))\n\t\treturn;\n\n\tCNetObj_Projectile *pProj = static_cast<CNetObj_Projectile *>(Server()->SnapNewItem(NETOBJTYPE_PROJECTILE, m_ID, sizeof(CNetObj_Projectile)));\n\tif(pProj)\n\t\tFillInfo(pProj);\n}\n"
  },
  {
    "path": "src/game/server/entities/projectile.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_SERVER_ENTITIES_PROJECTILE_H\n#define GAME_SERVER_ENTITIES_PROJECTILE_H\n\nclass CProjectile : public CEntity\n{\npublic:\n\tCProjectile(CGameWorld *pGameWorld, int Type, int Owner, vec2 Pos, vec2 Dir, int Span,\n\t\tint Damage, bool Explosive, float Force, int SoundImpact, int Weapon);\n\n\tvec2 GetPos(float Time);\n\tvoid FillInfo(CNetObj_Projectile *pProj);\n\n\tvirtual void Reset();\n\tvirtual void Tick();\n\tvirtual void TickPaused();\n\tvirtual void Snap(int SnappingClient);\n\nprivate:\n\tvec2 m_Direction;\n\tint m_LifeSpan;\n\tint m_Owner;\n\tint m_Type;\n\tint m_Damage;\n\tint m_SoundImpact;\n\tint m_Weapon;\n\tfloat m_Force;\n\tint m_StartTick;\n\tbool m_Explosive;\n};\n\n#endif\n"
  },
  {
    "path": "src/game/server/entity.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n\n#include \"entity.h\"\n#include \"gamecontext.h\"\n#include \"player.h\"\n\n//////////////////////////////////////////////////\n// Entity\n//////////////////////////////////////////////////\nCEntity::CEntity(CGameWorld *pGameWorld, int ObjType)\n{\n\tm_pGameWorld = pGameWorld;\n\n\tm_ObjType = ObjType;\n\tm_Pos = vec2(0,0);\n\tm_ProximityRadius = 0;\n\n\tm_MarkedForDestroy = false;\n\tm_ID = Server()->SnapNewID();\n\n\tm_pPrevTypeEntity = 0;\n\tm_pNextTypeEntity = 0;\n}\n\nCEntity::~CEntity()\n{\n\tGameWorld()->RemoveEntity(this);\n\tServer()->SnapFreeID(m_ID);\n}\n\nint CEntity::NetworkClipped(int SnappingClient)\n{\n\treturn NetworkClipped(SnappingClient, m_Pos);\n}\n\nint CEntity::NetworkClipped(int SnappingClient, vec2 CheckPos)\n{\n\tif(SnappingClient == -1)\n\t\treturn 0;\n\n\tfloat dx = GameServer()->m_apPlayers[SnappingClient]->m_ViewPos.x-CheckPos.x;\n\tfloat dy = GameServer()->m_apPlayers[SnappingClient]->m_ViewPos.y-CheckPos.y;\n\n\tif(absolute(dx) > 1000.0f || absolute(dy) > 800.0f)\n\t\treturn 1;\n\n\tif(distance(GameServer()->m_apPlayers[SnappingClient]->m_ViewPos, CheckPos) > 1100.0f)\n\t\treturn 1;\n\treturn 0;\n}\n\nbool CEntity::GameLayerClipped(vec2 CheckPos)\n{\n\treturn round(CheckPos.x)/32 < -200 || round(CheckPos.x)/32 > GameServer()->Collision()->GetWidth()+200 ||\n\t\t\tround(CheckPos.y)/32 < -200 || round(CheckPos.y)/32 > GameServer()->Collision()->GetHeight()+200 ? true : false;\n}\n"
  },
  {
    "path": "src/game/server/entity.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_SERVER_ENTITY_H\n#define GAME_SERVER_ENTITY_H\n\n#include <base/vmath.h>\n\n#include <game/server/gameworld.h>\n\n#include \"alloc.h\"\n\n/*\n\tClass: Entity\n\t\tBasic entity class.\n*/\nclass CEntity\n{\n\tMACRO_ALLOC_HEAP()\n\n\tfriend class CGameWorld;\t// entity list handling\n\tCEntity *m_pPrevTypeEntity;\n\tCEntity *m_pNextTypeEntity;\n\n\tclass CGameWorld *m_pGameWorld;\nprotected:\n\tbool m_MarkedForDestroy;\n\tint m_ID;\n\tint m_ObjType;\npublic:\n\tCEntity(CGameWorld *pGameWorld, int Objtype);\n\tvirtual ~CEntity();\n\n\tclass CGameWorld *GameWorld() { return m_pGameWorld; }\n\tclass CGameContext *GameServer() { return GameWorld()->GameServer(); }\n\tclass IServer *Server() { return GameWorld()->Server(); }\n\n\n\tCEntity *TypeNext() { return m_pNextTypeEntity; }\n\tCEntity *TypePrev() { return m_pPrevTypeEntity; }\n\n\t/*\n\t\tFunction: destroy\n\t\t\tDestorys the entity.\n\t*/\n\tvirtual void Destroy() { delete this; }\n\n\t/*\n\t\tFunction: reset\n\t\t\tCalled when the game resets the map. Puts the entity\n\t\t\tback to it's starting state or perhaps destroys it.\n\t*/\n\tvirtual void Reset() {}\n\n\t/*\n\t\tFunction: tick\n\t\t\tCalled progress the entity to the next tick. Updates\n\t\t\tand moves the entity to it's new state and position.\n\t*/\n\tvirtual void Tick() {}\n\n\t/*\n\t\tFunction: tick_defered\n\t\t\tCalled after all entities tick() function has been called.\n\t*/\n\tvirtual void TickDefered() {}\n\n\t/*\n\t\tFunction: TickPaused\n\t\t\tCalled when the game is paused, to freeze the state and position of the entity.\n\t*/\n\tvirtual void TickPaused() {}\n\n\t/*\n\t\tFunction: snap\n\t\t\tCalled when a new snapshot is being generated for a specific\n\t\t\tclient.\n\n\t\tArguments:\n\t\t\tsnapping_client - ID of the client which snapshot is\n\t\t\t\tbeing generated. Could be -1 to create a complete\n\t\t\t\tsnapshot of everything in the game for demo\n\t\t\t\trecording.\n\t*/\n\tvirtual void Snap(int SnappingClient) {}\n\n\tvirtual void PostSnap() {}\n\n\t/*\n\t\tFunction: networkclipped(int snapping_client)\n\t\t\tPerforms a series of test to see if a client can see the\n\t\t\tentity.\n\n\t\tArguments:\n\t\t\tsnapping_client - ID of the client which snapshot is\n\t\t\t\tbeing generated. Could be -1 to create a complete\n\t\t\t\tsnapshot of everything in the game for demo\n\t\t\t\trecording.\n\n\t\tReturns:\n\t\t\tNon-zero if the entity doesn't have to be in the snapshot.\n\t*/\n\tint NetworkClipped(int SnappingClient);\n\tint NetworkClipped(int SnappingClient, vec2 CheckPos);\n\n\tbool GameLayerClipped(vec2 CheckPos);\n\n\t/*\n\t\tVariable: proximity_radius\n\t\t\tContains the physical size of the entity.\n\t*/\n\tfloat m_ProximityRadius;\n\n\t/*\n\t\tVariable: pos\n\t\t\tContains the current posititon of the entity.\n\t*/\n\tvec2 m_Pos;\n};\n\n#endif\n"
  },
  {
    "path": "src/game/server/eventhandler.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include \"eventhandler.h\"\n#include \"gamecontext.h\"\n#include \"player.h\"\n\n//////////////////////////////////////////////////\n// Event handler\n//////////////////////////////////////////////////\nCEventHandler::CEventHandler()\n{\n\tm_pGameServer = 0;\n\tClear();\n}\n\nvoid CEventHandler::SetGameServer(CGameContext *pGameServer)\n{\n\tm_pGameServer = pGameServer;\n}\n\nvoid *CEventHandler::Create(int Type, int Size, int Mask)\n{\n\tif(m_NumEvents == MAX_EVENTS)\n\t\treturn 0;\n\tif(m_CurrentOffset+Size >= MAX_DATASIZE)\n\t\treturn 0;\n\n\tvoid *p = &m_aData[m_CurrentOffset];\n\tm_aOffsets[m_NumEvents] = m_CurrentOffset;\n\tm_aTypes[m_NumEvents] = Type;\n\tm_aSizes[m_NumEvents] = Size;\n\tm_aClientMasks[m_NumEvents] = Mask;\n\tm_CurrentOffset += Size;\n\tm_NumEvents++;\n\treturn p;\n}\n\nvoid CEventHandler::Clear()\n{\n\tm_NumEvents = 0;\n\tm_CurrentOffset = 0;\n}\n\nvoid CEventHandler::Snap(int SnappingClient)\n{\n\tfor(int i = 0; i < m_NumEvents; i++)\n\t{\n\t\tif(SnappingClient == -1 || CmaskIsSet(m_aClientMasks[i], SnappingClient))\n\t\t{\n\t\t\tCNetEvent_Common *ev = (CNetEvent_Common *)&m_aData[m_aOffsets[i]];\n\t\t\tif(SnappingClient == -1 || distance(GameServer()->m_apPlayers[SnappingClient]->m_ViewPos, vec2(ev->m_X, ev->m_Y)) < 1500.0f)\n\t\t\t{\n\t\t\t\tvoid *d = GameServer()->Server()->SnapNewItem(m_aTypes[i], i, m_aSizes[i]);\n\t\t\t\tif(d)\n\t\t\t\t\tmem_copy(d, &m_aData[m_aOffsets[i]], m_aSizes[i]);\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "src/game/server/eventhandler.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_SERVER_EVENTHANDLER_H\n#define GAME_SERVER_EVENTHANDLER_H\n\n//\nclass CEventHandler\n{\n\tstatic const int MAX_EVENTS = 128;\n\tstatic const int MAX_DATASIZE = 128*64;\n\n\tint m_aTypes[MAX_EVENTS]; // TODO: remove some of these arrays\n\tint m_aOffsets[MAX_EVENTS];\n\tint m_aSizes[MAX_EVENTS];\n\tint m_aClientMasks[MAX_EVENTS];\n\tchar m_aData[MAX_DATASIZE];\n\n\tclass CGameContext *m_pGameServer;\n\n\tint m_CurrentOffset;\n\tint m_NumEvents;\npublic:\n\tCGameContext *GameServer() const { return m_pGameServer; }\n\tvoid SetGameServer(CGameContext *pGameServer);\n\n\tCEventHandler();\n\tvoid *Create(int Type, int Size, int Mask = -1);\n\tvoid Clear();\n\tvoid Snap(int SnappingClient);\n};\n\n#endif\n"
  },
  {
    "path": "src/game/server/gamecontext.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/math.h>\n\n#include <engine/shared/config.h>\n#include <engine/shared/memheap.h>\n#include <engine/map.h>\n\n#include <game/collision.h>\n#include <game/gamecore.h>\n#include <game/version.h>\n\n#include \"entities/character.h\"\n#include \"gamemodes/ctf.h\"\n#include \"gamemodes/dm.h\"\n#include \"gamemodes/lms.h\"\n#include \"gamemodes/mod.h\"\n#include \"gamemodes/sur.h\"\n#include \"gamemodes/tdm.h\"\n#include \"gamecontext.h\"\n#include \"player.h\"\n\nenum\n{\n\tRESET,\n\tNO_RESET\n};\n\nvoid CGameContext::Construct(int Resetting)\n{\n\tm_Resetting = 0;\n\tm_pServer = 0;\n\n\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t\tm_apPlayers[i] = 0;\n\n\tm_pController = 0;\n\tm_VoteCloseTime = 0;\n\tm_pVoteOptionFirst = 0;\n\tm_pVoteOptionLast = 0;\n\tm_NumVoteOptions = 0;\n\tm_LockTeams = 0;\n\n\tif(Resetting==NO_RESET)\n\t\tm_pVoteOptionHeap = new CHeap();\n}\n\nCGameContext::CGameContext(int Resetting)\n{\n\tConstruct(Resetting);\n}\n\nCGameContext::CGameContext()\n{\n\tConstruct(NO_RESET);\n}\n\nCGameContext::~CGameContext()\n{\n\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t\tdelete m_apPlayers[i];\n\tif(!m_Resetting)\n\t\tdelete m_pVoteOptionHeap;\n}\n\nvoid CGameContext::Clear()\n{\n\tCHeap *pVoteOptionHeap = m_pVoteOptionHeap;\n\tCVoteOptionServer *pVoteOptionFirst = m_pVoteOptionFirst;\n\tCVoteOptionServer *pVoteOptionLast = m_pVoteOptionLast;\n\tint NumVoteOptions = m_NumVoteOptions;\n\tCTuningParams Tuning = m_Tuning;\n\n\tm_Resetting = true;\n\tthis->~CGameContext();\n\tmem_zero(this, sizeof(*this));\n\tnew (this) CGameContext(RESET);\n\n\tm_pVoteOptionHeap = pVoteOptionHeap;\n\tm_pVoteOptionFirst = pVoteOptionFirst;\n\tm_pVoteOptionLast = pVoteOptionLast;\n\tm_NumVoteOptions = NumVoteOptions;\n\tm_Tuning = Tuning;\n}\n\n\nclass CCharacter *CGameContext::GetPlayerChar(int ClientID)\n{\n\tif(ClientID < 0 || ClientID >= MAX_CLIENTS || !m_apPlayers[ClientID])\n\t\treturn 0;\n\treturn m_apPlayers[ClientID]->GetCharacter();\n}\n\nvoid CGameContext::CreateDamageInd(vec2 Pos, float Angle, int Amount)\n{\n\tfloat a = 3 * 3.14159f / 2 + Angle;\n\t//float a = get_angle(dir);\n\tfloat s = a-pi/3;\n\tfloat e = a+pi/3;\n\tfor(int i = 0; i < Amount; i++)\n\t{\n\t\tfloat f = mix(s, e, float(i+1)/float(Amount+2));\n\t\tCNetEvent_DamageInd *pEvent = (CNetEvent_DamageInd *)m_Events.Create(NETEVENTTYPE_DAMAGEIND, sizeof(CNetEvent_DamageInd));\n\t\tif(pEvent)\n\t\t{\n\t\t\tpEvent->m_X = (int)Pos.x;\n\t\t\tpEvent->m_Y = (int)Pos.y;\n\t\t\tpEvent->m_Angle = (int)(f*256.0f);\n\t\t}\n\t}\n}\n\nvoid CGameContext::CreateHammerHit(vec2 Pos)\n{\n\t// create the event\n\tCNetEvent_HammerHit *pEvent = (CNetEvent_HammerHit *)m_Events.Create(NETEVENTTYPE_HAMMERHIT, sizeof(CNetEvent_HammerHit));\n\tif(pEvent)\n\t{\n\t\tpEvent->m_X = (int)Pos.x;\n\t\tpEvent->m_Y = (int)Pos.y;\n\t}\n}\n\n\nvoid CGameContext::CreateExplosion(vec2 Pos, int Owner, int Weapon, bool NoDamage)\n{\n\t// create the event\n\tCNetEvent_Explosion *pEvent = (CNetEvent_Explosion *)m_Events.Create(NETEVENTTYPE_EXPLOSION, sizeof(CNetEvent_Explosion));\n\tif(pEvent)\n\t{\n\t\tpEvent->m_X = (int)Pos.x;\n\t\tpEvent->m_Y = (int)Pos.y;\n\t}\n\n\tif (!NoDamage)\n\t{\n\t\t// deal damage\n\t\tCCharacter *apEnts[MAX_CLIENTS];\n\t\tfloat Radius = 135.0f;\n\t\tfloat InnerRadius = 48.0f;\n\t\tint Num = m_World.FindEntities(Pos, Radius, (CEntity**)apEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER);\n\t\tfor(int i = 0; i < Num; i++)\n\t\t{\n\t\t\tvec2 Diff = apEnts[i]->m_Pos - Pos;\n\t\t\tvec2 ForceDir(0,1);\n\t\t\tfloat l = length(Diff);\n\t\t\tif(l)\n\t\t\t\tForceDir = normalize(Diff);\n\t\t\tl = 1-clamp((l-InnerRadius)/(Radius-InnerRadius), 0.0f, 1.0f);\n\t\t\tfloat Dmg = 6 * l;\n\t\t\tif((int)Dmg)\n\t\t\t\tapEnts[i]->TakeDamage(ForceDir*Dmg*2, (int)Dmg, Owner, Weapon);\n\t\t}\n\t}\n}\n\nvoid CGameContext::CreatePlayerSpawn(vec2 Pos)\n{\n\t// create the event\n\tCNetEvent_Spawn *ev = (CNetEvent_Spawn *)m_Events.Create(NETEVENTTYPE_SPAWN, sizeof(CNetEvent_Spawn));\n\tif(ev)\n\t{\n\t\tev->m_X = (int)Pos.x;\n\t\tev->m_Y = (int)Pos.y;\n\t}\n}\n\nvoid CGameContext::CreateDeath(vec2 Pos, int ClientID)\n{\n\t// create the event\n\tCNetEvent_Death *pEvent = (CNetEvent_Death *)m_Events.Create(NETEVENTTYPE_DEATH, sizeof(CNetEvent_Death));\n\tif(pEvent)\n\t{\n\t\tpEvent->m_X = (int)Pos.x;\n\t\tpEvent->m_Y = (int)Pos.y;\n\t\tpEvent->m_ClientID = ClientID;\n\t}\n}\n\nvoid CGameContext::CreateSound(vec2 Pos, int Sound, int Mask)\n{\n\tif (Sound < 0)\n\t\treturn;\n\n\t// create a sound\n\tCNetEvent_SoundWorld *pEvent = (CNetEvent_SoundWorld *)m_Events.Create(NETEVENTTYPE_SOUNDWORLD, sizeof(CNetEvent_SoundWorld), Mask);\n\tif(pEvent)\n\t{\n\t\tpEvent->m_X = (int)Pos.x;\n\t\tpEvent->m_Y = (int)Pos.y;\n\t\tpEvent->m_SoundID = Sound;\n\t}\n}\n\n\nvoid CGameContext::SendChatTarget(int To, const char *pText)\n{\n\tCNetMsg_Sv_Chat Msg;\n\tMsg.m_Team = 0;\n\tMsg.m_ClientID = -1;\n\tMsg.m_pMessage = pText;\n\tServer()->SendPackMsg(&Msg, MSGFLAG_VITAL, To);\n}\n\n\nvoid CGameContext::SendChat(int ChatterClientID, int Team, const char *pText)\n{\n\tchar aBuf[256];\n\tif(ChatterClientID >= 0 && ChatterClientID < MAX_CLIENTS)\n\t\tstr_format(aBuf, sizeof(aBuf), \"%d:%d:%s: %s\", ChatterClientID, Team, Server()->ClientName(ChatterClientID), pText);\n\telse\n\t\tstr_format(aBuf, sizeof(aBuf), \"*** %s\", pText);\n\tConsole()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, Team!=CHAT_ALL?\"teamchat\":\"chat\", aBuf);\n\n\tif(Team == CHAT_ALL)\n\t{\n\t\tCNetMsg_Sv_Chat Msg;\n\t\tMsg.m_Team = 0;\n\t\tMsg.m_ClientID = ChatterClientID;\n\t\tMsg.m_pMessage = pText;\n\t\tServer()->SendPackMsg(&Msg, MSGFLAG_VITAL, -1);\n\t}\n\telse\n\t{\n\t\tCNetMsg_Sv_Chat Msg;\n\t\tMsg.m_Team = 1;\n\t\tMsg.m_ClientID = ChatterClientID;\n\t\tMsg.m_pMessage = pText;\n\n\t\t// pack one for the recording only\n\t\tServer()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NOSEND, -1);\n\n\t\t// send to the clients\n\t\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t\t{\n\t\t\tif(m_apPlayers[i] && m_apPlayers[i]->GetTeam() == Team)\n\t\t\t\tServer()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, i);\n\t\t}\n\t}\n}\n\nvoid CGameContext::SendEmoticon(int ClientID, int Emoticon)\n{\n\tCNetMsg_Sv_Emoticon Msg;\n\tMsg.m_ClientID = ClientID;\n\tMsg.m_Emoticon = Emoticon;\n\tServer()->SendPackMsg(&Msg, MSGFLAG_VITAL, -1);\n}\n\nvoid CGameContext::SendWeaponPickup(int ClientID, int Weapon)\n{\n\tCNetMsg_Sv_WeaponPickup Msg;\n\tMsg.m_Weapon = Weapon;\n\tServer()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID);\n}\n\nvoid CGameContext::SendMotd(int ClientID)\n{\n\tCNetMsg_Sv_Motd Msg;\n\tMsg.m_pMessage = g_Config.m_SvMotd;\n\tServer()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID);\n}\n\nvoid CGameContext::SendSettings(int ClientID)\n{\n\tCNetMsg_Sv_ServerSettings Msg;\n\tMsg.m_KickVote = g_Config.m_SvVoteKick;\n\tMsg.m_KickMin = g_Config.m_SvVoteKickMin;\n\tMsg.m_SpecVote = g_Config.m_SvVoteSpectate;\n\tMsg.m_TeamLock = m_LockTeams != 0;\n\tMsg.m_TeamBalance = g_Config.m_SvTeambalanceTime != 0;\n\tMsg.m_PlayerSlots = Server()->MaxClients()-g_Config.m_SvSpectatorSlots;\n\tServer()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID);\n}\n\n\nvoid CGameContext::SendGameMsg(int GameMsgID, int ClientID)\n{\n\tCMsgPacker Msg(NETMSGTYPE_SV_GAMEMSG);\n\tMsg.AddInt(GameMsgID);\n\tServer()->SendMsg(&Msg, MSGFLAG_VITAL, ClientID);\n}\n\nvoid CGameContext::SendGameMsg(int GameMsgID, int ParaI1, int ClientID)\n{\n\tCMsgPacker Msg(NETMSGTYPE_SV_GAMEMSG);\n\tMsg.AddInt(GameMsgID);\n\tMsg.AddInt(ParaI1);\n\tServer()->SendMsg(&Msg, MSGFLAG_VITAL, ClientID);\n}\n\nvoid CGameContext::SendGameMsg(int GameMsgID, int ParaI1, int ParaI2, int ParaI3, int ClientID)\n{\n\tCMsgPacker Msg(NETMSGTYPE_SV_GAMEMSG);\n\tMsg.AddInt(GameMsgID);\n\tMsg.AddInt(ParaI1);\n\tMsg.AddInt(ParaI2);\n\tMsg.AddInt(ParaI3);\n\tServer()->SendMsg(&Msg, MSGFLAG_VITAL, ClientID);\n}\n\n//\nvoid CGameContext::StartVote(int Type, const char *pDesc, const char *pCommand, const char *pReason)\n{\n\t// check if a vote is already running\n\tif(m_VoteCloseTime)\n\t\treturn;\n\n\t// reset votes\n\tm_VoteEnforce = VOTE_ENFORCE_UNKNOWN;\n\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t{\n\t\tif(m_apPlayers[i])\n\t\t{\n\t\t\tm_apPlayers[i]->m_Vote = 0;\n\t\t\tm_apPlayers[i]->m_VotePos = 0;\n\t\t}\n\t}\n\n\t// start vote\n\tm_VoteCloseTime = time_get() + time_freq()*VOTE_TIME;\n\tstr_copy(m_aVoteDescription, pDesc, sizeof(m_aVoteDescription));\n\tstr_copy(m_aVoteCommand, pCommand, sizeof(m_aVoteCommand));\n\tstr_copy(m_aVoteReason, pReason, sizeof(m_aVoteReason));\n\tSendVoteSet(Type, -1);\n\tm_VoteUpdate = true;\n}\n\n\nvoid CGameContext::EndVote(int Type, bool Force)\n{\n\tm_VoteCloseTime = 0;\n\tif(Force)\n\t\tm_VoteCreator = -1;\n\tSendVoteSet(Type, -1);\n}\n\nvoid CGameContext::ForceVote(int Type, const char *pDescription, const char *pReason)\n{\n\tCNetMsg_Sv_VoteSet Msg;\n\tMsg.m_Type = Type;\n\tMsg.m_Timeout = 0;\n\tMsg.m_ClientID = -1;\n\tMsg.m_pDescription = pDescription;\n\tMsg.m_pReason = pReason;\n\tServer()->SendPackMsg(&Msg, MSGFLAG_VITAL, -1);\n}\n\nvoid CGameContext::SendVoteSet(int Type, int ToClientID)\n{\n\tCNetMsg_Sv_VoteSet Msg;\n\tif(m_VoteCloseTime)\n\t{\n\t\tMsg.m_ClientID = m_VoteCreator;\n\t\tMsg.m_Type = Type;\n\t\tMsg.m_Timeout = (m_VoteCloseTime-time_get())/time_freq();\n\t\tMsg.m_pDescription = m_aVoteDescription;\n\t\tMsg.m_pReason = m_aVoteReason;\n\t}\n\telse\n\t{\n\t\tMsg.m_Type = Type;\n\t\tMsg.m_Timeout = 0;\n\t\tMsg.m_ClientID = m_VoteCreator;\n\t\tMsg.m_pDescription = \"\";\n\t\tMsg.m_pReason = \"\";\n\t}\n\tServer()->SendPackMsg(&Msg, MSGFLAG_VITAL, ToClientID);\n}\n\nvoid CGameContext::SendVoteStatus(int ClientID, int Total, int Yes, int No)\n{\n\tCNetMsg_Sv_VoteStatus Msg = {0};\n\tMsg.m_Total = Total;\n\tMsg.m_Yes = Yes;\n\tMsg.m_No = No;\n\tMsg.m_Pass = Total - (Yes+No);\n\n\tServer()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID);\n\n}\n\nvoid CGameContext::AbortVoteOnDisconnect(int ClientID)\n{\n\tif(m_VoteCloseTime && ClientID == m_VoteClientID && (!str_comp_num(m_aVoteCommand, \"kick \", 5) ||\n\t\t!str_comp_num(m_aVoteCommand, \"set_team \", 9) || (!str_comp_num(m_aVoteCommand, \"ban \", 4) && Server()->IsBanned(ClientID))))\n\t\tm_VoteCloseTime = -1;\n}\n\nvoid CGameContext::AbortVoteOnTeamChange(int ClientID)\n{\n\tif(m_VoteCloseTime && ClientID == m_VoteClientID && !str_comp_num(m_aVoteCommand, \"set_team \", 9))\n\t\tm_VoteCloseTime = -1;\n}\n\n\nvoid CGameContext::CheckPureTuning()\n{\n\t// might not be created yet during start up\n\tif(!m_pController)\n\t\treturn;\n\n\tif(\tstr_comp(m_pController->GetGameType(), \"DM\")==0 ||\n\t\tstr_comp(m_pController->GetGameType(), \"TDM\")==0 ||\n\t\tstr_comp(m_pController->GetGameType(), \"CTF\")==0 ||\n\t\tstr_comp(m_pController->GetGameType(), \"LMS\")==0 ||\n\t\tstr_comp(m_pController->GetGameType(), \"SUR\")==0)\n\t{\n\t\tCTuningParams p;\n\t\tif(mem_comp(&p, &m_Tuning, sizeof(p)) != 0)\n\t\t{\n\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"server\", \"resetting tuning due to pure server\");\n\t\t\tm_Tuning = p;\n\t\t}\n\t}\n}\n\nvoid CGameContext::SendTuningParams(int ClientID)\n{\n\tCheckPureTuning();\n\n\tCMsgPacker Msg(NETMSGTYPE_SV_TUNEPARAMS);\n\tint *pParams = (int *)&m_Tuning;\n\tfor(unsigned i = 0; i < sizeof(m_Tuning)/sizeof(int); i++)\n\t\tMsg.AddInt(pParams[i]);\n\tServer()->SendMsg(&Msg, MSGFLAG_VITAL, ClientID);\n}\n\nvoid CGameContext::SwapTeams()\n{\n\tif(!m_pController->IsTeamplay())\n\t\treturn;\n\t\n\tSendGameMsg(GAMEMSG_TEAM_SWAP, -1);\n\n\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t{\n\t\tif(m_apPlayers[i] && m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS)\n\t\t\tm_pController->DoTeamChange(m_apPlayers[i], m_apPlayers[i]->GetTeam()^1, false);\n\t}\n}\n\nvoid CGameContext::OnTick()\n{\n\t// check tuning\n\tCheckPureTuning();\n\n\t// copy tuning\n\tm_World.m_Core.m_Tuning = m_Tuning;\n\tm_World.Tick();\n\n\t//if(world.paused) // make sure that the game object always updates\n\tm_pController->Tick();\n\n\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t{\n\t\tif(m_apPlayers[i])\n\t\t{\n\t\t\tm_apPlayers[i]->Tick();\n\t\t\tm_apPlayers[i]->PostTick();\n\t\t}\n\t}\n\n\t// update voting\n\tif(m_VoteCloseTime)\n\t{\n\t\t// abort the kick-vote on player-leave\n\t\tif(m_VoteCloseTime == -1)\n\t\t\tEndVote(VOTE_END_ABORT, false);\n\t\telse\n\t\t{\n\t\t\tint Total = 0, Yes = 0, No = 0;\n\t\t\tif(m_VoteUpdate)\n\t\t\t{\n\t\t\t\t// count votes\n\t\t\t\tchar aaBuf[MAX_CLIENTS][NETADDR_MAXSTRSIZE] = {{0}};\n\t\t\t\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t\t\t\t\tif(m_apPlayers[i])\n\t\t\t\t\t\tServer()->GetClientAddr(i, aaBuf[i], NETADDR_MAXSTRSIZE);\n\t\t\t\tbool aVoteChecked[MAX_CLIENTS] = {0};\n\t\t\t\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t\t\t\t{\n\t\t\t\t\tif(!m_apPlayers[i] || m_apPlayers[i]->GetTeam() == TEAM_SPECTATORS || aVoteChecked[i])\t// don't count in votes by spectators\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tint ActVote = m_apPlayers[i]->m_Vote;\n\t\t\t\t\tint ActVotePos = m_apPlayers[i]->m_VotePos;\n\n\t\t\t\t\t// check for more players with the same ip (only use the vote of the one who voted first)\n\t\t\t\t\tfor(int j = i+1; j < MAX_CLIENTS; ++j)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(!m_apPlayers[j] || aVoteChecked[j] || str_comp(aaBuf[j], aaBuf[i]))\n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\taVoteChecked[j] = true;\n\t\t\t\t\t\tif(m_apPlayers[j]->m_Vote && (!ActVote || ActVotePos > m_apPlayers[j]->m_VotePos))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tActVote = m_apPlayers[j]->m_Vote;\n\t\t\t\t\t\t\tActVotePos = m_apPlayers[j]->m_VotePos;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tTotal++;\n\t\t\t\t\tif(ActVote > 0)\n\t\t\t\t\t\tYes++;\n\t\t\t\t\telse if(ActVote < 0)\n\t\t\t\t\t\tNo++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(m_VoteEnforce == VOTE_ENFORCE_YES || (m_VoteUpdate && Yes >= Total/2+1))\n\t\t\t{\n\t\t\t\tServer()->SetRconCID(IServer::RCON_CID_VOTE);\n\t\t\t\tConsole()->ExecuteLine(m_aVoteCommand);\n\t\t\t\tServer()->SetRconCID(IServer::RCON_CID_SERV);\n\t\t\t\tif(m_VoteCreator != -1 && m_apPlayers[m_VoteCreator])\n\t\t\t\t\tm_apPlayers[m_VoteCreator]->m_LastVoteCall = 0;\n\n\t\t\t\tEndVote(VOTE_END_PASS, m_VoteEnforce==VOTE_ENFORCE_YES);\n\t\t\t}\n\t\t\telse if(m_VoteEnforce == VOTE_ENFORCE_NO || (m_VoteUpdate && No >= (Total+1)/2) || time_get() > m_VoteCloseTime)\n\t\t\t\tEndVote(VOTE_END_FAIL, m_VoteEnforce==VOTE_ENFORCE_NO);\n\t\t\telse if(m_VoteUpdate)\n\t\t\t{\n\t\t\t\tm_VoteUpdate = false;\n\t\t\t\tSendVoteStatus(-1, Total, Yes, No);\n\t\t\t}\n\t\t}\n\t}\n\n\n#ifdef CONF_DEBUG\n\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t{\n\t\tif(m_apPlayers[i] && m_apPlayers[i]->IsDummy())\n\t\t{\n\t\t\tCNetObj_PlayerInput Input = {0};\n\t\t\tInput.m_Direction = (i&1)?-1:1;\n\t\t\tm_apPlayers[i]->OnPredictedInput(&Input);\n\t\t}\n\t}\n#endif\n}\n\n// Server hooks\nvoid CGameContext::OnClientDirectInput(int ClientID, void *pInput)\n{\n\tint NumCorrections = m_NetObjHandler.NumObjCorrections();\n\tif(m_NetObjHandler.ValidateObj(NETOBJTYPE_PLAYERINPUT, pInput, sizeof(CNetObj_PlayerInput)) == 0)\n\t{\n\t\tif(g_Config.m_Debug && NumCorrections != m_NetObjHandler.NumObjCorrections())\n\t\t{\n\t\t\tchar aBuf[128];\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"NETOBJTYPE_PLAYERINPUT corrected on '%s'\", m_NetObjHandler.CorrectedObjOn());\n\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"server\", aBuf);\n\t\t}\n\t\tm_apPlayers[ClientID]->OnDirectInput((CNetObj_PlayerInput *)pInput);\n\t}\n}\n\nvoid CGameContext::OnClientPredictedInput(int ClientID, void *pInput)\n{\n\tif(!m_World.m_Paused)\n\t{\n\t\tint NumCorrections = m_NetObjHandler.NumObjCorrections();\n\t\tif(m_NetObjHandler.ValidateObj(NETOBJTYPE_PLAYERINPUT, pInput, sizeof(CNetObj_PlayerInput)) == 0)\n\t\t{\n\t\t\tif(g_Config.m_Debug && NumCorrections != m_NetObjHandler.NumObjCorrections())\n\t\t\t{\n\t\t\t\tchar aBuf[128];\n\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"NETOBJTYPE_PLAYERINPUT corrected on '%s'\", m_NetObjHandler.CorrectedObjOn());\n\t\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"server\", aBuf);\n\t\t\t}\n\t\t\tm_apPlayers[ClientID]->OnPredictedInput((CNetObj_PlayerInput *)pInput);\n\t\t}\n\t}\n}\n\nvoid CGameContext::OnClientEnter(int ClientID)\n{\n\tm_pController->OnPlayerConnect(m_apPlayers[ClientID]);\n\n\tm_VoteUpdate = true;\n\n\t// update client infos (others before local)\n\tCNetMsg_Sv_ClientInfo NewClientInfoMsg;\n\tNewClientInfoMsg.m_ClientID = ClientID;\n\tNewClientInfoMsg.m_Local = 0;\n\tNewClientInfoMsg.m_Team = m_apPlayers[ClientID]->GetTeam();\n\tNewClientInfoMsg.m_pName = Server()->ClientName(ClientID);\n\tNewClientInfoMsg.m_pClan = Server()->ClientClan(ClientID);\n\tNewClientInfoMsg.m_Country = Server()->ClientCountry(ClientID);\n\tfor(int p = 0; p < 6; p++)\n\t{\n\t\tNewClientInfoMsg.m_apSkinPartNames[p] = m_apPlayers[ClientID]->m_TeeInfos.m_aaSkinPartNames[p];\n\t\tNewClientInfoMsg.m_aUseCustomColors[p] = m_apPlayers[ClientID]->m_TeeInfos.m_aUseCustomColors[p];\n\t\tNewClientInfoMsg.m_aSkinPartColors[p] = m_apPlayers[ClientID]->m_TeeInfos.m_aSkinPartColors[p];\n\t}\n\t\n\n\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t{\n\t\tif(i == ClientID || !m_apPlayers[i] || (!Server()->ClientIngame(i) && !m_apPlayers[i]->IsDummy()))\n\t\t\tcontinue;\n\n\t\t// new info for others\n\t\tif(Server()->ClientIngame(i))\n\t\t\tServer()->SendPackMsg(&NewClientInfoMsg, MSGFLAG_VITAL|MSGFLAG_NORECORD, i);\n\n\t\t// existing infos for new player\n\t\tCNetMsg_Sv_ClientInfo ClientInfoMsg;\n\t\tClientInfoMsg.m_ClientID = i;\n\t\tClientInfoMsg.m_Local = 0;\n\t\tClientInfoMsg.m_Team = m_apPlayers[i]->GetTeam();\n\t\tClientInfoMsg.m_pName = Server()->ClientName(i);\n\t\tClientInfoMsg.m_pClan = Server()->ClientClan(i);\n\t\tClientInfoMsg.m_Country = Server()->ClientCountry(i);\n\t\tfor(int p = 0; p < 6; p++)\n\t\t{\n\t\t\tClientInfoMsg.m_apSkinPartNames[p] = m_apPlayers[i]->m_TeeInfos.m_aaSkinPartNames[p];\n\t\t\tClientInfoMsg.m_aUseCustomColors[p] = m_apPlayers[i]->m_TeeInfos.m_aUseCustomColors[p];\n\t\t\tClientInfoMsg.m_aSkinPartColors[p] = m_apPlayers[i]->m_TeeInfos.m_aSkinPartColors[p];\n\t\t}\n\t\tServer()->SendPackMsg(&ClientInfoMsg, MSGFLAG_VITAL|MSGFLAG_NORECORD, ClientID);\n\t}\n\n\t// local info\n\tNewClientInfoMsg.m_Local = 1;\n\tServer()->SendPackMsg(&NewClientInfoMsg, MSGFLAG_VITAL|MSGFLAG_NORECORD, ClientID);\t\n\n\tif(Server()->DemoRecorder_IsRecording())\n\t{\n\t\tCNetMsg_De_ClientEnter Msg;\n\t\tMsg.m_pName = NewClientInfoMsg.m_pName;\n\t\tMsg.m_Team = NewClientInfoMsg.m_Team;\n\t\tServer()->SendPackMsg(&Msg, MSGFLAG_NOSEND, -1);\n\t}\n}\n\nvoid CGameContext::OnClientConnected(int ClientID, bool Dummy)\n{\n\tm_apPlayers[ClientID] = new(ClientID) CPlayer(this, ClientID, Dummy);\n\t\n\tif(Dummy)\n\t\treturn;\n\n\t// send active vote\n\tif(m_VoteCloseTime)\n\t\tSendVoteSet(VOTE_UNKNOWN, ClientID);\n\n\t// send motd\n\tSendMotd(ClientID);\n\n\t// send settings\n\tSendSettings(ClientID);\n}\n\nvoid CGameContext::OnClientTeamChange(int ClientID)\n{\n\tif(m_apPlayers[ClientID]->GetTeam() == TEAM_SPECTATORS)\n\t\tAbortVoteOnTeamChange(ClientID);\n}\n\nvoid CGameContext::OnClientDrop(int ClientID, const char *pReason)\n{\n\t// update clients on drop\n\tif(Server()->ClientIngame(ClientID))\n\t{\n\t\tif(Server()->DemoRecorder_IsRecording())\n\t\t{\n\t\t\tCNetMsg_De_ClientLeave Msg;\n\t\t\tMsg.m_pName = Server()->ClientName(ClientID);\n\t\t\tMsg.m_pReason = pReason;\n\t\t\tServer()->SendPackMsg(&Msg, MSGFLAG_NOSEND, -1);\n\t\t}\n\t\t\n\t\tCNetMsg_Sv_ClientDrop Msg;\n\t\tMsg.m_ClientID = ClientID;\n\t\tMsg.m_pReason = pReason;\n\t\tServer()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, -1);\n\t}\n\n\tAbortVoteOnDisconnect(ClientID);\n\tm_pController->OnPlayerDisconnect(m_apPlayers[ClientID]);\n\tdelete m_apPlayers[ClientID];\n\tm_apPlayers[ClientID] = 0;\n\n\tm_VoteUpdate = true;\n}\n\nvoid CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID)\n{\n\tvoid *pRawMsg = m_NetObjHandler.SecureUnpackMsg(MsgID, pUnpacker);\n\tCPlayer *pPlayer = m_apPlayers[ClientID];\n\n\tif(!pRawMsg)\n\t{\n\t\tif(g_Config.m_Debug)\n\t\t{\n\t\t\tchar aBuf[256];\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"dropped weird message '%s' (%d), failed on '%s'\", m_NetObjHandler.GetMsgName(MsgID), MsgID, m_NetObjHandler.FailedMsgOn());\n\t\t\tConsole()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"server\", aBuf);\n\t\t}\n\t\treturn;\n\t}\n\n\tif(Server()->ClientIngame(ClientID))\n\t{\n\t\tif(MsgID == NETMSGTYPE_CL_SAY)\n\t\t{\n\t\t\tCNetMsg_Cl_Say *pMsg = (CNetMsg_Cl_Say *)pRawMsg;\n\t\t\tint Team = pMsg->m_Team;\n\t\t\tif(Team)\n\t\t\t\tTeam = pPlayer->GetTeam();\n\t\t\telse\n\t\t\t\tTeam = CGameContext::CHAT_ALL;\n\n\t\t\tif(g_Config.m_SvSpamprotection && pPlayer->m_LastChat && pPlayer->m_LastChat+Server()->TickSpeed() > Server()->Tick())\n\t\t\t\treturn;\n\n\t\t\tpPlayer->m_LastChat = Server()->Tick();\n\n\t\t\t// check for invalid chars\n\t\t\tunsigned char *pMessage = (unsigned char *)pMsg->m_pMessage;\n\t\t\twhile (*pMessage)\n\t\t\t{\n\t\t\t\tif(*pMessage < 32)\n\t\t\t\t\t*pMessage = ' ';\n\t\t\t\tpMessage++;\n\t\t\t}\n\n\t\t\tSendChat(ClientID, Team, pMsg->m_pMessage);\n\t\t}\n\t\telse if(MsgID == NETMSGTYPE_CL_CALLVOTE)\n\t\t{\n\t\t\tCNetMsg_Cl_CallVote *pMsg = (CNetMsg_Cl_CallVote *)pRawMsg;\n\t\t\tint64 Now = Server()->Tick();\n\n\t\t\tif(pMsg->m_Force)\n\t\t\t{\n\t\t\t\tif(!Server()->IsAuthed(ClientID))\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif((g_Config.m_SvSpamprotection && ((pPlayer->m_LastVoteTry && pPlayer->m_LastVoteTry+Server()->TickSpeed()*3 > Now) ||\n\t\t\t\t\t(pPlayer->m_LastVoteCall && pPlayer->m_LastVoteCall+Server()->TickSpeed()*VOTE_COOLDOWN > Now))) ||\n\t\t\t\t\tpPlayer->GetTeam() == TEAM_SPECTATORS || m_VoteCloseTime)\n\t\t\t\t\treturn;\n\t\t\t\t\n\t\t\t\tpPlayer->m_LastVoteTry = Now;\n\t\t\t}\n\n\t\t\tint Type = VOTE_UNKNOWN;\n\t\t\tchar aDesc[VOTE_DESC_LENGTH] = {0};\n\t\t\tchar aCmd[VOTE_CMD_LENGTH] = {0};\n\t\t\tconst char *pReason = pMsg->m_Reason[0] ? pMsg->m_Reason : \"No reason given\";\n\n\t\t\tif(str_comp_nocase(pMsg->m_Type, \"option\") == 0)\n\t\t\t{\n\t\t\t\tCVoteOptionServer *pOption = m_pVoteOptionFirst;\n\t\t\t\twhile(pOption)\n\t\t\t\t{\n\t\t\t\t\tif(str_comp_nocase(pMsg->m_Value, pOption->m_aDescription) == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tstr_format(aDesc, sizeof(aDesc), \"%s\", pOption->m_aDescription);\n\t\t\t\t\t\tstr_format(aCmd, sizeof(aCmd), \"%s\", pOption->m_aCommand);\n\t\t\t\t\t\tif(pMsg->m_Force)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tServer()->SetRconCID(ClientID);\n\t\t\t\t\t\t\tConsole()->ExecuteLine(aCmd);\n\t\t\t\t\t\t\tServer()->SetRconCID(IServer::RCON_CID_SERV);\n\t\t\t\t\t\t\tForceVote(VOTE_START_OP, aDesc, pReason);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tType = VOTE_START_OP;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tpOption = pOption->m_pNext;\n\t\t\t\t}\n\n\t\t\t\tif(!pOption)\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if(str_comp_nocase(pMsg->m_Type, \"kick\") == 0)\n\t\t\t{\n\t\t\t\tif(!g_Config.m_SvVoteKick || m_pController->GetRealPlayerNum() < g_Config.m_SvVoteKickMin)\n\t\t\t\t\treturn;\n\n\t\t\t\tint KickID = str_toint(pMsg->m_Value);\n\t\t\t\tif(KickID < 0 || KickID >= MAX_CLIENTS || !m_apPlayers[KickID] || KickID == ClientID || Server()->IsAuthed(KickID))\n\t\t\t\t\treturn;\n\n\t\t\t\tstr_format(aDesc, sizeof(aDesc), \"Kick '%s'\", Server()->ClientName(KickID));\n\t\t\t\tif (!g_Config.m_SvVoteKickBantime)\n\t\t\t\t\tstr_format(aCmd, sizeof(aCmd), \"kick %d Kicked by vote\", KickID);\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tchar aAddrStr[NETADDR_MAXSTRSIZE] = {0};\n\t\t\t\t\tServer()->GetClientAddr(KickID, aAddrStr, sizeof(aAddrStr));\n\t\t\t\t\tstr_format(aCmd, sizeof(aCmd), \"ban %s %d Banned by vote\", aAddrStr, g_Config.m_SvVoteKickBantime);\n\t\t\t\t}\n\t\t\t\tif(pMsg->m_Force)\n\t\t\t\t{\n\t\t\t\t\tServer()->SetRconCID(ClientID);\n\t\t\t\t\tConsole()->ExecuteLine(aCmd);\n\t\t\t\t\tServer()->SetRconCID(IServer::RCON_CID_SERV);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tType = VOTE_START_KICK;\n\t\t\t\tm_VoteClientID = KickID;\n\t\t\t}\n\t\t\telse if(str_comp_nocase(pMsg->m_Type, \"spectate\") == 0)\n\t\t\t{\n\t\t\t\tif(!g_Config.m_SvVoteSpectate)\n\t\t\t\t\treturn;\n\n\t\t\t\tint SpectateID = str_toint(pMsg->m_Value);\n\t\t\t\tif(SpectateID < 0 || SpectateID >= MAX_CLIENTS || !m_apPlayers[SpectateID] || m_apPlayers[SpectateID]->GetTeam() == TEAM_SPECTATORS || SpectateID == ClientID)\n\t\t\t\t\treturn;\n\n\t\t\t\tstr_format(aDesc, sizeof(aDesc), \"move '%s' to spectators\", Server()->ClientName(SpectateID));\n\t\t\t\tstr_format(aCmd, sizeof(aCmd), \"set_team %d -1 %d\", SpectateID, g_Config.m_SvVoteSpectateRejoindelay);\n\t\t\t\tif(pMsg->m_Force)\n\t\t\t\t{\n\t\t\t\t\tServer()->SetRconCID(ClientID);\n\t\t\t\t\tConsole()->ExecuteLine(aCmd);\n\t\t\t\t\tServer()->SetRconCID(IServer::RCON_CID_SERV);\n\t\t\t\t\tForceVote(VOTE_START_SPEC, aDesc, pReason);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tType = VOTE_START_SPEC;\n\t\t\t\tm_VoteClientID = SpectateID;\n\t\t\t}\n\n\t\t\tif(Type != VOTE_UNKNOWN)\n\t\t\t{\n\t\t\t\tm_VoteCreator = ClientID;\n\t\t\t\tStartVote(Type, aDesc, aCmd, pReason);\n\t\t\t\tpPlayer->m_Vote = 1;\n\t\t\t\tpPlayer->m_VotePos = m_VotePos = 1;\n\t\t\t\tpPlayer->m_LastVoteCall = Now;\n\t\t\t}\n\t\t}\n\t\telse if(MsgID == NETMSGTYPE_CL_VOTE)\n\t\t{\n\t\t\tif(!m_VoteCloseTime)\n\t\t\t\treturn;\n\n\t\t\tif(pPlayer->m_Vote == 0)\n\t\t\t{\n\t\t\t\tCNetMsg_Cl_Vote *pMsg = (CNetMsg_Cl_Vote *)pRawMsg;\n\t\t\t\tif(!pMsg->m_Vote)\n\t\t\t\t\treturn;\n\n\t\t\t\tpPlayer->m_Vote = pMsg->m_Vote;\n\t\t\t\tpPlayer->m_VotePos = ++m_VotePos;\n\t\t\t\tm_VoteUpdate = true;\n\t\t\t}\n\t\t}\n\t\telse if(MsgID == NETMSGTYPE_CL_SETTEAM && m_pController->IsTeamChangeAllowed())\n\t\t{\n\t\t\tCNetMsg_Cl_SetTeam *pMsg = (CNetMsg_Cl_SetTeam *)pRawMsg;\n\n\t\t\tif(pPlayer->GetTeam() == pMsg->m_Team ||\n\t\t\t\t(g_Config.m_SvSpamprotection && pPlayer->m_LastSetTeam && pPlayer->m_LastSetTeam+Server()->TickSpeed()*3 > Server()->Tick()) || \n\t\t\t\t(pMsg->m_Team != TEAM_SPECTATORS && m_LockTeams) || pPlayer->m_TeamChangeTick > Server()->Tick())\n\t\t\t\treturn;\n\n\t\t\tpPlayer->m_LastSetTeam = Server()->Tick();\n\n\t\t\t// Switch team on given client and kill/respawn him\n\t\t\tif(m_pController->CanJoinTeam(pMsg->m_Team, ClientID) && m_pController->CanChangeTeam(pPlayer, pMsg->m_Team))\n\t\t\t{\n\t\t\t\tif(pPlayer->GetTeam() == TEAM_SPECTATORS || pMsg->m_Team == TEAM_SPECTATORS)\n\t\t\t\t\tm_VoteUpdate = true;\n\t\t\t\tpPlayer->m_TeamChangeTick = Server()->Tick()+Server()->TickSpeed()*3;\n\t\t\t\tm_pController->DoTeamChange(pPlayer, pMsg->m_Team);\n\t\t\t}\n\t\t}\n\t\telse if (MsgID == NETMSGTYPE_CL_SETSPECTATORMODE && !m_World.m_Paused)\n\t\t{\n\t\t\tCNetMsg_Cl_SetSpectatorMode *pMsg = (CNetMsg_Cl_SetSpectatorMode *)pRawMsg;\n\n\t\t\tif(g_Config.m_SvSpamprotection && pPlayer->m_LastSetSpectatorMode && pPlayer->m_LastSetSpectatorMode+Server()->TickSpeed()*3 > Server()->Tick())\n\t\t\t\treturn;\n\n\t\t\tpPlayer->m_LastSetSpectatorMode = Server()->Tick();\n\t\t\tif(!pPlayer->SetSpectatorID(pMsg->m_SpectatorID))\n\t\t\t\tSendGameMsg(GAMEMSG_SPEC_INVALIDID, ClientID);\n\t\t}\n\t\telse if (MsgID == NETMSGTYPE_CL_EMOTICON && !m_World.m_Paused)\n\t\t{\n\t\t\tCNetMsg_Cl_Emoticon *pMsg = (CNetMsg_Cl_Emoticon *)pRawMsg;\n\n\t\t\tif(g_Config.m_SvSpamprotection && pPlayer->m_LastEmote && pPlayer->m_LastEmote+Server()->TickSpeed()*3 > Server()->Tick())\n\t\t\t\treturn;\n\n\t\t\tpPlayer->m_LastEmote = Server()->Tick();\n\n\t\t\tSendEmoticon(ClientID, pMsg->m_Emoticon);\n\t\t}\n\t\telse if (MsgID == NETMSGTYPE_CL_KILL && !m_World.m_Paused)\n\t\t{\n\t\t\tif(pPlayer->m_LastKill && pPlayer->m_LastKill+Server()->TickSpeed()*3 > Server()->Tick())\n\t\t\t\treturn;\n\n\t\t\tpPlayer->m_LastKill = Server()->Tick();\n\t\t\tpPlayer->KillCharacter(WEAPON_SELF);\n\t\t}\n\t\telse if (MsgID == NETMSGTYPE_CL_READYCHANGE)\n\t\t{\n\t\t\tif(pPlayer->m_LastReadyChange && pPlayer->m_LastReadyChange+Server()->TickSpeed()*1 > Server()->Tick())\n\t\t\t\treturn;\n\n\t\t\tpPlayer->m_LastReadyChange = Server()->Tick();\n\t\t\tm_pController->OnPlayerReadyChange(pPlayer);\n\t\t}\n\t}\n\telse\n\t{\n\t\tif (MsgID == NETMSGTYPE_CL_STARTINFO)\n\t\t{\n\t\t\tif(pPlayer->m_IsReadyToEnter)\n\t\t\t\treturn;\n\n\t\t\tCNetMsg_Cl_StartInfo *pMsg = (CNetMsg_Cl_StartInfo *)pRawMsg;\n\t\t\tpPlayer->m_LastChangeInfo = Server()->Tick();\n\n\t\t\t// set start infos\n\t\t\tServer()->SetClientName(ClientID, pMsg->m_pName);\n\t\t\tServer()->SetClientClan(ClientID, pMsg->m_pClan);\n\t\t\tServer()->SetClientCountry(ClientID, pMsg->m_Country);\n\n\t\t\tfor(int p = 0; p < 6; p++)\n\t\t\t{\n\t\t\t\tstr_copy(pPlayer->m_TeeInfos.m_aaSkinPartNames[p], pMsg->m_apSkinPartNames[p], 24);\n\t\t\t\tpPlayer->m_TeeInfos.m_aUseCustomColors[p] = pMsg->m_aUseCustomColors[p];\n\t\t\t\tpPlayer->m_TeeInfos.m_aSkinPartColors[p] = pMsg->m_aSkinPartColors[p];\n\t\t\t}\n\n\t\t\tm_pController->OnPlayerInfoChange(pPlayer);\n\n\t\t\t// send vote options\n\t\t\tCNetMsg_Sv_VoteClearOptions ClearMsg;\n\t\t\tServer()->SendPackMsg(&ClearMsg, MSGFLAG_VITAL, ClientID);\n\n\t\t\tCVoteOptionServer *pCurrent = m_pVoteOptionFirst;\n\t\t\twhile(pCurrent)\n\t\t\t{\n\t\t\t\t// count options for actual packet\n\t\t\t\tint NumOptions = 0;\n\t\t\t\tfor(CVoteOptionServer *p = pCurrent; p && NumOptions < MAX_VOTE_OPTION_ADD; p = p->m_pNext, ++NumOptions);\n\n\t\t\t\t// pack and send vote list packet\n\t\t\t\tCMsgPacker Msg(NETMSGTYPE_SV_VOTEOPTIONLISTADD);\n\t\t\t\tMsg.AddInt(NumOptions);\n\t\t\t\twhile(pCurrent && NumOptions--)\n\t\t\t\t{\n\t\t\t\t\tMsg.AddString(pCurrent->m_aDescription, VOTE_DESC_LENGTH);\n\t\t\t\t\tpCurrent = pCurrent->m_pNext;\n\t\t\t\t}\n\t\t\t\tServer()->SendMsg(&Msg, MSGFLAG_VITAL, ClientID);\n\t\t\t}\n\n\t\t\t// send tuning parameters to client\n\t\t\tSendTuningParams(ClientID);\n\n\t\t\t// client is ready to enter\n\t\t\tpPlayer->m_IsReadyToEnter = true;\n\t\t\tCNetMsg_Sv_ReadyToEnter m;\n\t\t\tServer()->SendPackMsg(&m, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID);\n\t\t}\n\t}\n}\n\nvoid CGameContext::ConTuneParam(IConsole::IResult *pResult, void *pUserData)\n{\n\tCGameContext *pSelf = (CGameContext *)pUserData;\n\tconst char *pParamName = pResult->GetString(0);\n\tfloat NewValue = pResult->GetFloat(1);\n\n\tif(pSelf->Tuning()->Set(pParamName, NewValue))\n\t{\n\t\tchar aBuf[256];\n\t\tstr_format(aBuf, sizeof(aBuf), \"%s changed to %.2f\", pParamName, NewValue);\n\t\tpSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"tuning\", aBuf);\n\t\tpSelf->SendTuningParams(-1);\n\t}\n\telse\n\t\tpSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"tuning\", \"No such tuning parameter\");\n}\n\nvoid CGameContext::ConTuneReset(IConsole::IResult *pResult, void *pUserData)\n{\n\tCGameContext *pSelf = (CGameContext *)pUserData;\n\tCTuningParams TuningParams;\n\t*pSelf->Tuning() = TuningParams;\n\tpSelf->SendTuningParams(-1);\n\tpSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"tuning\", \"Tuning reset\");\n}\n\nvoid CGameContext::ConTuneDump(IConsole::IResult *pResult, void *pUserData)\n{\n\tCGameContext *pSelf = (CGameContext *)pUserData;\n\tchar aBuf[256];\n\tfor(int i = 0; i < pSelf->Tuning()->Num(); i++)\n\t{\n\t\tfloat v;\n\t\tpSelf->Tuning()->Get(i, &v);\n\t\tstr_format(aBuf, sizeof(aBuf), \"%s %.2f\", pSelf->Tuning()->m_apNames[i], v);\n\t\tpSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"tuning\", aBuf);\n\t}\n}\n\nvoid CGameContext::ConPause(IConsole::IResult *pResult, void *pUserData)\n{\n\tCGameContext *pSelf = (CGameContext *)pUserData;\n\n\tif(pResult->NumArguments())\n\t\tpSelf->m_pController->DoPause(clamp(pResult->GetInteger(0), -1, 1000));\n\telse\n\t\tpSelf->m_pController->DoPause(pSelf->m_pController->IsGamePaused() ? 0 : IGameController::TIMER_INFINITE);\n}\n\nvoid CGameContext::ConChangeMap(IConsole::IResult *pResult, void *pUserData)\n{\n\tCGameContext *pSelf = (CGameContext *)pUserData;\n\tpSelf->m_pController->ChangeMap(pResult->NumArguments() ? pResult->GetString(0) : \"\");\n}\n\nvoid CGameContext::ConRestart(IConsole::IResult *pResult, void *pUserData)\n{\n\tCGameContext *pSelf = (CGameContext *)pUserData;\n\tif(pResult->NumArguments())\n\t\tpSelf->m_pController->DoWarmup(clamp(pResult->GetInteger(0), -1, 1000));\n\telse\n\t\tpSelf->m_pController->DoWarmup(0);\n}\n\nvoid CGameContext::ConSay(IConsole::IResult *pResult, void *pUserData)\n{\n\tCGameContext *pSelf = (CGameContext *)pUserData;\n\tpSelf->SendChat(-1, CGameContext::CHAT_ALL, pResult->GetString(0));\n}\n\nvoid CGameContext::ConSetTeam(IConsole::IResult *pResult, void *pUserData)\n{\n\tCGameContext *pSelf = (CGameContext *)pUserData;\n\tint ClientID = clamp(pResult->GetInteger(0), 0, (int)MAX_CLIENTS-1);\n\tint Team = clamp(pResult->GetInteger(1), -1, 1);\n\tint Delay = pResult->NumArguments()>2 ? pResult->GetInteger(2) : 0;\n\tif(!pSelf->m_apPlayers[ClientID])\n\t\treturn;\n\n\tchar aBuf[256];\n\tstr_format(aBuf, sizeof(aBuf), \"moved client %d to team %d\", ClientID, Team);\n\tpSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"server\", aBuf);\n\n\tpSelf->m_apPlayers[ClientID]->m_TeamChangeTick = pSelf->Server()->Tick()+pSelf->Server()->TickSpeed()*Delay*60;\n\tpSelf->m_pController->DoTeamChange(pSelf->m_apPlayers[ClientID], Team);\n}\n\nvoid CGameContext::ConSetTeamAll(IConsole::IResult *pResult, void *pUserData)\n{\n\tCGameContext *pSelf = (CGameContext *)pUserData;\n\tint Team = clamp(pResult->GetInteger(0), -1, 1);\n\n\tpSelf->SendGameMsg(GAMEMSG_TEAM_ALL, Team, -1);\n\n\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t\tif(pSelf->m_apPlayers[i])\n\t\t\tpSelf->m_pController->DoTeamChange(pSelf->m_apPlayers[i], Team, false);\n}\n\nvoid CGameContext::ConSwapTeams(IConsole::IResult *pResult, void *pUserData)\n{\n\tCGameContext *pSelf = (CGameContext *)pUserData;\n\tpSelf->SwapTeams();\n}\n\nvoid CGameContext::ConShuffleTeams(IConsole::IResult *pResult, void *pUserData)\n{\n\tCGameContext *pSelf = (CGameContext *)pUserData;\n\tif(!pSelf->m_pController->IsTeamplay())\n\t\treturn;\n\n\tint rnd = 0;\n\tint PlayerTeam = 0;\n\tint aPlayer[MAX_CLIENTS];\n\n\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t\tif(pSelf->m_apPlayers[i] && pSelf->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS)\n\t\t\taPlayer[PlayerTeam++]=i;\n\n\tpSelf->SendGameMsg(GAMEMSG_TEAM_SHUFFLE, -1);\n\n\t//creating random permutation\n\tfor(int i = PlayerTeam; i > 1; i--)\n\t{\n\t\trnd = rand() % i;\n\t\tint tmp = aPlayer[rnd];\n\t\taPlayer[rnd] = aPlayer[i-1];\n\t\taPlayer[i-1] = tmp;\n\t}\n\t//uneven Number of Players?\n\trnd = PlayerTeam % 2 ? rand() % 2 : 0;\n\n\tfor(int i = 0; i < PlayerTeam; i++)\n\t\tpSelf->m_pController->DoTeamChange(pSelf->m_apPlayers[aPlayer[i]], i < (PlayerTeam+rnd)/2 ? TEAM_RED : TEAM_BLUE, false); \n}\n\nvoid CGameContext::ConLockTeams(IConsole::IResult *pResult, void *pUserData)\n{\n\tCGameContext *pSelf = (CGameContext *)pUserData;\n\tpSelf->m_LockTeams ^= 1;\n\tpSelf->SendSettings(-1);\n}\n\nvoid CGameContext::ConForceTeamBalance(IConsole::IResult *pResult, void *pUserData)\n{\n\tCGameContext *pSelf = (CGameContext *)pUserData;\n\tpSelf->m_pController->ForceTeamBalance();\n}\n\nvoid CGameContext::ConAddVote(IConsole::IResult *pResult, void *pUserData)\n{\n\tCGameContext *pSelf = (CGameContext *)pUserData;\n\tconst char *pDescription = pResult->GetString(0);\n\tconst char *pCommand = pResult->GetString(1);\n\n\tif(pSelf->m_NumVoteOptions == MAX_VOTE_OPTIONS)\n\t{\n\t\tpSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"server\", \"maximum number of vote options reached\");\n\t\treturn;\n\t}\n\n\t// check for valid option\n\tif(!pSelf->Console()->LineIsValid(pCommand) || str_length(pCommand) >= VOTE_CMD_LENGTH)\n\t{\n\t\tchar aBuf[256];\n\t\tstr_format(aBuf, sizeof(aBuf), \"skipped invalid command '%s'\", pCommand);\n\t\tpSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"server\", aBuf);\n\t\treturn;\n\t}\n\twhile(*pDescription && *pDescription == ' ')\n\t\tpDescription++;\n\tif(str_length(pDescription) >= VOTE_DESC_LENGTH || *pDescription == 0)\n\t{\n\t\tchar aBuf[256];\n\t\tstr_format(aBuf, sizeof(aBuf), \"skipped invalid option '%s'\", pDescription);\n\t\tpSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"server\", aBuf);\n\t\treturn;\n\t}\n\n\t// check for duplicate entry\n\tCVoteOptionServer *pOption = pSelf->m_pVoteOptionFirst;\n\twhile(pOption)\n\t{\n\t\tif(str_comp_nocase(pDescription, pOption->m_aDescription) == 0)\n\t\t{\n\t\t\tchar aBuf[256];\n\t\t\tstr_format(aBuf, sizeof(aBuf), \"option '%s' already exists\", pDescription);\n\t\t\tpSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"server\", aBuf);\n\t\t\treturn;\n\t\t}\n\t\tpOption = pOption->m_pNext;\n\t}\n\n\t// add the option\n\t++pSelf->m_NumVoteOptions;\n\tint Len = str_length(pCommand);\n\n\tpOption = (CVoteOptionServer *)pSelf->m_pVoteOptionHeap->Allocate(sizeof(CVoteOptionServer) + Len);\n\tpOption->m_pNext = 0;\n\tpOption->m_pPrev = pSelf->m_pVoteOptionLast;\n\tif(pOption->m_pPrev)\n\t\tpOption->m_pPrev->m_pNext = pOption;\n\tpSelf->m_pVoteOptionLast = pOption;\n\tif(!pSelf->m_pVoteOptionFirst)\n\t\tpSelf->m_pVoteOptionFirst = pOption;\n\n\tstr_copy(pOption->m_aDescription, pDescription, sizeof(pOption->m_aDescription));\n\tmem_copy(pOption->m_aCommand, pCommand, Len+1);\n\tchar aBuf[256];\n\tstr_format(aBuf, sizeof(aBuf), \"added option '%s' '%s'\", pOption->m_aDescription, pOption->m_aCommand);\n\tpSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"server\", aBuf);\n\n\t// inform clients about added option\n\tCNetMsg_Sv_VoteOptionAdd OptionMsg;\n\tOptionMsg.m_pDescription = pOption->m_aDescription;\n\tpSelf->Server()->SendPackMsg(&OptionMsg, MSGFLAG_VITAL, -1);\n}\n\nvoid CGameContext::ConRemoveVote(IConsole::IResult *pResult, void *pUserData)\n{\n\tCGameContext *pSelf = (CGameContext *)pUserData;\n\tconst char *pDescription = pResult->GetString(0);\n\n\t// check for valid option\n\tCVoteOptionServer *pOption = pSelf->m_pVoteOptionFirst;\n\twhile(pOption)\n\t{\n\t\tif(str_comp_nocase(pDescription, pOption->m_aDescription) == 0)\n\t\t\tbreak;\n\t\tpOption = pOption->m_pNext;\n\t}\n\tif(!pOption)\n\t{\n\t\tchar aBuf[256];\n\t\tstr_format(aBuf, sizeof(aBuf), \"option '%s' does not exist\", pDescription);\n\t\tpSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"server\", aBuf);\n\t\treturn;\n\t}\n\n\t// inform clients about removed option\n\tCNetMsg_Sv_VoteOptionRemove OptionMsg;\n\tOptionMsg.m_pDescription = pOption->m_aDescription;\n\tpSelf->Server()->SendPackMsg(&OptionMsg, MSGFLAG_VITAL, -1);\n\n\t// TODO: improve this\n\t// remove the option\n\t--pSelf->m_NumVoteOptions;\n\tchar aBuf[256];\n\tstr_format(aBuf, sizeof(aBuf), \"removed option '%s' '%s'\", pOption->m_aDescription, pOption->m_aCommand);\n\tpSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"server\", aBuf);\n\n\tCHeap *pVoteOptionHeap = new CHeap();\n\tCVoteOptionServer *pVoteOptionFirst = 0;\n\tCVoteOptionServer *pVoteOptionLast = 0;\n\tint NumVoteOptions = pSelf->m_NumVoteOptions;\n\tfor(CVoteOptionServer *pSrc = pSelf->m_pVoteOptionFirst; pSrc; pSrc = pSrc->m_pNext)\n\t{\n\t\tif(pSrc == pOption)\n\t\t\tcontinue;\n\n\t\t// copy option\n\t\tint Len = str_length(pSrc->m_aCommand);\n\t\tCVoteOptionServer *pDst = (CVoteOptionServer *)pVoteOptionHeap->Allocate(sizeof(CVoteOptionServer) + Len);\n\t\tpDst->m_pNext = 0;\n\t\tpDst->m_pPrev = pVoteOptionLast;\n\t\tif(pDst->m_pPrev)\n\t\t\tpDst->m_pPrev->m_pNext = pDst;\n\t\tpVoteOptionLast = pDst;\n\t\tif(!pVoteOptionFirst)\n\t\t\tpVoteOptionFirst = pDst;\n\n\t\tstr_copy(pDst->m_aDescription, pSrc->m_aDescription, sizeof(pDst->m_aDescription));\n\t\tmem_copy(pDst->m_aCommand, pSrc->m_aCommand, Len+1);\n\t}\n\n\t// clean up\n\tdelete pSelf->m_pVoteOptionHeap;\n\tpSelf->m_pVoteOptionHeap = pVoteOptionHeap;\n\tpSelf->m_pVoteOptionFirst = pVoteOptionFirst;\n\tpSelf->m_pVoteOptionLast = pVoteOptionLast;\n\tpSelf->m_NumVoteOptions = NumVoteOptions;\n}\n\nvoid CGameContext::ConClearVotes(IConsole::IResult *pResult, void *pUserData)\n{\n\tCGameContext *pSelf = (CGameContext *)pUserData;\n\n\tpSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"server\", \"cleared votes\");\n\tCNetMsg_Sv_VoteClearOptions VoteClearOptionsMsg;\n\tpSelf->Server()->SendPackMsg(&VoteClearOptionsMsg, MSGFLAG_VITAL, -1);\n\tpSelf->m_pVoteOptionHeap->Reset();\n\tpSelf->m_pVoteOptionFirst = 0;\n\tpSelf->m_pVoteOptionLast = 0;\n\tpSelf->m_NumVoteOptions = 0;\n}\n\nvoid CGameContext::ConVote(IConsole::IResult *pResult, void *pUserData)\n{\n\tCGameContext *pSelf = (CGameContext *)pUserData;\n\n\t// check if there is a vote running\n\tif(!pSelf->m_VoteCloseTime)\n\t\treturn;\n\n\tif(str_comp_nocase(pResult->GetString(0), \"yes\") == 0)\n\t\tpSelf->m_VoteEnforce = CGameContext::VOTE_ENFORCE_YES;\n\telse if(str_comp_nocase(pResult->GetString(0), \"no\") == 0)\n\t\tpSelf->m_VoteEnforce = CGameContext::VOTE_ENFORCE_NO;\n\tchar aBuf[256];\n\tstr_format(aBuf, sizeof(aBuf), \"forcing vote %s\", pResult->GetString(0));\n\tpSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"server\", aBuf);\n}\n\nvoid CGameContext::ConchainSpecialMotdupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)\n{\n\tpfnCallback(pResult, pCallbackUserData);\n\tif(pResult->NumArguments())\n\t{\n\t\tCGameContext *pSelf = (CGameContext *)pUserData;\n\t\tpSelf->SendMotd(-1);\n\t}\n}\n\nvoid CGameContext::ConchainSettingUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)\n{\n\tpfnCallback(pResult, pCallbackUserData);\n\tif(pResult->NumArguments())\n\t{\n\t\tCGameContext *pSelf = (CGameContext *)pUserData;\n\t\tpSelf->SendSettings(-1);\n\t}\n}\n\nvoid CGameContext::OnConsoleInit()\n{\n\tm_pServer = Kernel()->RequestInterface<IServer>();\n\tm_pConsole = Kernel()->RequestInterface<IConsole>();\n\n\tConsole()->Register(\"tune\", \"si\", CFGFLAG_SERVER, ConTuneParam, this, \"Tune variable to value\");\n\tConsole()->Register(\"tune_reset\", \"\", CFGFLAG_SERVER, ConTuneReset, this, \"Reset tuning\");\n\tConsole()->Register(\"tune_dump\", \"\", CFGFLAG_SERVER, ConTuneDump, this, \"Dump tuning\");\n\n\tConsole()->Register(\"pause\", \"?i\", CFGFLAG_SERVER|CFGFLAG_STORE, ConPause, this, \"Pause/unpause game\");\n\tConsole()->Register(\"change_map\", \"?r\", CFGFLAG_SERVER|CFGFLAG_STORE, ConChangeMap, this, \"Change map\");\n\tConsole()->Register(\"restart\", \"?i\", CFGFLAG_SERVER|CFGFLAG_STORE, ConRestart, this, \"Restart in x seconds (0 = abort)\");\n\tConsole()->Register(\"say\", \"r\", CFGFLAG_SERVER, ConSay, this, \"Say in chat\");\n\tConsole()->Register(\"set_team\", \"ii?i\", CFGFLAG_SERVER, ConSetTeam, this, \"Set team of player to team\");\n\tConsole()->Register(\"set_team_all\", \"i\", CFGFLAG_SERVER, ConSetTeamAll, this, \"Set team of all players to team\");\n\tConsole()->Register(\"swap_teams\", \"\", CFGFLAG_SERVER, ConSwapTeams, this, \"Swap the current teams\");\n\tConsole()->Register(\"shuffle_teams\", \"\", CFGFLAG_SERVER, ConShuffleTeams, this, \"Shuffle the current teams\");\n\tConsole()->Register(\"lock_teams\", \"\", CFGFLAG_SERVER, ConLockTeams, this, \"Lock/unlock teams\");\n\tConsole()->Register(\"force_teambalance\", \"\", CFGFLAG_SERVER, ConForceTeamBalance, this, \"Force team balance\");\n\n\tConsole()->Register(\"add_vote\", \"sr\", CFGFLAG_SERVER, ConAddVote, this, \"Add a voting option\");\n\tConsole()->Register(\"remove_vote\", \"s\", CFGFLAG_SERVER, ConRemoveVote, this, \"remove a voting option\");\n\tConsole()->Register(\"clear_votes\", \"\", CFGFLAG_SERVER, ConClearVotes, this, \"Clears the voting options\");\n\tConsole()->Register(\"vote\", \"r\", CFGFLAG_SERVER, ConVote, this, \"Force a vote to yes/no\");\n\n\tConsole()->Chain(\"sv_motd\", ConchainSpecialMotdupdate, this);\n\n\tConsole()->Chain(\"sv_vote_kick\", ConchainSettingUpdate, this);\n\tConsole()->Chain(\"sv_vote_kick_min\", ConchainSettingUpdate, this);\n\tConsole()->Chain(\"sv_vote_spectate\", ConchainSettingUpdate, this);\n\tConsole()->Chain(\"sv_teambalance_time\", ConchainSettingUpdate, this);\n\tConsole()->Chain(\"sv_spectator_slots\", ConchainSettingUpdate, this);\n}\n\nvoid CGameContext::OnInit()\n{\n\t// init everything\n\tm_pServer = Kernel()->RequestInterface<IServer>();\n\tm_pConsole = Kernel()->RequestInterface<IConsole>();\n\tm_World.SetGameServer(this);\n\tm_Events.SetGameServer(this);\n\n\tfor(int i = 0; i < NUM_NETOBJTYPES; i++)\n\t\tServer()->SnapSetStaticsize(i, m_NetObjHandler.GetObjSize(i));\n\n\tm_Layers.Init(Kernel());\n\tm_Collision.Init(&m_Layers);\n\n\t// select gametype\n\tif(str_comp_nocase(g_Config.m_SvGametype, \"mod\") == 0)\n\t\tm_pController = new CGameControllerMOD(this);\n\telse if(str_comp_nocase(g_Config.m_SvGametype, \"ctf\") == 0)\n\t\tm_pController = new CGameControllerCTF(this);\n\telse if(str_comp_nocase(g_Config.m_SvGametype, \"lms\") == 0)\n\t\tm_pController = new CGameControllerLMS(this);\n\telse if(str_comp_nocase(g_Config.m_SvGametype, \"sur\") == 0)\n\t\tm_pController = new CGameControllerSUR(this);\n\telse if(str_comp_nocase(g_Config.m_SvGametype, \"tdm\") == 0)\n\t\tm_pController = new CGameControllerTDM(this);\n\telse\n\t\tm_pController = new CGameControllerDM(this);\n\n\t// create all entities from the game layer\n\tCMapItemLayerTilemap *pTileMap = m_Layers.GameLayer();\n\tCTile *pTiles = (CTile *)Kernel()->RequestInterface<IMap>()->GetData(pTileMap->m_Data);\n\tfor(int y = 0; y < pTileMap->m_Height; y++)\n\t{\n\t\tfor(int x = 0; x < pTileMap->m_Width; x++)\n\t\t{\n\t\t\tint Index = pTiles[y*pTileMap->m_Width+x].m_Index;\n\n\t\t\tif(Index >= ENTITY_OFFSET)\n\t\t\t{\n\t\t\t\tvec2 Pos(x*32.0f+16.0f, y*32.0f+16.0f);\n\t\t\t\tm_pController->OnEntity(Index-ENTITY_OFFSET, Pos);\n\t\t\t}\n\t\t}\n\t}\n\n#ifdef CONF_DEBUG\n\tif(g_Config.m_DbgDummies)\n\t{\n\t\tfor(int i = 0; i < g_Config.m_DbgDummies ; i++)\n\t\t\tOnClientConnected(MAX_CLIENTS-i-1, true);\n\t}\n#endif\n}\n\nvoid CGameContext::OnShutdown()\n{\n\tdelete m_pController;\n\tm_pController = 0;\n\tClear();\n}\n\nvoid CGameContext::OnSnap(int ClientID)\n{\n\t// add tuning to demo\n\tCTuningParams StandardTuning;\n\tif(ClientID == -1 && Server()->DemoRecorder_IsRecording() && mem_comp(&StandardTuning, &m_Tuning, sizeof(CTuningParams)) != 0)\n\t{\n\t\tCNetObj_De_TuneParams *pTuneParams = static_cast<CNetObj_De_TuneParams *>(Server()->SnapNewItem(NETOBJTYPE_DE_TUNEPARAMS, 0, sizeof(CNetObj_De_TuneParams)));\n\t\tif(!pTuneParams)\n\t\t\treturn;\n\n\t\tmem_copy(pTuneParams->m_aTuneParams, &m_Tuning, sizeof(pTuneParams->m_aTuneParams));\n\t}\n\n\tm_World.Snap(ClientID);\n\tm_pController->Snap(ClientID);\n\tm_Events.Snap(ClientID);\n\n\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t{\n\t\tif(m_apPlayers[i])\n\t\t\tm_apPlayers[i]->Snap(ClientID);\n\t}\n}\nvoid CGameContext::OnPreSnap() {}\nvoid CGameContext::OnPostSnap()\n{\n\tm_World.PostSnap();\n\tm_Events.Clear();\n}\n\nbool CGameContext::IsClientReady(int ClientID)\n{\n\treturn m_apPlayers[ClientID] && m_apPlayers[ClientID]->m_IsReadyToEnter ? true : false;\n}\n\nbool CGameContext::IsClientPlayer(int ClientID)\n{\n\treturn m_apPlayers[ClientID] && m_apPlayers[ClientID]->GetTeam() == TEAM_SPECTATORS ? false : true;\n}\n\nconst char *CGameContext::GameType() { return m_pController && m_pController->GetGameType() ? m_pController->GetGameType() : \"\"; }\nconst char *CGameContext::Version() { return GAME_VERSION; }\nconst char *CGameContext::NetVersion() { return GAME_NETVERSION; }\n\nIGameServer *CreateGameServer() { return new CGameContext; }\n"
  },
  {
    "path": "src/game/server/gamecontext.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_SERVER_GAMECONTEXT_H\n#define GAME_SERVER_GAMECONTEXT_H\n\n#include <engine/console.h>\n#include <engine/server.h>\n\n#include <game/layers.h>\n#include <game/voting.h>\n\n#include \"eventhandler.h\"\n#include \"gameworld.h\"\n\n/*\n\tTick\n\t\tGame Context (CGameContext::tick)\n\t\t\tGame World (GAMEWORLD::tick)\n\t\t\t\tReset world if requested (GAMEWORLD::reset)\n\t\t\t\tAll entities in the world (ENTITY::tick)\n\t\t\t\tAll entities in the world (ENTITY::tick_defered)\n\t\t\t\tRemove entities marked for deletion (GAMEWORLD::remove_entities)\n\t\t\tGame Controller (GAMECONTROLLER::tick)\n\t\t\tAll players (CPlayer::tick)\n\n\n\tSnap\n\t\tGame Context (CGameContext::snap)\n\t\t\tGame World (GAMEWORLD::snap)\n\t\t\t\tAll entities in the world (ENTITY::snap)\n\t\t\tGame Controller (GAMECONTROLLER::snap)\n\t\t\tEvents handler (EVENT_HANDLER::snap)\n\t\t\tAll players (CPlayer::snap)\n\n*/\nclass CGameContext : public IGameServer\n{\n\tIServer *m_pServer;\n\tclass IConsole *m_pConsole;\n\tCLayers m_Layers;\n\tCCollision m_Collision;\n\tCNetObjHandler m_NetObjHandler;\n\tCTuningParams m_Tuning;\n\n\tstatic void ConTuneParam(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConTuneReset(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConTuneDump(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConPause(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConChangeMap(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConRestart(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConBroadcast(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConSay(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConSetTeam(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConSetTeamAll(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConSwapTeams(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConShuffleTeams(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConLockTeams(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConForceTeamBalance(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConAddVote(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConRemoveVote(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConClearVotes(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConVote(IConsole::IResult *pResult, void *pUserData);\n\tstatic void ConchainSpecialMotdupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData);\n\tstatic void ConchainSettingUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData);\n\n\tCGameContext(int Resetting);\n\tvoid Construct(int Resetting);\n\n\tbool m_Resetting;\npublic:\n\tIServer *Server() const { return m_pServer; }\n\tclass IConsole *Console() { return m_pConsole; }\n\tCCollision *Collision() { return &m_Collision; }\n\tCTuningParams *Tuning() { return &m_Tuning; }\n\n\tCGameContext();\n\t~CGameContext();\n\n\tvoid Clear();\n\n\tCEventHandler m_Events;\n\tclass CPlayer *m_apPlayers[MAX_CLIENTS];\n\n\tclass IGameController *m_pController;\n\tCGameWorld m_World;\n\n\t// helper functions\n\tclass CCharacter *GetPlayerChar(int ClientID);\n\n\tint m_LockTeams;\n\n\t// voting\n\tvoid StartVote(int Type, const char *pDesc, const char *pCommand, const char *pReason);\n\tvoid EndVote(int Type, bool Force);\n\tvoid ForceVote(int Type, const char *pDescription, const char *pReason);\n\tvoid SendVoteSet(int Type, int ToClientID);\n\tvoid SendVoteStatus(int ClientID, int Total, int Yes, int No);\n\tvoid AbortVoteOnDisconnect(int ClientID);\n\tvoid AbortVoteOnTeamChange(int ClientID);\n\n\tint m_VoteCreator;\n\tint64 m_VoteCloseTime;\n\tbool m_VoteUpdate;\n\tint m_VotePos;\n\tchar m_aVoteDescription[VOTE_DESC_LENGTH];\n\tchar m_aVoteCommand[VOTE_CMD_LENGTH];\n\tchar m_aVoteReason[VOTE_REASON_LENGTH];\n\tint m_VoteClientID;\n\tint m_NumVoteOptions;\n\tint m_VoteEnforce;\n\tenum\n\t{\n\t\tVOTE_ENFORCE_UNKNOWN=0,\n\t\tVOTE_ENFORCE_NO,\n\t\tVOTE_ENFORCE_YES,\n\n\t\tVOTE_TIME=25,\n\t};\n\tclass CHeap *m_pVoteOptionHeap;\n\tCVoteOptionServer *m_pVoteOptionFirst;\n\tCVoteOptionServer *m_pVoteOptionLast;\n\n\t// helper functions\n\tvoid CreateDamageInd(vec2 Pos, float AngleMod, int Amount);\n\tvoid CreateExplosion(vec2 Pos, int Owner, int Weapon, bool NoDamage);\n\tvoid CreateHammerHit(vec2 Pos);\n\tvoid CreatePlayerSpawn(vec2 Pos);\n\tvoid CreateDeath(vec2 Pos, int Who);\n\tvoid CreateSound(vec2 Pos, int Sound, int Mask=-1);\n\n\n\tenum\n\t{\n\t\tCHAT_ALL=-2,\n\t\tCHAT_SPEC=-1,\n\t\tCHAT_RED=0,\n\t\tCHAT_BLUE=1\n\t};\n\n\t// network\n\tvoid SendChatTarget(int To, const char *pText);\n\tvoid SendChat(int ClientID, int Team, const char *pText);\n\tvoid SendEmoticon(int ClientID, int Emoticon);\n\tvoid SendWeaponPickup(int ClientID, int Weapon);\n\tvoid SendMotd(int ClientID);\n\tvoid SendSettings(int ClientID);\n\n\tvoid SendGameMsg(int GameMsgID, int ClientID);\n\tvoid SendGameMsg(int GameMsgID, int ParaI1, int ClientID);\n\tvoid SendGameMsg(int GameMsgID, int ParaI1, int ParaI2, int ParaI3, int ClientID);\n\n\t//\n\tvoid CheckPureTuning();\n\tvoid SendTuningParams(int ClientID);\n\n\t//\n\tvoid SwapTeams();\n\n\t// engine events\n\tvirtual void OnInit();\n\tvirtual void OnConsoleInit();\n\tvirtual void OnShutdown();\n\n\tvirtual void OnTick();\n\tvirtual void OnPreSnap();\n\tvirtual void OnSnap(int ClientID);\n\tvirtual void OnPostSnap();\n\n\tvirtual void OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID);\n\n\tvirtual void OnClientConnected(int ClientID) { OnClientConnected(ClientID, false); }\n\tvoid OnClientConnected(int ClientID, bool Dummy);\n\tvoid OnClientTeamChange(int ClientID);\n\tvirtual void OnClientEnter(int ClientID);\n\tvirtual void OnClientDrop(int ClientID, const char *pReason);\n\tvirtual void OnClientDirectInput(int ClientID, void *pInput);\n\tvirtual void OnClientPredictedInput(int ClientID, void *pInput);\n\n\tvirtual bool IsClientReady(int ClientID);\n\tvirtual bool IsClientPlayer(int ClientID);\n\n\tvirtual const char *GameType();\n\tvirtual const char *Version();\n\tvirtual const char *NetVersion();\n};\n\ninline int CmaskAll() { return -1; }\ninline int CmaskOne(int ClientID) { return 1<<ClientID; }\ninline int CmaskAllExceptOne(int ClientID) { return 0x7fffffff^CmaskOne(ClientID); }\ninline bool CmaskIsSet(int Mask, int ClientID) { return (Mask&CmaskOne(ClientID)) != 0; }\n#endif\n"
  },
  {
    "path": "src/game/server/gamecontroller.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/shared/config.h>\n\n#include <game/mapitems.h>\n\n#include \"entities/character.h\"\n#include \"entities/pickup.h\"\n#include \"gamecontext.h\"\n#include \"gamecontroller.h\"\n#include \"player.h\"\n\n\nIGameController::IGameController(CGameContext *pGameServer)\n{\n\tm_pGameServer = pGameServer;\n\tm_pServer = m_pGameServer->Server();\n\n\t// balancing\n\tm_aTeamSize[TEAM_RED] = 0;\n\tm_aTeamSize[TEAM_BLUE] = 0;\n\tm_UnbalancedTick = TBALANCE_OK;\n\n\t// game\n\tm_GameState = IGS_GAME_RUNNING;\n\tm_GameStateTimer = TIMER_INFINITE;\n\tm_GameStartTick = Server()->Tick();\n\tm_MatchCount = 0;\n\tm_RoundCount = 0;\n\tm_SuddenDeath = 0;\n\tm_aTeamscore[TEAM_RED] = 0;\n\tm_aTeamscore[TEAM_BLUE] = 0;\n\tif(g_Config.m_SvWarmup)\n\t\tSetGameState(IGS_WARMUP_USER, g_Config.m_SvWarmup);\n\telse\n\t\tSetGameState(IGS_WARMUP_GAME, TIMER_INFINITE);\n\n\t// info\n\tm_GameFlags = 0;\n\tm_pGameType = \"unknown\";\n\tm_GameInfo.m_MatchCurrent = m_MatchCount+1;\n\tm_GameInfo.m_MatchNum = (str_length(g_Config.m_SvMaprotation) && g_Config.m_SvMatchesPerMap) ? g_Config.m_SvMatchesPerMap : 0;\n\tm_GameInfo.m_ScoreLimit = g_Config.m_SvScorelimit;\n\tm_GameInfo.m_TimeLimit = g_Config.m_SvTimelimit;\n\n\t// map\n\tm_aMapWish[0] = 0;\n\n\t// spawn\n\tm_aNumSpawnPoints[0] = 0;\n\tm_aNumSpawnPoints[1] = 0;\n\tm_aNumSpawnPoints[2] = 0;\n}\n\n//activity\nvoid IGameController::DoActivityCheck()\n{\n\tif(g_Config.m_SvInactiveKickTime == 0)\n\t\treturn;\n\n\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t{\n\t\tif(GameServer()->m_apPlayers[i] && !GameServer()->m_apPlayers[i]->IsDummy() && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS &&\n\t\t\t!Server()->IsAuthed(i) && (GameServer()->m_apPlayers[i]->m_InactivityTickCounter > g_Config.m_SvInactiveKickTime*Server()->TickSpeed()*60))\n\t\t{\n\t\t\tswitch(g_Config.m_SvInactiveKick)\n\t\t\t{\n\t\t\tcase 0:\n\t\t\t\t{\n\t\t\t\t\t// move player to spectator\n\t\t\t\t\tDoTeamChange(GameServer()->m_apPlayers[i], TEAM_SPECTATORS);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\t{\n\t\t\t\t\t// move player to spectator if the reserved slots aren't filled yet, kick him otherwise\n\t\t\t\t\tint Spectators = 0;\n\t\t\t\t\tfor(int j = 0; j < MAX_CLIENTS; ++j)\n\t\t\t\t\t\tif(GameServer()->m_apPlayers[j] && GameServer()->m_apPlayers[j]->GetTeam() == TEAM_SPECTATORS)\n\t\t\t\t\t\t\t++Spectators;\n\t\t\t\t\tif(Spectators >= g_Config.m_SvSpectatorSlots)\n\t\t\t\t\t\tServer()->Kick(i, \"Kicked for inactivity\");\n\t\t\t\t\telse\n\t\t\t\t\t\tDoTeamChange(GameServer()->m_apPlayers[i], TEAM_SPECTATORS);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\t{\n\t\t\t\t\t// kick the player\n\t\t\t\t\tServer()->Kick(i, \"Kicked for inactivity\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nbool IGameController::GetPlayersReadyState()\n{\n\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t{\n\t\tif(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS && !GameServer()->m_apPlayers[i]->m_IsReadyToPlay)\n\t\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nvoid IGameController::SetPlayersReadyState(bool ReadyState)\n{\n\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t{\n\t\tif(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS && (ReadyState || !GameServer()->m_apPlayers[i]->m_DeadSpecMode))\n\t\t\tGameServer()->m_apPlayers[i]->m_IsReadyToPlay = ReadyState;\n\t}\n}\n\n// balancing\nbool IGameController::CanBeMovedOnBalance(int ClientID) const\n{\n\treturn true;\n}\n\nvoid IGameController::CheckTeamBalance()\n{\n\tif(!IsTeamplay() || !g_Config.m_SvTeambalanceTime)\n\t{\n\t\tm_UnbalancedTick = TBALANCE_OK;\n\t\treturn;\n\t}\n\n\t// check if teams are unbalanced\n\tchar aBuf[256];\n\tif(absolute(m_aTeamSize[TEAM_RED]-m_aTeamSize[TEAM_BLUE]) >= NUM_TEAMS)\n\t{\n\t\tstr_format(aBuf, sizeof(aBuf), \"Teams are NOT balanced (red=%d blue=%d)\", m_aTeamSize[TEAM_RED], m_aTeamSize[TEAM_BLUE]);\n\t\tif(m_UnbalancedTick <= TBALANCE_OK)\n\t\t\tm_UnbalancedTick = Server()->Tick();\n\t}\n\telse\n\t{\n\t\tstr_format(aBuf, sizeof(aBuf), \"Teams are balanced (red=%d blue=%d)\", m_aTeamSize[TEAM_RED], m_aTeamSize[TEAM_BLUE]);\n\t\tm_UnbalancedTick = TBALANCE_OK;\n\t}\n\tGameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"game\", aBuf);\n}\n\nvoid IGameController::DoTeamBalance()\n{\n\tif(!IsTeamplay() || !g_Config.m_SvTeambalanceTime || absolute(m_aTeamSize[TEAM_RED]-m_aTeamSize[TEAM_BLUE]) < NUM_TEAMS)\n\t\treturn;\n\n\tGameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"game\", \"Balancing teams\");\n\n\tfloat aTeamScore[NUM_TEAMS] = {0};\n\tfloat aPlayerScore[MAX_CLIENTS] = {0.0f};\n\n\t// gather stats\n\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t{\n\t\tif(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS)\n\t\t{\n\t\t\taPlayerScore[i] = GameServer()->m_apPlayers[i]->m_Score*Server()->TickSpeed()*60.0f/\n\t\t\t\t(Server()->Tick()-GameServer()->m_apPlayers[i]->m_ScoreStartTick);\n\t\t\taTeamScore[GameServer()->m_apPlayers[i]->GetTeam()] += aPlayerScore[i];\n\t\t}\n\t}\n\n\tint BiggerTeam = (m_aTeamSize[TEAM_RED] > m_aTeamSize[TEAM_BLUE]) ? TEAM_RED : TEAM_BLUE;\n\tint NumBalance = absolute(m_aTeamSize[TEAM_RED]-m_aTeamSize[TEAM_BLUE]) / NUM_TEAMS;\n\n\t// balance teams\n\tdo\n\t{\n\t\tCPlayer *pPlayer = 0;\n\t\tfloat ScoreDiff = aTeamScore[BiggerTeam];\n\t\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t\t{\n\t\t\tif(!GameServer()->m_apPlayers[i] || !CanBeMovedOnBalance(i))\n\t\t\t\tcontinue;\n\n\t\t\t// remember the player whom would cause lowest score-difference\n\t\t\tif(GameServer()->m_apPlayers[i]->GetTeam() == BiggerTeam &&\n\t\t\t\t(!pPlayer || absolute((aTeamScore[BiggerTeam^1]+aPlayerScore[i]) - (aTeamScore[BiggerTeam]-aPlayerScore[i])) < ScoreDiff))\n\t\t\t{\n\t\t\t\tpPlayer = GameServer()->m_apPlayers[i];\n\t\t\t\tScoreDiff = absolute((aTeamScore[BiggerTeam^1]+aPlayerScore[i]) - (aTeamScore[BiggerTeam]-aPlayerScore[i]));\n\t\t\t}\n\t\t}\n\n\t\t// move the player to the other team\n\t\tint Temp = pPlayer->m_LastActionTick;\n\t\tDoTeamChange(pPlayer, BiggerTeam^1);\n\t\tpPlayer->m_LastActionTick = Temp;\n\t\tpPlayer->Respawn();\n\t\tGameServer()->SendGameMsg(GAMEMSG_TEAM_BALANCE_VICTIM, pPlayer->GetTeam(), pPlayer->GetCID());\n\t}\n\twhile(--NumBalance);\n\n\tm_UnbalancedTick = TBALANCE_OK;\n\tGameServer()->SendGameMsg(GAMEMSG_TEAM_BALANCE, -1);\n}\n\n// event\nint IGameController::OnCharacterDeath(CCharacter *pVictim, CPlayer *pKiller, int Weapon)\n{\n\t// do scoreing\n\tif(!pKiller || Weapon == WEAPON_GAME)\n\t\treturn 0;\n\tif(pKiller == pVictim->GetPlayer())\n\t\tpVictim->GetPlayer()->m_Score--; // suicide\n\telse\n\t{\n\t\tif(IsTeamplay() && pVictim->GetPlayer()->GetTeam() == pKiller->GetTeam())\n\t\t\tpKiller->m_Score--; // teamkill\n\t\telse\n\t\t\tpKiller->m_Score++; // normal kill\n\t}\n\tif(Weapon == WEAPON_SELF)\n\t\tpVictim->GetPlayer()->m_RespawnTick = Server()->Tick()+Server()->TickSpeed()*3.0f;\n\n\n\t// update spectator modes for dead players in survival\n\tif(m_GameFlags&GAMEFLAG_SURVIVAL)\n\t{\n\t\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t\t\tif(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->m_DeadSpecMode)\n\t\t\t\tGameServer()->m_apPlayers[i]->UpdateDeadSpecMode();\n\t}\n\n\treturn 0;\n}\n\nvoid IGameController::OnCharacterSpawn(CCharacter *pChr)\n{\n\tif(m_GameFlags&GAMEFLAG_SURVIVAL)\n\t{\n\t\t// give start equipment\n\t\tpChr->IncreaseHealth(10);\n\t\tpChr->IncreaseArmor(5);\n\n\t\tpChr->GiveWeapon(WEAPON_HAMMER, -1);\n\t\tpChr->GiveWeapon(WEAPON_GUN, 10);\n\t\tpChr->GiveWeapon(WEAPON_SHOTGUN, 10);\n\t\tpChr->GiveWeapon(WEAPON_GRENADE, 10);\n\t\tpChr->GiveWeapon(WEAPON_LASER, 5);\n\n\t\t// prevent respawn\n\t\tpChr->GetPlayer()->m_RespawnDisabled = GetStartRespawnState();\n\t}\n\telse\n\t{\n\t\t// default health\n\t\tpChr->IncreaseHealth(10);\n\n\t\t// give default weapons\n\t\tpChr->GiveWeapon(WEAPON_HAMMER, -1);\n\t\tpChr->GiveWeapon(WEAPON_GUN, 10);\n\t}\n}\n\nbool IGameController::OnEntity(int Index, vec2 Pos)\n{\n\t// don't add pickups in survival\n\tif(m_GameFlags&GAMEFLAG_SURVIVAL)\n\t{\n\t\tif(Index < ENTITY_SPAWN || Index > ENTITY_SPAWN_BLUE)\n\t\t\treturn false;\n\t}\n\n\tint Type = -1;\n\n\tswitch(Index)\n\t{\n\tcase ENTITY_SPAWN:\n\t\tm_aaSpawnPoints[0][m_aNumSpawnPoints[0]++] = Pos;\n\t\tbreak;\n\tcase ENTITY_SPAWN_RED:\n\t\tm_aaSpawnPoints[1][m_aNumSpawnPoints[1]++] = Pos;\n\t\tbreak;\n\tcase ENTITY_SPAWN_BLUE:\n\t\tm_aaSpawnPoints[2][m_aNumSpawnPoints[2]++] = Pos;\n\t\tbreak;\n\tcase ENTITY_ARMOR_1:\n\t\tType = PICKUP_ARMOR;\n\t\tbreak;\n\tcase ENTITY_HEALTH_1:\n\t\tType = PICKUP_HEALTH;\n\t\tbreak;\n\tcase ENTITY_WEAPON_SHOTGUN:\n\t\tType = PICKUP_SHOTGUN;\n\t\tbreak;\n\tcase ENTITY_WEAPON_GRENADE:\n\t\tType = PICKUP_GRENADE;\n\t\tbreak;\n\tcase ENTITY_WEAPON_LASER:\n\t\tType = PICKUP_LASER;\n\t\tbreak;\n\tcase ENTITY_POWERUP_NINJA:\n\t\tif(g_Config.m_SvPowerups)\n\t\t\tType = PICKUP_NINJA;\n\t}\n\n\tif(Type != -1)\n\t{\n\t\tCPickup *pPickup = new CPickup(&GameServer()->m_World, Type);\n\t\tpPickup->m_Pos = Pos;\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nvoid IGameController::OnPlayerConnect(CPlayer *pPlayer)\n{\n\tint ClientID = pPlayer->GetCID();\n\tpPlayer->Respawn();\n\n\tchar aBuf[128];\n\tstr_format(aBuf, sizeof(aBuf), \"team_join player='%d:%s' team=%d\", ClientID, Server()->ClientName(ClientID), pPlayer->GetTeam());\n\tGameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"game\", aBuf);\n\n\t// update game info\n\tUpdateGameInfo(ClientID);\n}\n\nvoid IGameController::OnPlayerDisconnect(CPlayer *pPlayer)\n{\n\tpPlayer->OnDisconnect();\n\n\tint ClientID = pPlayer->GetCID();\n\tif(Server()->ClientIngame(ClientID))\n\t{\n\t\tchar aBuf[128];\n\t\tstr_format(aBuf, sizeof(aBuf), \"leave player='%d:%s'\", ClientID, Server()->ClientName(ClientID));\n\t\tGameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, \"game\", aBuf);\n\t}\n\n\tif(pPlayer->GetTeam() != TEAM_SPECTATORS)\n\t{\n\t\t--m_aTeamSize[pPlayer->GetTeam()];\n\t\tm_UnbalancedTick = TBALANCE_CHECK;\n\t}\n}\n\nvoid IGameController::OnPlayerInfoChange(CPlayer *pPlayer)\n{\n}\n\nvoid IGameController::OnPlayerReadyChange(CPlayer *pPlayer)\n{\n\tif(g_Config.m_SvPlayerReadyMode && pPlayer->GetTeam() != TEAM_SPECTATORS && !pPlayer->m_DeadSpecMode)\n\t{\n\t\t// change players ready state\n\t\tpPlayer->m_IsReadyToPlay ^= 1;\n\n\t\t// check if it effects current game state\n\t\tswitch(m_GameState)\n\t\t{\n\t\tcase IGS_GAME_RUNNING:\n\t\t\t// one player isn't ready -> pause the game\n\t\t\tif(!pPlayer->m_IsReadyToPlay)\n\t\t\t\tSetGameState(IGS_GAME_PAUSED, TIMER_INFINITE);\n\t\t\tbreak;\n\t\tcase IGS_WARMUP_USER:\n\t\t\t// all players are ready -> end warmup\n\t\t\tif(GetPlayersReadyState())\n\t\t\t\tSetGameState(IGS_WARMUP_USER, 0);\n\t\t\tbreak;\n\t\tcase IGS_GAME_PAUSED:\n\t\t\t// all players are ready -> unpause the game\n\t\t\tif(GetPlayersReadyState())\n\t\t\t\tSetGameState(IGS_GAME_PAUSED, 0);\n\t\t\tbreak;\n\t\tcase IGS_WARMUP_GAME:\n\t\tcase IGS_START_COUNTDOWN:\n\t\tcase IGS_END_MATCH:\n\t\tcase IGS_END_ROUND:\n\t\t\t// not effected\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid IGameController::OnReset()\n{\n\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t{\n\t\tif(GameServer()->m_apPlayers[i])\n\t\t{\n\t\t\tGameServer()->m_apPlayers[i]->m_RespawnDisabled = false;\n\t\t\tGameServer()->m_apPlayers[i]->Respawn();\n\t\t\tGameServer()->m_apPlayers[i]->m_RespawnTick = Server()->Tick()+Server()->TickSpeed()/2;\n\t\t\tif(m_RoundCount == 0)\n\t\t\t{\n\t\t\t\tGameServer()->m_apPlayers[i]->m_Score = 0;\n\t\t\t\tGameServer()->m_apPlayers[i]->m_ScoreStartTick = Server()->Tick();\n\t\t\t}\n\t\t\tGameServer()->m_apPlayers[i]->m_IsReadyToPlay = true;\n\t\t}\n\t}\n}\n\n// game\nvoid IGameController::DoWincheckMatch()\n{\n\tif(IsTeamplay())\n\t{\n\t\t// check score win condition\n\t\tif((m_GameInfo.m_ScoreLimit > 0 && (m_aTeamscore[TEAM_RED] >= m_GameInfo.m_ScoreLimit || m_aTeamscore[TEAM_BLUE] >= m_GameInfo.m_ScoreLimit)) ||\n\t\t\t(m_GameInfo.m_TimeLimit > 0 && (Server()->Tick()-m_GameStartTick) >= m_GameInfo.m_TimeLimit*Server()->TickSpeed()*60))\n\t\t{\n\t\t\tif(m_aTeamscore[TEAM_RED] != m_aTeamscore[TEAM_BLUE] || m_GameFlags&GAMEFLAG_SURVIVAL)\n\t\t\t\tEndMatch();\n\t\t\telse\n\t\t\t\tm_SuddenDeath = 1;\n\t\t}\n\t}\n\telse\n\t{\n\t\t// gather some stats\n\t\tint Topscore = 0;\n\t\tint TopscoreCount = 0;\n\t\tfor(int i = 0; i < MAX_CLIENTS; i++)\n\t\t{\n\t\t\tif(GameServer()->m_apPlayers[i])\n\t\t\t{\n\t\t\t\tif(GameServer()->m_apPlayers[i]->m_Score > Topscore)\n\t\t\t\t{\n\t\t\t\t\tTopscore = GameServer()->m_apPlayers[i]->m_Score;\n\t\t\t\t\tTopscoreCount = 1;\n\t\t\t\t}\n\t\t\t\telse if(GameServer()->m_apPlayers[i]->m_Score == Topscore)\n\t\t\t\t\tTopscoreCount++;\n\t\t\t}\n\t\t}\n\n\t\t// check score win condition\n\t\tif((m_GameInfo.m_ScoreLimit > 0 && Topscore >= m_GameInfo.m_ScoreLimit) ||\n\t\t\t(m_GameInfo.m_TimeLimit > 0 && (Server()->Tick()-m_GameStartTick) >= m_GameInfo.m_TimeLimit*Server()->TickSpeed()*60))\n\t\t{\n\t\t\tif(TopscoreCount == 1)\n\t\t\t\tEndMatch();\n\t\t\telse\n\t\t\t\tm_SuddenDeath = 1;\n\t\t}\n\t}\n}\n\nvoid IGameController::ResetGame()\n{\n\t// reset the game\n\tGameServer()->m_World.m_ResetRequested = true;\n\t\n\tSetGameState(IGS_GAME_RUNNING);\n\tm_GameStartTick = Server()->Tick();\n\tm_SuddenDeath = 0;\n\n\tint MatchNum = (str_length(g_Config.m_SvMaprotation) && g_Config.m_SvMatchesPerMap) ? g_Config.m_SvMatchesPerMap : 0;\n\tif(MatchNum == 0)\n\t\tm_MatchCount = 0;\n\tbool GameInfoChanged = (m_GameInfo.m_MatchCurrent != m_MatchCount+1) || (m_GameInfo.m_MatchNum != MatchNum) ||\n\t\t\t\t\t\t\t(m_GameInfo.m_ScoreLimit != g_Config.m_SvScorelimit) || (m_GameInfo.m_TimeLimit != g_Config.m_SvTimelimit);\n\tm_GameInfo.m_MatchCurrent = m_MatchCount+1;\n\tm_GameInfo.m_MatchNum = MatchNum;\n\tm_GameInfo.m_ScoreLimit = g_Config.m_SvScorelimit;\n\tm_GameInfo.m_TimeLimit = g_Config.m_SvTimelimit;\n\tif(GameInfoChanged)\n\t\tUpdateGameInfo(-1);\n\n\t// do team-balancing\n\tDoTeamBalance();\n}\n\nvoid IGameController::SetGameState(EGameState GameState, int Timer)\n{\n\t// change game state\n\tswitch(GameState)\n\t{\n\tcase IGS_WARMUP_GAME:\n\t\t// game based warmup is only possible when game or any warmup is running\n\t\tif(m_GameState == IGS_GAME_RUNNING || m_GameState == IGS_WARMUP_GAME || m_GameState == IGS_WARMUP_USER)\n\t\t{\n\t\t\tif(Timer == TIMER_INFINITE)\n\t\t\t{\n\t\t\t\t// run warmup till there're enough players\n\t\t\t\tm_GameState = GameState;\n \t\t\t\tm_GameStateTimer = TIMER_INFINITE;\n\t\t\n\t\t\t\t// enable respawning in survival when activating warmup\n\t\t\t\tif(m_GameFlags&GAMEFLAG_SURVIVAL)\n\t\t\t\t{\n\t\t\t\t\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t\t\t\t\t\tif(GameServer()->m_apPlayers[i])\n\t\t\t\t\t\t\tGameServer()->m_apPlayers[i]->m_RespawnDisabled = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(Timer == 0)\n\t\t\t{\n\t\t\t\t// start new match\n\t\t\t\tStartMatch();\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase IGS_WARMUP_USER:\n\t\t// user based warmup is only possible when the game or a user based warmup is running\n\t\tif(m_GameState == IGS_GAME_RUNNING || m_GameState == IGS_WARMUP_USER)\n\t\t{\n\t\t\tif(Timer != 0)\n\t\t\t{\n\t\t\t\t// start warmup\n\t\t\t\tif(Timer < 0 && g_Config.m_SvPlayerReadyMode)\n\t\t\t\t{\n\t\t\t\t\t// run warmup till all players are ready\n\t\t\t\t\tm_GameState = GameState;\n \t\t\t\t\tm_GameStateTimer = TIMER_INFINITE;\n \t\t\t\t\tSetPlayersReadyState(false);\n\t\t\t\t}\n\t\t\t\telse if(Timer > 0)\n\t\t\t\t{\n\t\t\t\t\t// run warmup for a specific time intervall\n\t\t\t\t\tm_GameState = GameState;\n\t\t\t\t\tm_GameStateTimer = Timer*Server()->TickSpeed();\n\t\t\t\t}\n\t\t\n\t\t\t\t// enable respawning in survival when activating warmup\n\t\t\t\tif(m_GameFlags&GAMEFLAG_SURVIVAL)\n\t\t\t\t{\n\t\t\t\t\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t\t\t\t\t\tif(GameServer()->m_apPlayers[i])\n\t\t\t\t\t\t\tGameServer()->m_apPlayers[i]->m_RespawnDisabled = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// start new match\n\t\t\t\tStartMatch();\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase IGS_START_COUNTDOWN:\n\t\t// only possible when game, pause or start countdown is running\n\t\tif(m_GameState == IGS_GAME_RUNNING || m_GameState == IGS_GAME_PAUSED || m_GameState == IGS_START_COUNTDOWN)\n\t\t{\n\t\t\tm_GameState = GameState;\n\t\t\tm_GameStateTimer = 3*Server()->TickSpeed();\n\t\t\tGameServer()->m_World.m_Paused = true;\n\t\t}\n\t\tbreak;\n\tcase IGS_GAME_RUNNING:\n\t\t// always possible\n\t\t{\n\t\t\tm_GameState = GameState;\n\t\t\tm_GameStateTimer = TIMER_INFINITE;\n\t\t\tSetPlayersReadyState(true);\n\t\t\tGameServer()->m_World.m_Paused = false;\n\t\t}\n\t\tbreak;\n\tcase IGS_GAME_PAUSED:\n\t\t// only possible when game is running or paused\n\t\tif(m_GameState == IGS_GAME_RUNNING || m_GameState == IGS_GAME_PAUSED)\n\t\t{\n\t\t\tif(Timer != 0)\n\t\t\t{\n\t\t\t\t// start pause\n\t\t\t\tif(Timer < 0)\n\t\t\t\t{\n\t\t\t\t\t// pauses infinitely till all players are ready or disabled via rcon command\n\t\t\t\t\tm_GameStateTimer = TIMER_INFINITE;\n\t\t\t\t\tSetPlayersReadyState(false);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// pauses for a specific time intervall\n\t\t\t\t\tm_GameStateTimer = Timer*Server()->TickSpeed();\n\t\t\t\t}\n\n\t\t\t\tm_GameState = GameState;\n\t\t\t\tGameServer()->m_World.m_Paused = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// start a countdown to end pause\n\t\t\t\tSetGameState(IGS_START_COUNTDOWN);\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase IGS_END_ROUND:\n\tcase IGS_END_MATCH:\n\t\t// only possible when game is running or over\n\t\tif(m_GameState == IGS_GAME_RUNNING || m_GameState == IGS_END_MATCH || m_GameState == IGS_END_ROUND || m_GameState == IGS_GAME_PAUSED)\n\t\t{\n\t\t\tm_GameState = GameState;\n\t\t\tm_GameStateTimer = Timer*Server()->TickSpeed();\n\t\t\tm_SuddenDeath = 0;\n\t\t\tGameServer()->m_World.m_Paused = true;\n\t\t}\n\t}\n}\n\nvoid IGameController::StartMatch()\n{\n\tResetGame();\n\n\tm_RoundCount = 0;\n\tm_aTeamscore[TEAM_RED] = 0;\n\tm_aTeamscore[TEAM_BLUE] = 0;\n\n\t// start countdown if there're enough players, otherwise do warmup till there're\n\tif(HasEnoughPlayers())\n\t\tSetGameState(IGS_START_COUNTDOWN);\n\telse\n\t\tSetGameState(IGS_WARMUP_GAME, TIMER_INFINITE);\n\n\tServer()->DemoRecorder_HandleAutoStart();\n\tchar aBuf[256];\n\tstr_format(aBuf, sizeof(aBuf), \"start match type='%s' teamplay='%d'\", m_pGameType, m_GameFlags&GAMEFLAG_TEAMS);\n\tGameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"game\", aBuf);\n}\n\nvoid IGameController::StartRound()\n{\n\tResetGame();\n\n\t++m_RoundCount;\n\n\t// start countdown if there're enough players, otherwise abort to warmup\n\tif(HasEnoughPlayers())\n\t\tSetGameState(IGS_START_COUNTDOWN);\n\telse\n\t\tSetGameState(IGS_WARMUP_GAME, TIMER_INFINITE);\n}\n\n// general\nvoid IGameController::Snap(int SnappingClient)\n{\n\tCNetObj_GameData *pGameData = static_cast<CNetObj_GameData *>(Server()->SnapNewItem(NETOBJTYPE_GAMEDATA, 0, sizeof(CNetObj_GameData)));\n\tif(!pGameData)\n\t\treturn;\n\n\tpGameData->m_GameStartTick = m_GameStartTick;\n\tpGameData->m_GameStateFlags = 0;\n\tpGameData->m_GameStateEndTick = 0; // no timer/infinite = 0, on end = GameEndTick, otherwise = GameStateEndTick\n\tswitch(m_GameState)\n\t{\n\tcase IGS_WARMUP_GAME:\n\tcase IGS_WARMUP_USER:\n\t\tpGameData->m_GameStateFlags |= GAMESTATEFLAG_WARMUP;\n\t\tif(m_GameStateTimer != TIMER_INFINITE)\n\t\t\tpGameData->m_GameStateEndTick = Server()->Tick()+m_GameStateTimer;\n\t\tbreak;\n\tcase IGS_START_COUNTDOWN:\n\t\tpGameData->m_GameStateFlags |= GAMESTATEFLAG_STARTCOUNTDOWN|GAMESTATEFLAG_PAUSED;\n\t\tif(m_GameStateTimer != TIMER_INFINITE)\n\t\t\tpGameData->m_GameStateEndTick = Server()->Tick()+m_GameStateTimer;\n\t\tbreak;\n\tcase IGS_GAME_PAUSED:\n\t\tpGameData->m_GameStateFlags |= GAMESTATEFLAG_PAUSED;\n\t\tif(m_GameStateTimer != TIMER_INFINITE)\n\t\t\tpGameData->m_GameStateEndTick = Server()->Tick()+m_GameStateTimer;\n\t\tbreak;\n\tcase IGS_END_ROUND:\n\t\tpGameData->m_GameStateFlags |= GAMESTATEFLAG_ROUNDOVER;\n\t\tpGameData->m_GameStateEndTick = Server()->Tick()-m_GameStartTick-TIMER_END*Server()->TickSpeed()+m_GameStateTimer;\n\t\tbreak;\n\tcase IGS_END_MATCH:\n\t\tpGameData->m_GameStateFlags |= GAMESTATEFLAG_GAMEOVER;\n\t\tpGameData->m_GameStateEndTick = Server()->Tick()-m_GameStartTick-TIMER_END*Server()->TickSpeed()+m_GameStateTimer;\n\t\tbreak;\n\tcase IGS_GAME_RUNNING:\n\t\t// not effected\n\t\tbreak;\n\t}\n\tif(m_SuddenDeath)\n\t\tpGameData->m_GameStateFlags |= GAMESTATEFLAG_SUDDENDEATH;\n\n\tif(IsTeamplay())\n\t{\n\t\tCNetObj_GameDataTeam *pGameDataTeam = static_cast<CNetObj_GameDataTeam *>(Server()->SnapNewItem(NETOBJTYPE_GAMEDATATEAM, 0, sizeof(CNetObj_GameDataTeam)));\n\t\tif(!pGameDataTeam)\n\t\t\treturn;\n\n\t\tpGameDataTeam->m_TeamscoreRed = m_aTeamscore[TEAM_RED];\n\t\tpGameDataTeam->m_TeamscoreBlue = m_aTeamscore[TEAM_BLUE];\n\t}\n\n\t// demo recording\n\tif(SnappingClient == -1)\n\t{\n\t\tCNetObj_De_GameInfo *pGameInfo = static_cast<CNetObj_De_GameInfo *>(Server()->SnapNewItem(NETOBJTYPE_DE_GAMEINFO, 0, sizeof(CNetObj_De_GameInfo)));\n\t\tif(!pGameInfo)\n\t\t\treturn;\n\n\t\tpGameInfo->m_GameFlags = m_GameFlags;\n\t\tpGameInfo->m_ScoreLimit = m_GameInfo.m_ScoreLimit;\n\t\tpGameInfo->m_TimeLimit = m_GameInfo.m_TimeLimit;\n\t\tpGameInfo->m_MatchNum = m_GameInfo.m_MatchNum;\n\t\tpGameInfo->m_MatchCurrent = m_GameInfo.m_MatchCurrent;\n\t}\n}\n\nvoid IGameController::Tick()\n{\n\t// handle game states\n\tif(m_GameState != IGS_GAME_RUNNING)\n\t{\n\t\tif(m_GameStateTimer > 0)\n\t\t\t--m_GameStateTimer;\n\n\t\tif(m_GameStateTimer == 0)\n\t\t{\n\t\t\t// timer fires\n\t\t\tswitch(m_GameState)\n\t\t\t{\n\t\t\tcase IGS_WARMUP_USER:\n\t\t\t\t// end warmup\n\t\t\t\tSetGameState(IGS_WARMUP_USER, 0);\n\t\t\t\tbreak;\n\t\t\tcase IGS_START_COUNTDOWN:\n\t\t\t\t// unpause the game\n\t\t\t\tSetGameState(IGS_GAME_RUNNING);\n\t\t\t\tbreak;\n\t\t\tcase IGS_GAME_PAUSED:\n\t\t\t\t// end pause\n\t\t\t\tSetGameState(IGS_GAME_PAUSED, 0);\n\t\t\t\tbreak;\n\t\t\tcase IGS_END_ROUND:\n\t\t\t\t// check if the match is over otherwise start next round\n\t\t\t\tDoWincheckMatch();\n\t\t\t\tif(m_GameState != IGS_END_MATCH)\n\t\t\t\t\tStartRound();\n\t\t\t\tbreak;\n\t\t\tcase IGS_END_MATCH:\n\t\t\t\t// start next match\n\t\t\t\tCycleMap();\n\t\t\t\tm_MatchCount++;\n\t\t\t\tStartMatch();\n\t\t\t\tbreak;\n\t\t\tcase IGS_WARMUP_GAME:\n\t\t\tcase IGS_GAME_RUNNING:\n\t\t\t\t// not effected\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// timer still running\n\t\t\tswitch(m_GameState)\n \t\t\t{\n\t\t\tcase IGS_WARMUP_USER:\n\t\t\t\t// check if player ready mode was disabled and it waits that all players are ready -> end warmup\n\t\t\t\tif(!g_Config.m_SvPlayerReadyMode && m_GameStateTimer == TIMER_INFINITE)\n\t\t\t\t\tSetGameState(IGS_WARMUP_USER, 0);\n\t\t\t\tbreak;\n\t\t\tcase IGS_START_COUNTDOWN:\n\t\t\tcase IGS_GAME_PAUSED:\n\t\t\t\t// freeze the game\n\t\t\t\t++m_GameStartTick;\n\t\t\t\tbreak;\n\t\t\tcase IGS_WARMUP_GAME:\n\t\t\tcase IGS_GAME_RUNNING:\n\t\t\tcase IGS_END_MATCH:\n\t\t\tcase IGS_END_ROUND:\n\t\t\t\t// not effected\n\t\t\t\tbreak;\n \t\t\t}\n\t\t}\n\t}\n\n\t// do team-balancing (skip this in survival, done there when a round starts)\n\tif(IsTeamplay() && !(m_GameFlags&GAMEFLAG_SURVIVAL))\n\t{\n\t\tswitch(m_UnbalancedTick)\n\t\t{\n\t\tcase TBALANCE_CHECK:\n\t\t\tCheckTeamBalance();\n\t\t\tbreak;\n\t\tcase TBALANCE_OK:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif(Server()->Tick() > m_UnbalancedTick+g_Config.m_SvTeambalanceTime*Server()->TickSpeed()*60)\n\t\t\t\tDoTeamBalance();\n\t\t}\n\t}\n\n\t// check for inactive players\n\tDoActivityCheck();\n\n\t// win check\n\tif((m_GameState == IGS_GAME_RUNNING || m_GameState == IGS_GAME_PAUSED) && !GameServer()->m_World.m_ResetRequested)\n\t{\n\t\tif(m_GameFlags&GAMEFLAG_SURVIVAL)\n\t\t\tDoWincheckRound();\n\t\telse\n\t\t\tDoWincheckMatch();\n\t}\n}\n\n// info\nbool IGameController::IsFriendlyFire(int ClientID1, int ClientID2) const\n{\n\tif(ClientID1 == ClientID2)\n\t\treturn false;\n\n\tif(IsTeamplay())\n\t{\n\t\tif(!GameServer()->m_apPlayers[ClientID1] || !GameServer()->m_apPlayers[ClientID2])\n\t\t\treturn false;\n\n\t\tif(!g_Config.m_SvTeamdamage && GameServer()->m_apPlayers[ClientID1]->GetTeam() == GameServer()->m_apPlayers[ClientID2]->GetTeam())\n\t\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nbool IGameController::IsPlayerReadyMode() const\n{\n\treturn g_Config.m_SvPlayerReadyMode != 0 && (m_GameStateTimer == TIMER_INFINITE && (m_GameState == IGS_WARMUP_USER || m_GameState == IGS_GAME_PAUSED));\n}\n\nbool IGameController::IsTeamChangeAllowed() const\n{\n\treturn !GameServer()->m_World.m_Paused || (m_GameState == IGS_START_COUNTDOWN && m_GameStartTick == Server()->Tick());\n}\n\nvoid IGameController::UpdateGameInfo(int ClientID)\n{\n\tCNetMsg_Sv_GameInfo GameInfoMsg;\n\tGameInfoMsg.m_GameFlags = m_GameFlags;\n\tGameInfoMsg.m_ScoreLimit = m_GameInfo.m_ScoreLimit;\n\tGameInfoMsg.m_TimeLimit = m_GameInfo.m_TimeLimit;\n\tGameInfoMsg.m_MatchNum = m_GameInfo.m_MatchNum;\n\tGameInfoMsg.m_MatchCurrent = m_GameInfo.m_MatchCurrent;\n\n\tif(ClientID == -1)\n\t{\n\t\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t\t{\n\t\t\tif(!GameServer()->m_apPlayers[i] || !Server()->ClientIngame(i))\n\t\t\t\tcontinue;\n\n\t\t\tServer()->SendPackMsg(&GameInfoMsg, MSGFLAG_VITAL|MSGFLAG_NORECORD, i);\n\t\t}\n\t}\n\telse\n\t\tServer()->SendPackMsg(&GameInfoMsg, MSGFLAG_VITAL|MSGFLAG_NORECORD, ClientID);\n}\n\n// map\nstatic bool IsSeparator(char c) { return c == ';' || c == ' ' || c == ',' || c == '\\t'; }\n\nvoid IGameController::ChangeMap(const char *pToMap)\n{\n\tstr_copy(m_aMapWish, pToMap, sizeof(m_aMapWish));\n\tEndMatch();\n}\n\nvoid IGameController::CycleMap()\n{\n\tif(m_aMapWish[0] != 0)\n\t{\n\t\tchar aBuf[256];\n\t\tstr_format(aBuf, sizeof(aBuf), \"rotating map to %s\", m_aMapWish);\n\t\tGameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"game\", aBuf);\n\t\tstr_copy(g_Config.m_SvMap, m_aMapWish, sizeof(g_Config.m_SvMap));\n\t\tm_aMapWish[0] = 0;\n\t\tm_MatchCount = 0;\n\t\treturn;\n\t}\n\tif(!str_length(g_Config.m_SvMaprotation))\n\t\treturn;\n\n\tif(m_MatchCount < m_GameInfo.m_MatchNum-1)\n\t{\n\t\tif(g_Config.m_SvMatchSwap)\n\t\t\tGameServer()->SwapTeams();\n\t\treturn;\n\t}\n\n\t// handle maprotation\n\tconst char *pMapRotation = g_Config.m_SvMaprotation;\n\tconst char *pCurrentMap = g_Config.m_SvMap;\n\n\tint CurrentMapLen = str_length(pCurrentMap);\n\tconst char *pNextMap = pMapRotation;\n\twhile(*pNextMap)\n\t{\n\t\tint WordLen = 0;\n\t\twhile(pNextMap[WordLen] && !IsSeparator(pNextMap[WordLen]))\n\t\t\tWordLen++;\n\n\t\tif(WordLen == CurrentMapLen && str_comp_num(pNextMap, pCurrentMap, CurrentMapLen) == 0)\n\t\t{\n\t\t\t// map found\n\t\t\tpNextMap += CurrentMapLen;\n\t\t\twhile(*pNextMap && IsSeparator(*pNextMap))\n\t\t\t\tpNextMap++;\n\n\t\t\tbreak;\n\t\t}\n\n\t\tpNextMap++;\n\t}\n\n\t// restart rotation\n\tif(pNextMap[0] == 0)\n\t\tpNextMap = pMapRotation;\n\n\t// cut out the next map\n\tchar aBuf[512] = {0};\n\tfor(int i = 0; i < 511; i++)\n\t{\n\t\taBuf[i] = pNextMap[i];\n\t\tif(IsSeparator(pNextMap[i]) || pNextMap[i] == 0)\n\t\t{\n\t\t\taBuf[i] = 0;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// skip spaces\n\tint i = 0;\n\twhile(IsSeparator(aBuf[i]))\n\t\ti++;\n\n\tm_MatchCount = 0;\n\n\tchar aBufMsg[256];\n\tstr_format(aBufMsg, sizeof(aBufMsg), \"rotating map to %s\", &aBuf[i]);\n\tGameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"game\", aBuf);\n\tstr_copy(g_Config.m_SvMap, &aBuf[i], sizeof(g_Config.m_SvMap));\n}\n\n// spawn\nbool IGameController::CanSpawn(int Team, vec2 *pOutPos) const\n{\n\t// spectators can't spawn\n\tif(Team == TEAM_SPECTATORS || GameServer()->m_World.m_Paused || GameServer()->m_World.m_ResetRequested)\n\t\treturn false;\n\n\tCSpawnEval Eval;\n\n\tif(IsTeamplay())\n\t{\n\t\tEval.m_FriendlyTeam = Team;\n\n\t\t// first try own team spawn, then normal spawn and then enemy\n\t\tEvaluateSpawnType(&Eval, 1+(Team&1));\n\t\tif(!Eval.m_Got)\n\t\t{\n\t\t\tEvaluateSpawnType(&Eval, 0);\n\t\t\tif(!Eval.m_Got)\n\t\t\t\tEvaluateSpawnType(&Eval, 1+((Team+1)&1));\n\t\t}\n\t}\n\telse\n\t{\n\t\tEvaluateSpawnType(&Eval, 0);\n\t\tEvaluateSpawnType(&Eval, 1);\n\t\tEvaluateSpawnType(&Eval, 2);\n\t}\n\n\t*pOutPos = Eval.m_Pos;\n\treturn Eval.m_Got;\n}\n\nfloat IGameController::EvaluateSpawnPos(CSpawnEval *pEval, vec2 Pos) const\n{\n\tfloat Score = 0.0f;\n\tCCharacter *pC = static_cast<CCharacter *>(GameServer()->m_World.FindFirst(CGameWorld::ENTTYPE_CHARACTER));\n\tfor(; pC; pC = (CCharacter *)pC->TypeNext())\n\t{\n\t\t// team mates are not as dangerous as enemies\n\t\tfloat Scoremod = 1.0f;\n\t\tif(pEval->m_FriendlyTeam != -1 && pC->GetPlayer()->GetTeam() == pEval->m_FriendlyTeam)\n\t\t\tScoremod = 0.5f;\n\n\t\tfloat d = distance(Pos, pC->m_Pos);\n\t\tScore += Scoremod * (d == 0 ? 1000000000.0f : 1.0f/d);\n\t}\n\n\treturn Score;\n}\n\nvoid IGameController::EvaluateSpawnType(CSpawnEval *pEval, int Type) const\n{\n\t// get spawn point\n\tfor(int i = 0; i < m_aNumSpawnPoints[Type]; i++)\n\t{\n\t\t// check if the position is occupado\n\t\tCCharacter *aEnts[MAX_CLIENTS];\n\t\tint Num = GameServer()->m_World.FindEntities(m_aaSpawnPoints[Type][i], 64, (CEntity**)aEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER);\n\t\tvec2 Positions[5] = { vec2(0.0f, 0.0f), vec2(-32.0f, 0.0f), vec2(0.0f, -32.0f), vec2(32.0f, 0.0f), vec2(0.0f, 32.0f) };\t// start, left, up, right, down\n\t\tint Result = -1;\n\t\tfor(int Index = 0; Index < 5 && Result == -1; ++Index)\n\t\t{\n\t\t\tResult = Index;\n\t\t\tfor(int c = 0; c < Num; ++c)\n\t\t\t\tif(GameServer()->Collision()->CheckPoint(m_aaSpawnPoints[Type][i]+Positions[Index]) ||\n\t\t\t\t\tdistance(aEnts[c]->m_Pos, m_aaSpawnPoints[Type][i]+Positions[Index]) <= aEnts[c]->m_ProximityRadius)\n\t\t\t\t{\n\t\t\t\t\tResult = -1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t}\n\t\tif(Result == -1)\n\t\t\tcontinue;\t// try next spawn point\n\n\t\tvec2 P = m_aaSpawnPoints[Type][i]+Positions[Result];\n\t\tfloat S = EvaluateSpawnPos(pEval, P);\n\t\tif(!pEval->m_Got || pEval->m_Score > S)\n\t\t{\n\t\t\tpEval->m_Got = true;\n\t\t\tpEval->m_Score = S;\n\t\t\tpEval->m_Pos = P;\n\t\t}\n\t}\n}\n\nbool IGameController::GetStartRespawnState() const\n{\n\tif(m_GameFlags&GAMEFLAG_SURVIVAL)\n\t{\n\t\t// players can always respawn during warmup or match/round start countdown\n\t\tif(m_GameState == IGS_WARMUP_GAME || m_GameState == IGS_WARMUP_USER || (m_GameState == IGS_START_COUNTDOWN && m_GameStartTick == Server()->Tick()))\n\t\t\treturn false;\n\t\telse\n\t\t\treturn true;\n\t}\n\telse\n\t\treturn false;\n}\n\n// team\nbool IGameController::CanChangeTeam(CPlayer *pPlayer, int JoinTeam) const\n{\n\tif(!IsTeamplay() || JoinTeam == TEAM_SPECTATORS || !g_Config.m_SvTeambalanceTime)\n\t\treturn true;\n\n\t// simulate what would happen if the player changes team\n\tint aPlayerCount[NUM_TEAMS] = { m_aTeamSize[TEAM_RED], m_aTeamSize[TEAM_BLUE] };\n\taPlayerCount[JoinTeam]++;\n\tif(pPlayer->GetTeam() != TEAM_SPECTATORS)\n\t\taPlayerCount[JoinTeam^1]--;\n\n\t// check if the player-difference decreases or is smaller than 2\n\treturn aPlayerCount[JoinTeam]-aPlayerCount[JoinTeam^1] < NUM_TEAMS;\n}\n\nbool IGameController::CanJoinTeam(int Team, int NotThisID) const\n{\n\tif(Team == TEAM_SPECTATORS)\n\t\treturn true;\n\n\t// check if there're enough player slots left\n\tint TeamMod = GameServer()->m_apPlayers[NotThisID] && GameServer()->m_apPlayers[NotThisID]->GetTeam() != TEAM_SPECTATORS ? -1 : 0;\n\treturn TeamMod+m_aTeamSize[TEAM_RED]+m_aTeamSize[TEAM_BLUE] < Server()->MaxClients()-g_Config.m_SvSpectatorSlots;\n}\n\nint IGameController::ClampTeam(int Team) const\n{\n\tif(Team < TEAM_RED)\n\t\treturn TEAM_SPECTATORS;\n\tif(IsTeamplay())\n\t\treturn Team&1;\n\treturn TEAM_RED;\n}\n\nvoid IGameController::DoTeamChange(CPlayer *pPlayer, int Team, bool DoChatMsg)\n{\n\tTeam = ClampTeam(Team);\n\tif(Team == pPlayer->GetTeam())\n\t\treturn;\n\n\tint OldTeam = pPlayer->GetTeam();\n\tpPlayer->SetTeam(Team);\n\n\tint ClientID = pPlayer->GetCID();\n\n\t// notify clients\n\tCNetMsg_Sv_Team Msg;\n\tMsg.m_ClientID = ClientID;\n\tMsg.m_Team = Team;\n\tMsg.m_Silent = DoChatMsg ? 0 : 1;\n\tMsg.m_CooldownTick = pPlayer->m_TeamChangeTick;\n\tServer()->SendPackMsg(&Msg, MSGFLAG_VITAL, -1);\n\n\tchar aBuf[128];\n\tstr_format(aBuf, sizeof(aBuf), \"team_join player='%d:%s' m_Team=%d\", ClientID, Server()->ClientName(ClientID), Team);\n\tGameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"game\", aBuf);\n\n\t// update effected game settings\n\tif(OldTeam != TEAM_SPECTATORS)\n\t{\n\t\t--m_aTeamSize[OldTeam];\n\t\tm_UnbalancedTick = TBALANCE_CHECK;\n\t}\n\tif(Team != TEAM_SPECTATORS)\n\t{\n\t\t++m_aTeamSize[Team];\n\t\tm_UnbalancedTick = TBALANCE_CHECK;\n\t\tif(m_GameState == IGS_WARMUP_GAME && HasEnoughPlayers())\n\t\t\tSetGameState(IGS_WARMUP_GAME, 0);\n\t\tpPlayer->m_IsReadyToPlay = !IsPlayerReadyMode();\n\t\tif(m_GameFlags&GAMEFLAG_SURVIVAL)\n\t\t\tpPlayer->m_RespawnDisabled = GetStartRespawnState();\n\t}\n\tOnPlayerInfoChange(pPlayer);\n\tGameServer()->OnClientTeamChange(ClientID);\n}\n\nint IGameController::GetStartTeam()\n{\n\t// this will force the auto balancer to work overtime aswell\n\tif(g_Config.m_DbgStress)\n\t\treturn TEAM_RED;\n\n\tif(g_Config.m_SvTournamentMode)\n\t\treturn TEAM_SPECTATORS;\n\n\t// determine new team\n\tint Team = TEAM_RED;\n\tif(IsTeamplay())\n\t\tTeam = m_aTeamSize[TEAM_RED] > m_aTeamSize[TEAM_BLUE] ? TEAM_BLUE : TEAM_RED;\n\n\t// check if there're enough player slots left\n\tif(m_aTeamSize[TEAM_RED]+m_aTeamSize[TEAM_BLUE] < Server()->MaxClients()-g_Config.m_SvSpectatorSlots)\n\t{\n\t\t++m_aTeamSize[Team];\n\t\tm_UnbalancedTick = TBALANCE_CHECK;\n\t\tif(m_GameState == IGS_WARMUP_GAME && HasEnoughPlayers())\n\t\t\tSetGameState(IGS_WARMUP_GAME, 0);\n\t\treturn Team;\n\t}\n\treturn TEAM_SPECTATORS;\n}\n"
  },
  {
    "path": "src/game/server/gamecontroller.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_SERVER_GAMECONTROLLER_H\n#define GAME_SERVER_GAMECONTROLLER_H\n\n#include <base/vmath.h>\n\n#include <game/generated/protocol.h>\n\n/*\n\tClass: Game Controller\n\t\tControls the main game logic. Keeping track of team and player score,\n\t\twinning conditions and specific game logic.\n*/\nclass IGameController\n{\n\tclass CGameContext *m_pGameServer;\n\tclass IServer *m_pServer;\n\n\t// activity\n\tvoid DoActivityCheck();\n\tbool GetPlayersReadyState();\n\tvoid SetPlayersReadyState(bool ReadyState);\n\n\t// balancing\n\tenum\n\t{\n\t\tTBALANCE_CHECK=-2,\n\t\tTBALANCE_OK,\n\t};\n\tint m_aTeamSize[NUM_TEAMS];\n\tint m_UnbalancedTick;\n\n\tvirtual bool CanBeMovedOnBalance(int ClientID) const;\n\tvoid CheckTeamBalance();\n\tvoid DoTeamBalance();\n\n\t// game\n\tenum EGameState\n\t{\n\t\t// internal game states\n\t\tIGS_WARMUP_GAME,\t\t// warmup started by game because there're not enough players (infinite)\n\t\tIGS_WARMUP_USER,\t\t// warmup started by user action via rcon or new match (infinite or timer)\n\n\t\tIGS_START_COUNTDOWN,\t// start countown to unpause the game or start match/round (tick timer)\n\n\t\tIGS_GAME_PAUSED,\t\t// game paused (infinite or tick timer)\n\t\tIGS_GAME_RUNNING,\t\t// game running (infinite)\n\t\t\n\t\tIGS_END_MATCH,\t\t\t// match is over (tick timer)\n\t\tIGS_END_ROUND,\t\t\t// round is over (tick timer)\n \t};\n\tEGameState m_GameState;\n\tint m_GameStateTimer;\n\n\tvirtual void DoWincheckMatch();\n\tvirtual void DoWincheckRound() {};\n\tbool HasEnoughPlayers() const { return (IsTeamplay() && m_aTeamSize[TEAM_RED] > 0 && m_aTeamSize[TEAM_BLUE] > 0) || (!IsTeamplay() && m_aTeamSize[TEAM_RED] > 1); }\n\tvoid ResetGame();\n\tvoid SetGameState(EGameState GameState, int Timer=0);\n\tvoid StartMatch();\n\tvoid StartRound();\n\n\t// map\n\tchar m_aMapWish[128];\n\t\n\tvoid CycleMap();\n\n\t// spawn\n\tstruct CSpawnEval\n\t{\n\t\tCSpawnEval()\n\t\t{\n\t\t\tm_Got = false;\n\t\t\tm_FriendlyTeam = -1;\n\t\t\tm_Pos = vec2(100,100);\n\t\t}\n\n\t\tvec2 m_Pos;\n\t\tbool m_Got;\n\t\tint m_FriendlyTeam;\n\t\tfloat m_Score;\n\t};\n\tvec2 m_aaSpawnPoints[3][64];\n\tint m_aNumSpawnPoints[3];\n\t\n\tfloat EvaluateSpawnPos(CSpawnEval *pEval, vec2 Pos) const;\n\tvoid EvaluateSpawnType(CSpawnEval *pEval, int Type) const;\n\n\t// team\n\tint ClampTeam(int Team) const;\n\nprotected:\n\tCGameContext *GameServer() const { return m_pGameServer; }\n\tIServer *Server() const { return m_pServer; }\n\n\t// game\n\tint m_GameStartTick;\n\tint m_MatchCount;\n\tint m_RoundCount;\n\tint m_SuddenDeath;\n\tint m_aTeamscore[NUM_TEAMS];\n\n\tvoid EndMatch() { SetGameState(IGS_END_MATCH, TIMER_END); }\n\tvoid EndRound() { SetGameState(IGS_END_ROUND, TIMER_END); }\n\n\t// info\n\tint m_GameFlags;\n\tconst char *m_pGameType;\n\tstruct CGameInfo\n\t{\n\t\tint m_MatchCurrent;\n\t\tint m_MatchNum;\n\t\tint m_ScoreLimit;\n\t\tint m_TimeLimit;\n\t} m_GameInfo;\n\n\tvoid UpdateGameInfo(int ClientID);\n\npublic:\n\tIGameController(class CGameContext *pGameServer);\n\tvirtual ~IGameController() {};\n\n\t// event\n\t/*\n\t\tFunction: on_CCharacter_death\n\t\t\tCalled when a CCharacter in the world dies.\n\n\t\tArguments:\n\t\t\tvictim - The CCharacter that died.\n\t\t\tkiller - The player that killed it.\n\t\t\tweapon - What weapon that killed it. Can be -1 for undefined\n\t\t\t\tweapon when switching team or player suicides.\n\t*/\n\tvirtual int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon);\n\t/*\n\t\tFunction: on_CCharacter_spawn\n\t\t\tCalled when a CCharacter spawns into the game world.\n\n\t\tArguments:\n\t\t\tchr - The CCharacter that was spawned.\n\t*/\n\tvirtual void OnCharacterSpawn(class CCharacter *pChr);\n\n\t/*\n\t\tFunction: on_entity\n\t\t\tCalled when the map is loaded to process an entity\n\t\t\tin the map.\n\n\t\tArguments:\n\t\t\tindex - Entity index.\n\t\t\tpos - Where the entity is located in the world.\n\n\t\tReturns:\n\t\t\tbool?\n\t*/\n\tvirtual bool OnEntity(int Index, vec2 Pos);\n\n\tvoid OnPlayerConnect(class CPlayer *pPlayer);\n\tvoid OnPlayerDisconnect(class CPlayer *pPlayer);\n\tvoid OnPlayerInfoChange(class CPlayer *pPlayer);\n\tvoid OnPlayerReadyChange(class CPlayer *pPlayer);\n\n\tvoid OnReset();\n\n\t// game\n\tenum\n\t{\n\t\tTIMER_INFINITE = -1,\n\t\tTIMER_END = 10,\n\t};\n\n\tvoid DoPause(int Seconds) { SetGameState(IGS_GAME_PAUSED, Seconds); }\n\tvoid DoWarmup(int Seconds)\n\t{\n\t\tif(m_GameState==IGS_WARMUP_GAME)\n\t\t\tSetGameState(IGS_WARMUP_GAME, 0);\n\t\telse\n\t\t\tSetGameState(IGS_WARMUP_USER, Seconds);\n\t}\n\n\t// general\n\tvirtual void Snap(int SnappingClient);\n\tvirtual void Tick();\n\n\t// info\n\tbool IsFriendlyFire(int ClientID1, int ClientID2) const;\n\tbool IsGamePaused() const { return m_GameState == IGS_GAME_PAUSED || m_GameState == IGS_START_COUNTDOWN; }\n\tbool IsPlayerReadyMode() const;\n\tbool IsTeamChangeAllowed() const;\n\tbool IsTeamplay() const { return m_GameFlags&GAMEFLAG_TEAMS; }\n\t\n\tconst char *GetGameType() const { return m_pGameType; }\n\t\n\t// map\n\tvoid ChangeMap(const char *pToMap);\n\n\t//spawn\n\tbool CanSpawn(int Team, vec2 *pPos) const;\n\tbool GetStartRespawnState() const;\n\n\t// team\n\tbool CanJoinTeam(int Team, int NotThisID) const;\n\tbool CanChangeTeam(CPlayer *pPplayer, int JoinTeam) const;\n\n\tvoid DoTeamChange(class CPlayer *pPlayer, int Team, bool DoChatMsg=true);\n\tvoid ForceTeamBalance() { if(!(m_GameFlags&GAMEFLAG_SURVIVAL)) DoTeamBalance(); }\n\t\n\tint GetRealPlayerNum() const { return m_aTeamSize[TEAM_RED]+m_aTeamSize[TEAM_BLUE]; }\n\tint GetStartTeam();\n};\n\n#endif\n"
  },
  {
    "path": "src/game/server/gamemodes/ctf.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/shared/config.h>\n\n#include <game/mapitems.h>\n\n#include <game/server/entities/character.h>\n#include <game/server/entities/flag.h>\n#include <game/server/gamecontext.h>\n#include <game/server/player.h>\n#include \"ctf.h\"\n\nCGameControllerCTF::CGameControllerCTF(CGameContext *pGameServer)\n: IGameController(pGameServer)\n{\n\t// game\n\tm_apFlags[0] = 0;\n\tm_apFlags[1] = 0;\n\tm_pGameType = \"CTF\";\n\tm_GameFlags = GAMEFLAG_TEAMS|GAMEFLAG_FLAGS;\n}\n\n// balancing\nbool CGameControllerCTF::CanBeMovedOnBalance(int ClientID) const\n{\n\tCCharacter* Character = GameServer()->m_apPlayers[ClientID]->GetCharacter();\n\tif(Character)\n\t{\n\t\tfor(int fi = 0; fi < 2; fi++)\n\t\t{\n\t\t\tCFlag *F = m_apFlags[fi];\n\t\t\tif(F && F->m_pCarryingCharacter == Character)\n\t\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n// event\nint CGameControllerCTF::OnCharacterDeath(CCharacter *pVictim, CPlayer *pKiller, int WeaponID)\n{\n\tIGameController::OnCharacterDeath(pVictim, pKiller, WeaponID);\n\tint HadFlag = 0;\n\n\t// drop flags\n\tfor(int i = 0; i < 2; i++)\n\t{\n\t\tCFlag *F = m_apFlags[i];\n\t\tif(F && pKiller && pKiller->GetCharacter() && F->m_pCarryingCharacter == pKiller->GetCharacter())\n\t\t\tHadFlag |= 2;\n\t\tif(F && F->m_pCarryingCharacter == pVictim)\n\t\t{\n\t\t\tGameServer()->SendGameMsg(GAMEMSG_CTF_DROP, -1);\n\t\t\tF->m_DropTick = Server()->Tick();\n\t\t\tF->m_pCarryingCharacter = 0;\n\t\t\tF->m_Vel = vec2(0,0);\n\n\t\t\tif(pKiller && pKiller->GetTeam() != pVictim->GetPlayer()->GetTeam())\n\t\t\t\tpKiller->m_Score++;\n\n\t\t\tHadFlag |= 1;\n\t\t}\n\t}\n\n\treturn HadFlag;\n}\n\nbool CGameControllerCTF::OnEntity(int Index, vec2 Pos)\n{\n\tif(IGameController::OnEntity(Index, Pos))\n\t\treturn true;\n\n\tint Team = -1;\n\tif(Index == ENTITY_FLAGSTAND_RED) Team = TEAM_RED;\n\tif(Index == ENTITY_FLAGSTAND_BLUE) Team = TEAM_BLUE;\n\tif(Team == -1 || m_apFlags[Team])\n\t\treturn false;\n\n\tCFlag *F = new CFlag(&GameServer()->m_World, Team);\n\tF->m_StandPos = Pos;\n\tF->m_Pos = Pos;\n\tm_apFlags[Team] = F;\n\tGameServer()->m_World.InsertEntity(F);\n\treturn true;\n}\n\n// game\nvoid CGameControllerCTF::DoWincheckMatch()\n{\n\t// check score win condition\n\tif((m_GameInfo.m_ScoreLimit > 0 && (m_aTeamscore[TEAM_RED] >= m_GameInfo.m_ScoreLimit || m_aTeamscore[TEAM_BLUE] >= m_GameInfo.m_ScoreLimit)) ||\n\t\t(m_GameInfo.m_TimeLimit > 0 && (Server()->Tick()-m_GameStartTick) >= m_GameInfo.m_TimeLimit*Server()->TickSpeed()*60))\n\t{\n\t\tif(m_SuddenDeath)\n\t\t{\n\t\t\tif(m_aTeamscore[TEAM_RED]/100 != m_aTeamscore[TEAM_BLUE]/100)\n\t\t\t\tEndMatch();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(m_aTeamscore[TEAM_RED] != m_aTeamscore[TEAM_BLUE])\n\t\t\t\tEndMatch();\n\t\t\telse\n\t\t\t\tm_SuddenDeath = 1;\n\t\t}\n\t}\n}\n\n// general\nvoid CGameControllerCTF::Snap(int SnappingClient)\n{\n\tIGameController::Snap(SnappingClient);\n\n\tCNetObj_GameDataFlag *pGameDataFlag = static_cast<CNetObj_GameDataFlag *>(Server()->SnapNewItem(NETOBJTYPE_GAMEDATAFLAG, 0, sizeof(CNetObj_GameDataFlag)));\n\tif(!pGameDataFlag)\n\t\treturn;\n\n\tpGameDataFlag->m_FlagDropTickRed = 0;\n\tif(m_apFlags[TEAM_RED])\n\t{\n\t\tif(m_apFlags[TEAM_RED]->m_AtStand)\n\t\t\tpGameDataFlag->m_FlagCarrierRed = FLAG_ATSTAND;\n\t\telse if(m_apFlags[TEAM_RED]->m_pCarryingCharacter && m_apFlags[TEAM_RED]->m_pCarryingCharacter->GetPlayer())\n\t\t\tpGameDataFlag->m_FlagCarrierRed = m_apFlags[TEAM_RED]->m_pCarryingCharacter->GetPlayer()->GetCID();\n\t\telse\n\t\t{\n\t\t\tpGameDataFlag->m_FlagCarrierRed = FLAG_TAKEN;\n\t\t\tpGameDataFlag->m_FlagDropTickRed = m_apFlags[TEAM_RED]->m_DropTick;\n\t\t}\n\t}\n\telse\n\t\tpGameDataFlag->m_FlagCarrierRed = FLAG_MISSING;\n\tpGameDataFlag->m_FlagDropTickBlue = 0;\n\tif(m_apFlags[TEAM_BLUE])\n\t{\n\t\tif(m_apFlags[TEAM_BLUE]->m_AtStand)\n\t\t\tpGameDataFlag->m_FlagCarrierBlue = FLAG_ATSTAND;\n\t\telse if(m_apFlags[TEAM_BLUE]->m_pCarryingCharacter && m_apFlags[TEAM_BLUE]->m_pCarryingCharacter->GetPlayer())\n\t\t\tpGameDataFlag->m_FlagCarrierBlue = m_apFlags[TEAM_BLUE]->m_pCarryingCharacter->GetPlayer()->GetCID();\n\t\telse\n\t\t{\n\t\t\tpGameDataFlag->m_FlagCarrierBlue = FLAG_TAKEN;\n\t\t\tpGameDataFlag->m_FlagDropTickBlue = m_apFlags[TEAM_BLUE]->m_DropTick;\n\t\t}\n\t}\n\telse\n\t\tpGameDataFlag->m_FlagCarrierBlue = FLAG_MISSING;\n}\n\nvoid CGameControllerCTF::Tick()\n{\n\tIGameController::Tick();\n\n\tif(GameServer()->m_World.m_ResetRequested || GameServer()->m_World.m_Paused)\n\t\treturn;\n\n\tfor(int fi = 0; fi < 2; fi++)\n\t{\n\t\tCFlag *F = m_apFlags[fi];\n\n\t\tif(!F)\n\t\t\tcontinue;\n\n\t\t// flag hits death-tile or left the game layer, reset it\n\t\tif(GameServer()->Collision()->GetCollisionAt(F->m_Pos.x, F->m_Pos.y)&CCollision::COLFLAG_DEATH || F->GameLayerClipped(F->m_Pos))\n\t\t{\n\t\t\tGameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"game\", \"flag_return\");\n\t\t\tGameServer()->SendGameMsg(GAMEMSG_CTF_RETURN, -1);\n\t\t\tF->Reset();\n\t\t\tcontinue;\n\t\t}\n\n\t\t//\n\t\tif(F->m_pCarryingCharacter)\n\t\t{\n\t\t\t// update flag position\n\t\t\tF->m_Pos = F->m_pCarryingCharacter->m_Pos;\n\n\t\t\tif(m_apFlags[fi^1] && m_apFlags[fi^1]->m_AtStand)\n\t\t\t{\n\t\t\t\tif(distance(F->m_Pos, m_apFlags[fi^1]->m_Pos) < CFlag::ms_PhysSize + CCharacter::ms_PhysSize)\n\t\t\t\t{\n\t\t\t\t\t// CAPTURE! \\o/\n\t\t\t\t\tm_aTeamscore[fi^1] += 100;\n\t\t\t\t\tF->m_pCarryingCharacter->GetPlayer()->m_Score += 5;\n\n\t\t\t\t\tchar aBuf[64];\n\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"flag_capture player='%d:%s'\",\n\t\t\t\t\t\tF->m_pCarryingCharacter->GetPlayer()->GetCID(),\n\t\t\t\t\t\tServer()->ClientName(F->m_pCarryingCharacter->GetPlayer()->GetCID()));\n\t\t\t\t\tGameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"game\", aBuf);\n\n\t\t\t\t\tGameServer()->SendGameMsg(GAMEMSG_CTF_CAPTURE, fi, F->m_pCarryingCharacter->GetPlayer()->GetCID(), Server()->Tick()-F->m_GrabTick, -1);\n\t\t\t\t\tfor(int i = 0; i < 2; i++)\n\t\t\t\t\t\tm_apFlags[i]->Reset();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tCCharacter *apCloseCCharacters[MAX_CLIENTS];\n\t\t\tint Num = GameServer()->m_World.FindEntities(F->m_Pos, CFlag::ms_PhysSize, (CEntity**)apCloseCCharacters, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER);\n\t\t\tfor(int i = 0; i < Num; i++)\n\t\t\t{\n\t\t\t\tif(!apCloseCCharacters[i]->IsAlive() || apCloseCCharacters[i]->GetPlayer()->GetTeam() == TEAM_SPECTATORS || GameServer()->Collision()->IntersectLine(F->m_Pos, apCloseCCharacters[i]->m_Pos, NULL, NULL))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif(apCloseCCharacters[i]->GetPlayer()->GetTeam() == F->m_Team)\n\t\t\t\t{\n\t\t\t\t\t// return the flag\n\t\t\t\t\tif(!F->m_AtStand)\n\t\t\t\t\t{\n\t\t\t\t\t\tCCharacter *pChr = apCloseCCharacters[i];\n\t\t\t\t\t\tpChr->GetPlayer()->m_Score += 1;\n\n\t\t\t\t\t\tchar aBuf[256];\n\t\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"flag_return player='%d:%s'\",\n\t\t\t\t\t\t\tpChr->GetPlayer()->GetCID(),\n\t\t\t\t\t\t\tServer()->ClientName(pChr->GetPlayer()->GetCID()));\n\t\t\t\t\t\tGameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"game\", aBuf);\n\t\t\t\t\t\tGameServer()->SendGameMsg(GAMEMSG_CTF_RETURN, -1);\n\t\t\t\t\t\tF->Reset();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// take the flag\n\t\t\t\t\tif(F->m_AtStand)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_aTeamscore[fi^1]++;\n\t\t\t\t\t\tF->m_GrabTick = Server()->Tick();\n\t\t\t\t\t}\n\n\t\t\t\t\tF->m_AtStand = 0;\n\t\t\t\t\tF->m_pCarryingCharacter = apCloseCCharacters[i];\n\t\t\t\t\tF->m_pCarryingCharacter->GetPlayer()->m_Score += 1;\n\n\t\t\t\t\tchar aBuf[256];\n\t\t\t\t\tstr_format(aBuf, sizeof(aBuf), \"flag_grab player='%d:%s'\",\n\t\t\t\t\t\tF->m_pCarryingCharacter->GetPlayer()->GetCID(),\n\t\t\t\t\t\tServer()->ClientName(F->m_pCarryingCharacter->GetPlayer()->GetCID()));\n\t\t\t\t\tGameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, \"game\", aBuf);\n\t\t\t\t\tGameServer()->SendGameMsg(GAMEMSG_CTF_GRAB, fi, -1);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(!F->m_pCarryingCharacter && !F->m_AtStand)\n\t\t\t{\n\t\t\t\tif(Server()->Tick() > F->m_DropTick + Server()->TickSpeed()*30)\n\t\t\t\t{\n\t\t\t\t\tGameServer()->SendGameMsg(GAMEMSG_CTF_RETURN, -1);\n\t\t\t\t\tF->Reset();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tF->m_Vel.y += GameServer()->m_World.m_Core.m_Tuning.m_Gravity;\n\t\t\t\t\tGameServer()->Collision()->MoveBox(&F->m_Pos, &F->m_Vel, vec2(F->ms_PhysSize, F->ms_PhysSize), 0.5f);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "src/game/server/gamemodes/ctf.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_SERVER_GAMEMODES_CTF_H\n#define GAME_SERVER_GAMEMODES_CTF_H\n#include <game/server/gamecontroller.h>\n#include <game/server/entity.h>\n\nclass CGameControllerCTF : public IGameController\n{\n\t// balancing\n\tvirtual bool CanBeMovedOnBalance(int ClientID) const;\n\n\t// game\n\tclass CFlag *m_apFlags[2];\n\n\tvirtual void DoWincheckMatch();\n\npublic:\n\tCGameControllerCTF(class CGameContext *pGameServer);\n\t\n\t// event\n\tvirtual int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon);\n\tvirtual bool OnEntity(int Index, vec2 Pos);\n\n\t// general\n\tvirtual void Snap(int SnappingClient);\n\tvirtual void Tick();\n};\n\n#endif\n\n"
  },
  {
    "path": "src/game/server/gamemodes/dm.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include \"dm.h\"\n\n\nCGameControllerDM::CGameControllerDM(CGameContext *pGameServer)\n: IGameController(pGameServer)\n{\n\tm_pGameType = \"DM\";\n}\n"
  },
  {
    "path": "src/game/server/gamemodes/dm.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_SERVER_GAMEMODES_DM_H\n#define GAME_SERVER_GAMEMODES_DM_H\n#include <game/server/gamecontroller.h>\n\nclass CGameControllerDM : public IGameController\n{\npublic:\n\tCGameControllerDM(class CGameContext *pGameServer);\n};\n\n#endif\n"
  },
  {
    "path": "src/game/server/gamemodes/lms.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/shared/config.h>\n\n#include <game/server/entities/character.h>\n#include <game/server/gamecontext.h>\n#include <game/server/player.h>\n#include \"lms.h\"\n\nCGameControllerLMS::CGameControllerLMS(CGameContext *pGameServer) : IGameController(pGameServer)\n{\n\tm_pGameType = \"LMS\";\n\tm_GameFlags = GAMEFLAG_SURVIVAL;\n}\n\n// event\nint CGameControllerLMS::OnCharacterDeath(CCharacter *pVictim, CPlayer *pKiller, int Weapon)\n{\n\t// update spectator modes for dead players in survival\n\tif(m_GameFlags&GAMEFLAG_SURVIVAL)\n\t{\n\t\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t\t\tif(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->m_DeadSpecMode)\n\t\t\t\tGameServer()->m_apPlayers[i]->UpdateDeadSpecMode();\n\t}\n\n\treturn 0;\n}\n\n// game\nvoid CGameControllerLMS::DoWincheckRound()\n{\n\t// check for time based win\n\tif(m_GameInfo.m_TimeLimit > 0 && (Server()->Tick()-m_GameStartTick) >= m_GameInfo.m_TimeLimit*Server()->TickSpeed()*60)\n\t{\n\t\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t\t{\n\t\t\tif(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS &&\n\t\t\t\t(!GameServer()->m_apPlayers[i]->m_RespawnDisabled || \n\t\t\t\t(GameServer()->m_apPlayers[i]->GetCharacter() && GameServer()->m_apPlayers[i]->GetCharacter()->IsAlive())))\n\t\t\t\tGameServer()->m_apPlayers[i]->m_Score++;\n\t\t}\n\n\t\tEndRound();\n\t}\n\telse\n\t{\n\t\t// check for survival win\n\t\tCPlayer *pAlivePlayer = 0;\n\t\tint AlivePlayerCount = 0;\n\t\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t\t{\n\t\t\tif(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS &&\n\t\t\t\t(!GameServer()->m_apPlayers[i]->m_RespawnDisabled || \n\t\t\t\t(GameServer()->m_apPlayers[i]->GetCharacter() && GameServer()->m_apPlayers[i]->GetCharacter()->IsAlive())))\n\t\t\t{\n\t\t\t\t++AlivePlayerCount;\n\t\t\t\tpAlivePlayer = GameServer()->m_apPlayers[i];\n\t\t\t}\n\t\t}\n\n\t\tif(AlivePlayerCount == 0)\t\t// no winner\n\t\t\tEndRound();\n\t\telse if(AlivePlayerCount == 1)\t// 1 winner\n\t\t{\n\t\t\tpAlivePlayer->m_Score++;\n\t\t\tEndRound();\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "src/game/server/gamemodes/lms.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_SERVER_GAMEMODES_LMS_H\n#define GAME_SERVER_GAMEMODES_LMS_H\n#include <game/server/gamecontroller.h>\n\nclass CGameControllerLMS : public IGameController\n{\npublic:\n\tCGameControllerLMS(class CGameContext *pGameServer);\n\n\t// event\n\tvirtual int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon);\n\n\t// game\n\tvirtual void DoWincheckRound();\n};\n\n#endif\n"
  },
  {
    "path": "src/game/server/gamemodes/mod.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include \"mod.h\"\n\nCGameControllerMOD::CGameControllerMOD(class CGameContext *pGameServer)\n: IGameController(pGameServer)\n{\n\t// Exchange this to a string that identifies your game mode.\n\t// DM, TDM and CTF are reserved for teeworlds original modes.\n\tm_pGameType = \"MOD\";\n\n\t//m_GameFlags = GAMEFLAG_TEAMS; // GAMEFLAG_TEAMS makes it a two-team gamemode\n}\n\nvoid CGameControllerMOD::Tick()\n{\n\t// this is the main part of the gamemode, this function is run every tick\n\n\tIGameController::Tick();\n}\n"
  },
  {
    "path": "src/game/server/gamemodes/mod.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_SERVER_GAMEMODES_MOD_H\n#define GAME_SERVER_GAMEMODES_MOD_H\n#include <game/server/gamecontroller.h>\n\n// you can subclass GAMECONTROLLER_CTF, GAMECONTROLLER_TDM etc if you want\n// todo a modification with their base as well.\nclass CGameControllerMOD : public IGameController\n{\npublic:\n\tCGameControllerMOD(class CGameContext *pGameServer);\n\tvirtual void Tick();\n\t// add more virtual functions here if you wish\n};\n#endif\n"
  },
  {
    "path": "src/game/server/gamemodes/sur.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/shared/config.h>\n\n#include <game/server/entities/character.h>\n#include <game/server/gamecontext.h>\n#include <game/server/player.h>\n#include \"sur.h\"\n\nCGameControllerSUR::CGameControllerSUR(CGameContext *pGameServer) : IGameController(pGameServer)\n{\n\tm_pGameType = \"SUR\";\n\tm_GameFlags = GAMEFLAG_TEAMS|GAMEFLAG_SURVIVAL;\n}\n\n// game\nvoid CGameControllerSUR::DoWincheckRound()\n{\n\tint Count[2] = {0};\n\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t{\n\t\tif(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS &&\n\t\t\t(!GameServer()->m_apPlayers[i]->m_RespawnDisabled || \n\t\t\t(GameServer()->m_apPlayers[i]->GetCharacter() && GameServer()->m_apPlayers[i]->GetCharacter()->IsAlive())))\n\t\t\t++Count[GameServer()->m_apPlayers[i]->GetTeam()];\n\t}\n\n\tif(Count[TEAM_RED]+Count[TEAM_BLUE] == 0 || (m_GameInfo.m_TimeLimit > 0 && (Server()->Tick()-m_GameStartTick) >= m_GameInfo.m_TimeLimit*Server()->TickSpeed()*60))\n\t{\n\t\t++m_aTeamscore[TEAM_BLUE];\n\t\t++m_aTeamscore[TEAM_RED];\n\t\tEndRound();\n\t}\n\telse if(Count[TEAM_RED] == 0)\n\t{\n\t\t++m_aTeamscore[TEAM_BLUE];\n\t\tEndRound();\n\t}\n\telse if(Count[TEAM_BLUE] == 0)\n\t{\n\t\t++m_aTeamscore[TEAM_RED];\n\t\tEndRound();\n\t}\n}\n"
  },
  {
    "path": "src/game/server/gamemodes/sur.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_SERVER_GAMEMODES_SUR_H\n#define GAME_SERVER_GAMEMODES_SUR_H\n#include <game/server/gamecontroller.h>\n\nclass CGameControllerSUR : public IGameController\n{\npublic:\n\tCGameControllerSUR(class CGameContext *pGameServer);\n\n\t// game\n\tvirtual void DoWincheckRound();\n};\n\n#endif\n"
  },
  {
    "path": "src/game/server/gamemodes/tdm.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <engine/shared/config.h>\n\n#include <game/server/entities/character.h>\n#include <game/server/gamecontext.h>\n#include <game/server/player.h>\n#include \"tdm.h\"\n\nCGameControllerTDM::CGameControllerTDM(class CGameContext *pGameServer) : IGameController(pGameServer)\n{\n\tm_pGameType = \"TDM\";\n\tm_GameFlags = GAMEFLAG_TEAMS;\n}\n\n// event\nint CGameControllerTDM::OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon)\n{\n\tIGameController::OnCharacterDeath(pVictim, pKiller, Weapon);\n\n\n\tif(pKiller && Weapon != WEAPON_GAME)\n\t{\n\t\t// do team scoring\n\t\tif(pKiller == pVictim->GetPlayer() || pKiller->GetTeam() == pVictim->GetPlayer()->GetTeam())\n\t\t\tm_aTeamscore[pKiller->GetTeam()&1]--; // klant arschel\n\t\telse\n\t\t\tm_aTeamscore[pKiller->GetTeam()&1]++; // good shit\n\t}\n\n\tpVictim->GetPlayer()->m_RespawnTick = max(pVictim->GetPlayer()->m_RespawnTick, Server()->Tick()+Server()->TickSpeed()*g_Config.m_SvRespawnDelayTDM);\n\n\treturn 0;\n}\n"
  },
  {
    "path": "src/game/server/gamemodes/tdm.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_SERVER_GAMEMODES_TDM_H\n#define GAME_SERVER_GAMEMODES_TDM_H\n#include <game/server/gamecontroller.h>\n\nclass CGameControllerTDM : public IGameController\n{\npublic:\n\tCGameControllerTDM(class CGameContext *pGameServer);\n\n\t// event\n\tvirtual int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon);\n};\n\n#endif\n"
  },
  {
    "path": "src/game/server/gameworld.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n\n#include \"entities/character.h\"\n#include \"entity.h\"\n#include \"gamecontext.h\"\n#include \"gamecontroller.h\"\n#include \"gameworld.h\"\n\n\n//////////////////////////////////////////////////\n// game world\n//////////////////////////////////////////////////\nCGameWorld::CGameWorld()\n{\n\tm_pGameServer = 0x0;\n\tm_pServer = 0x0;\n\n\tm_Paused = false;\n\tm_ResetRequested = false;\n\tfor(int i = 0; i < NUM_ENTTYPES; i++)\n\t\tm_apFirstEntityTypes[i] = 0;\n}\n\nCGameWorld::~CGameWorld()\n{\n\t// delete all entities\n\tfor(int i = 0; i < NUM_ENTTYPES; i++)\n\t\twhile(m_apFirstEntityTypes[i])\n\t\t\tdelete m_apFirstEntityTypes[i];\n}\n\nvoid CGameWorld::SetGameServer(CGameContext *pGameServer)\n{\n\tm_pGameServer = pGameServer;\n\tm_pServer = m_pGameServer->Server();\n}\n\nCEntity *CGameWorld::FindFirst(int Type)\n{\n\treturn Type < 0 || Type >= NUM_ENTTYPES ? 0 : m_apFirstEntityTypes[Type];\n}\n\nint CGameWorld::FindEntities(vec2 Pos, float Radius, CEntity **ppEnts, int Max, int Type)\n{\n\tif(Type < 0 || Type >= NUM_ENTTYPES)\n\t\treturn 0;\n\n\tint Num = 0;\n\tfor(CEntity *pEnt = m_apFirstEntityTypes[Type];\tpEnt; pEnt = pEnt->m_pNextTypeEntity)\n\t{\n\t\tif(distance(pEnt->m_Pos, Pos) < Radius+pEnt->m_ProximityRadius)\n\t\t{\n\t\t\tif(ppEnts)\n\t\t\t\tppEnts[Num] = pEnt;\n\t\t\tNum++;\n\t\t\tif(Num == Max)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn Num;\n}\n\nvoid CGameWorld::InsertEntity(CEntity *pEnt)\n{\n#ifdef CONF_DEBUG\n\tfor(CEntity *pCur = m_apFirstEntityTypes[pEnt->m_ObjType]; pCur; pCur = pCur->m_pNextTypeEntity)\n\t\tdbg_assert(pCur != pEnt, \"err\");\n#endif\n\n\t// insert it\n\tif(m_apFirstEntityTypes[pEnt->m_ObjType])\n\t\tm_apFirstEntityTypes[pEnt->m_ObjType]->m_pPrevTypeEntity = pEnt;\n\tpEnt->m_pNextTypeEntity = m_apFirstEntityTypes[pEnt->m_ObjType];\n\tpEnt->m_pPrevTypeEntity = 0x0;\n\tm_apFirstEntityTypes[pEnt->m_ObjType] = pEnt;\n}\n\nvoid CGameWorld::DestroyEntity(CEntity *pEnt)\n{\n\tpEnt->m_MarkedForDestroy = true;\n}\n\nvoid CGameWorld::RemoveEntity(CEntity *pEnt)\n{\n\t// not in the list\n\tif(!pEnt->m_pNextTypeEntity && !pEnt->m_pPrevTypeEntity && m_apFirstEntityTypes[pEnt->m_ObjType] != pEnt)\n\t\treturn;\n\n\t// remove\n\tif(pEnt->m_pPrevTypeEntity)\n\t\tpEnt->m_pPrevTypeEntity->m_pNextTypeEntity = pEnt->m_pNextTypeEntity;\n\telse\n\t\tm_apFirstEntityTypes[pEnt->m_ObjType] = pEnt->m_pNextTypeEntity;\n\tif(pEnt->m_pNextTypeEntity)\n\t\tpEnt->m_pNextTypeEntity->m_pPrevTypeEntity = pEnt->m_pPrevTypeEntity;\n\n\t// keep list traversing valid\n\tif(m_pNextTraverseEntity == pEnt)\n\t\tm_pNextTraverseEntity = pEnt->m_pNextTypeEntity;\n\n\tpEnt->m_pNextTypeEntity = 0;\n\tpEnt->m_pPrevTypeEntity = 0;\n}\n\n//\nvoid CGameWorld::Snap(int SnappingClient)\n{\n\tfor(int i = 0; i < NUM_ENTTYPES; i++)\n\t\tfor(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; )\n\t\t{\n\t\t\tm_pNextTraverseEntity = pEnt->m_pNextTypeEntity;\n\t\t\tpEnt->Snap(SnappingClient);\n\t\t\tpEnt = m_pNextTraverseEntity;\n\t\t}\n}\n\nvoid CGameWorld::PostSnap()\n{\n\tfor(int i = 0; i < NUM_ENTTYPES; i++)\n\t\tfor(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; )\n\t\t{\n\t\t\tm_pNextTraverseEntity = pEnt->m_pNextTypeEntity;\n\t\t\tpEnt->PostSnap();\n\t\t\tpEnt = m_pNextTraverseEntity;\n\t\t}\n}\n\nvoid CGameWorld::Reset()\n{\n\t// reset all entities\n\tfor(int i = 0; i < NUM_ENTTYPES; i++)\n\t\tfor(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; )\n\t\t{\n\t\t\tm_pNextTraverseEntity = pEnt->m_pNextTypeEntity;\n\t\t\tpEnt->Reset();\n\t\t\tpEnt = m_pNextTraverseEntity;\n\t\t}\n\tRemoveEntities();\n\n\tGameServer()->m_pController->OnReset();\n\tRemoveEntities();\n\n\tm_ResetRequested = false;\n}\n\nvoid CGameWorld::RemoveEntities()\n{\n\t// destroy objects marked for destruction\n\tfor(int i = 0; i < NUM_ENTTYPES; i++)\n\t\tfor(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; )\n\t\t{\n\t\t\tm_pNextTraverseEntity = pEnt->m_pNextTypeEntity;\n\t\t\tif(pEnt->m_MarkedForDestroy)\n\t\t\t{\n\t\t\t\tRemoveEntity(pEnt);\n\t\t\t\tpEnt->Destroy();\n\t\t\t}\n\t\t\tpEnt = m_pNextTraverseEntity;\n\t\t}\n}\n\nvoid CGameWorld::Tick()\n{\n\tif(m_ResetRequested)\n\t\tReset();\n\n\tif(!m_Paused)\n\t{\n\t\t// update all objects\n\t\tfor(int i = 0; i < NUM_ENTTYPES; i++)\n\t\t\tfor(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; )\n\t\t\t{\n\t\t\t\tm_pNextTraverseEntity = pEnt->m_pNextTypeEntity;\n\t\t\t\tpEnt->Tick();\n\t\t\t\tpEnt = m_pNextTraverseEntity;\n\t\t\t}\n\n\t\tfor(int i = 0; i < NUM_ENTTYPES; i++)\n\t\t\tfor(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; )\n\t\t\t{\n\t\t\t\tm_pNextTraverseEntity = pEnt->m_pNextTypeEntity;\n\t\t\t\tpEnt->TickDefered();\n\t\t\t\tpEnt = m_pNextTraverseEntity;\n\t\t\t}\n\t}\n\telse if(GameServer()->m_pController->IsGamePaused())\n\t{\n\t\t// update all objects\n\t\tfor(int i = 0; i < NUM_ENTTYPES; i++)\n\t\t\tfor(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; )\n\t\t\t{\n\t\t\t\tm_pNextTraverseEntity = pEnt->m_pNextTypeEntity;\n\t\t\t\tpEnt->TickPaused();\n\t\t\t\tpEnt = m_pNextTraverseEntity;\n\t\t\t}\n\t}\n\n\tRemoveEntities();\n}\n\n\n// TODO: should be more general\nCCharacter *CGameWorld::IntersectCharacter(vec2 Pos0, vec2 Pos1, float Radius, vec2& NewPos, CEntity *pNotThis)\n{\n\t// Find other players\n\tfloat ClosestLen = distance(Pos0, Pos1) * 100.0f;\n\tCCharacter *pClosest = 0;\n\n\tCCharacter *p = (CCharacter *)FindFirst(ENTTYPE_CHARACTER);\n\tfor(; p; p = (CCharacter *)p->TypeNext())\n \t{\n\t\tif(p == pNotThis)\n\t\t\tcontinue;\n\n\t\tvec2 IntersectPos = closest_point_on_line(Pos0, Pos1, p->m_Pos);\n\t\tfloat Len = distance(p->m_Pos, IntersectPos);\n\t\tif(Len < p->m_ProximityRadius+Radius)\n\t\t{\n\t\t\tLen = distance(Pos0, IntersectPos);\n\t\t\tif(Len < ClosestLen)\n\t\t\t{\n\t\t\t\tNewPos = IntersectPos;\n\t\t\t\tClosestLen = Len;\n\t\t\t\tpClosest = p;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn pClosest;\n}\n\n\nCCharacter *CGameWorld::ClosestCharacter(vec2 Pos, float Radius, CEntity *pNotThis)\n{\n\t// Find other players\n\tfloat ClosestRange = Radius*2;\n\tCCharacter *pClosest = 0;\n\n\tCCharacter *p = (CCharacter *)GameServer()->m_World.FindFirst(ENTTYPE_CHARACTER);\n\tfor(; p; p = (CCharacter *)p->TypeNext())\n \t{\n\t\tif(p == pNotThis)\n\t\t\tcontinue;\n\n\t\tfloat Len = distance(Pos, p->m_Pos);\n\t\tif(Len < p->m_ProximityRadius+Radius)\n\t\t{\n\t\t\tif(Len < ClosestRange)\n\t\t\t{\n\t\t\t\tClosestRange = Len;\n\t\t\t\tpClosest = p;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn pClosest;\n}\n"
  },
  {
    "path": "src/game/server/gameworld.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_SERVER_GAMEWORLD_H\n#define GAME_SERVER_GAMEWORLD_H\n\n#include <game/gamecore.h>\n\nclass CEntity;\nclass CCharacter;\n\n/*\n\tClass: Game World\n\t\tTracks all entities in the game. Propagates tick and\n\t\tsnap calls to all entities.\n*/\nclass CGameWorld\n{\npublic:\n\tenum\n\t{\n\t\tENTTYPE_PROJECTILE = 0,\n\t\tENTTYPE_LASER,\n\t\tENTTYPE_PICKUP,\n\t\tENTTYPE_FLAG,\n\t\tENTTYPE_CHARACTER,\n\t\tNUM_ENTTYPES\n\t};\n\nprivate:\n\tvoid Reset();\n\tvoid RemoveEntities();\n\n\tCEntity *m_pNextTraverseEntity;\n\tCEntity *m_apFirstEntityTypes[NUM_ENTTYPES];\n\n\tclass CGameContext *m_pGameServer;\n\tclass IServer *m_pServer;\n\npublic:\n\tclass CGameContext *GameServer() { return m_pGameServer; }\n\tclass IServer *Server() { return m_pServer; }\n\n\tbool m_ResetRequested;\n\tbool m_Paused;\n\tCWorldCore m_Core;\n\n\tCGameWorld();\n\t~CGameWorld();\n\n\tvoid SetGameServer(CGameContext *pGameServer);\n\n\tCEntity *FindFirst(int Type);\n\n\t/*\n\t\tFunction: find_entities\n\t\t\tFinds entities close to a position and returns them in a list.\n\n\t\tArguments:\n\t\t\tpos - Position.\n\t\t\tradius - How close the entities have to be.\n\t\t\tents - Pointer to a list that should be filled with the pointers\n\t\t\t\tto the entities.\n\t\t\tmax - Number of entities that fits into the ents array.\n\t\t\ttype - Type of the entities to find.\n\n\t\tReturns:\n\t\t\tNumber of entities found and added to the ents array.\n\t*/\n\tint FindEntities(vec2 Pos, float Radius, CEntity **ppEnts, int Max, int Type);\n\n\t/*\n\t\tFunction: interserct_CCharacter\n\t\t\tFinds the closest CCharacter that intersects the line.\n\n\t\tArguments:\n\t\t\tpos0 - Start position\n\t\t\tpos2 - End position\n\t\t\tradius - How for from the line the CCharacter is allowed to be.\n\t\t\tnew_pos - Intersection position\n\t\t\tnotthis - Entity to ignore intersecting with\n\n\t\tReturns:\n\t\t\tReturns a pointer to the closest hit or NULL of there is no intersection.\n\t*/\n\tclass CCharacter *IntersectCharacter(vec2 Pos0, vec2 Pos1, float Radius, vec2 &NewPos, class CEntity *pNotThis = 0);\n\n\t/*\n\t\tFunction: closest_CCharacter\n\t\t\tFinds the closest CCharacter to a specific point.\n\n\t\tArguments:\n\t\t\tpos - The center position.\n\t\t\tradius - How far off the CCharacter is allowed to be\n\t\t\tnotthis - Entity to ignore\n\n\t\tReturns:\n\t\t\tReturns a pointer to the closest CCharacter or NULL if no CCharacter is close enough.\n\t*/\n\tclass CCharacter *ClosestCharacter(vec2 Pos, float Radius, CEntity *ppNotThis);\n\n\t/*\n\t\tFunction: insert_entity\n\t\t\tAdds an entity to the world.\n\n\t\tArguments:\n\t\t\tentity - Entity to add\n\t*/\n\tvoid InsertEntity(CEntity *pEntity);\n\n\t/*\n\t\tFunction: remove_entity\n\t\t\tRemoves an entity from the world.\n\n\t\tArguments:\n\t\t\tentity - Entity to remove\n\t*/\n\tvoid RemoveEntity(CEntity *pEntity);\n\n\t/*\n\t\tFunction: destroy_entity\n\t\t\tDestroys an entity in the world.\n\n\t\tArguments:\n\t\t\tentity - Entity to destroy\n\t*/\n\tvoid DestroyEntity(CEntity *pEntity);\n\n\t/*\n\t\tFunction: snap\n\t\t\tCalls snap on all the entities in the world to create\n\t\t\tthe snapshot.\n\n\t\tArguments:\n\t\t\tsnapping_client - ID of the client which snapshot\n\t\t\tis being created.\n\t*/\n\tvoid Snap(int SnappingClient);\n\t\n\tvoid PostSnap();\n\n\t/*\n\t\tFunction: tick\n\t\t\tCalls tick on all the entities in the world to progress\n\t\t\tthe world to the next tick.\n\n\t*/\n\tvoid Tick();\n};\n\n#endif\n"
  },
  {
    "path": "src/game/server/player.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n\n#include \"entities/character.h\"\n#include \"gamecontext.h\"\n#include \"gamecontroller.h\"\n#include \"player.h\"\n\n\nMACRO_ALLOC_POOL_ID_IMPL(CPlayer, MAX_CLIENTS)\n\nIServer *CPlayer::Server() const { return m_pGameServer->Server(); }\n\nCPlayer::CPlayer(CGameContext *pGameServer, int ClientID, bool Dummy)\n{\n\tm_pGameServer = pGameServer;\n\tm_RespawnTick = Server()->Tick();\n\tm_DieTick = Server()->Tick();\n\tm_ScoreStartTick = Server()->Tick();\n\tm_pCharacter = 0;\n\tm_ClientID = ClientID;\n\tm_Team = GameServer()->m_pController->GetStartTeam();\n\tm_SpectatorID = SPEC_FREEVIEW;\n\tm_LastActionTick = Server()->Tick();\n\tm_TeamChangeTick = Server()->Tick();\n\tm_InactivityTickCounter = 0;\n\tm_Dummy = Dummy;\n\tm_IsReadyToPlay = !GameServer()->m_pController->IsPlayerReadyMode();\n\tm_RespawnDisabled = GameServer()->m_pController->GetStartRespawnState();\n\tm_DeadSpecMode = false;\n\tm_Spawning = 0;\n}\n\nCPlayer::~CPlayer()\n{\n\tdelete m_pCharacter;\n\tm_pCharacter = 0;\n}\n\nvoid CPlayer::Tick()\n{\n\tif(!IsDummy() && !Server()->ClientIngame(m_ClientID))\n\t\treturn;\n\n\tServer()->SetClientScore(m_ClientID, m_Score);\n\n\t// do latency stuff\n\t{\n\t\tIServer::CClientInfo Info;\n\t\tif(Server()->GetClientInfo(m_ClientID, &Info))\n\t\t{\n\t\t\tm_Latency.m_Accum += Info.m_Latency;\n\t\t\tm_Latency.m_AccumMax = max(m_Latency.m_AccumMax, Info.m_Latency);\n\t\t\tm_Latency.m_AccumMin = min(m_Latency.m_AccumMin, Info.m_Latency);\n\t\t}\n\t\t// each second\n\t\tif(Server()->Tick()%Server()->TickSpeed() == 0)\n\t\t{\n\t\t\tm_Latency.m_Avg = m_Latency.m_Accum/Server()->TickSpeed();\n\t\t\tm_Latency.m_Max = m_Latency.m_AccumMax;\n\t\t\tm_Latency.m_Min = m_Latency.m_AccumMin;\n\t\t\tm_Latency.m_Accum = 0;\n\t\t\tm_Latency.m_AccumMin = 1000;\n\t\t\tm_Latency.m_AccumMax = 0;\n\t\t}\n\t}\n\n\tif(m_pCharacter && !m_pCharacter->IsAlive())\n\t{\n\t\tdelete m_pCharacter;\n\t\tm_pCharacter = 0;\n\t}\n\n\tif(!GameServer()->m_pController->IsGamePaused())\n\t{\n\t\tif(!m_pCharacter && m_Team == TEAM_SPECTATORS && m_SpectatorID == SPEC_FREEVIEW)\n\t\t\tm_ViewPos -= vec2(clamp(m_ViewPos.x-m_LatestActivity.m_TargetX, -500.0f, 500.0f), clamp(m_ViewPos.y-m_LatestActivity.m_TargetY, -400.0f, 400.0f));\n\n\t\tif(!m_pCharacter && m_DieTick+Server()->TickSpeed()*3 <= Server()->Tick() && !m_DeadSpecMode)\n\t\t\tRespawn();\n\n\t\tif(m_pCharacter)\n\t\t{\n\t\t\tif(m_pCharacter->IsAlive())\n\t\t\t\tm_ViewPos = m_pCharacter->m_Pos;\n\t\t}\n\t\telse if(m_Spawning && m_RespawnTick <= Server()->Tick())\n\t\t\tTryRespawn();\n\n\t\tif(!m_DeadSpecMode && m_LastActionTick != Server()->Tick())\n\t\t\t++m_InactivityTickCounter;\n\t}\n\telse\n\t{\n\t\t++m_RespawnTick;\n\t\t++m_DieTick;\n\t\t++m_ScoreStartTick;\n\t\t++m_LastActionTick;\n\t\t++m_TeamChangeTick;\n \t}\n}\n\nvoid CPlayer::PostTick()\n{\n\t// update latency value\n\tif(m_PlayerFlags&PLAYERFLAG_SCOREBOARD)\n\t{\n\t\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t\t{\n\t\t\tif(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS)\n\t\t\t\tm_aActLatency[i] = GameServer()->m_apPlayers[i]->m_Latency.m_Min;\n\t\t}\n\t}\n\n\t// update view pos for spectators and dead players\n\tif((m_Team == TEAM_SPECTATORS || m_DeadSpecMode) && m_SpectatorID != SPEC_FREEVIEW && GameServer()->m_apPlayers[m_SpectatorID])\n\t\tm_ViewPos = GameServer()->m_apPlayers[m_SpectatorID]->m_ViewPos;\n}\n\nvoid CPlayer::Snap(int SnappingClient)\n{\n\tif(!IsDummy() && !Server()->ClientIngame(m_ClientID))\n\t\treturn;\n\n\tCNetObj_PlayerInfo *pPlayerInfo = static_cast<CNetObj_PlayerInfo *>(Server()->SnapNewItem(NETOBJTYPE_PLAYERINFO, m_ClientID, sizeof(CNetObj_PlayerInfo)));\n\tif(!pPlayerInfo)\n\t\treturn;\n\n\tpPlayerInfo->m_PlayerFlags = m_PlayerFlags&PLAYERFLAG_CHATTING;\n\tif(Server()->IsAuthed(m_ClientID))\n\t\tpPlayerInfo->m_PlayerFlags |= PLAYERFLAG_ADMIN;\n\tif(!GameServer()->m_pController->IsPlayerReadyMode() || m_IsReadyToPlay)\n\t\tpPlayerInfo->m_PlayerFlags |= PLAYERFLAG_READY;\n\tif(m_RespawnDisabled && (!GetCharacter() || !GetCharacter()->IsAlive()))\n\t\tpPlayerInfo->m_PlayerFlags |= PLAYERFLAG_DEAD;\n\tif(SnappingClient != -1 && (m_Team == TEAM_SPECTATORS || m_DeadSpecMode) && SnappingClient == m_SpectatorID)\n\t\tpPlayerInfo->m_PlayerFlags |= PLAYERFLAG_WATCHING;\n\tpPlayerInfo->m_Latency = SnappingClient == -1 ? m_Latency.m_Min : GameServer()->m_apPlayers[SnappingClient]->m_aActLatency[m_ClientID];\n\tpPlayerInfo->m_Score = m_Score;\n\n\tif(m_ClientID == SnappingClient && (m_Team == TEAM_SPECTATORS || m_DeadSpecMode))\n\t{\n\t\tCNetObj_SpectatorInfo *pSpectatorInfo = static_cast<CNetObj_SpectatorInfo *>(Server()->SnapNewItem(NETOBJTYPE_SPECTATORINFO, m_ClientID, sizeof(CNetObj_SpectatorInfo)));\n\t\tif(!pSpectatorInfo)\n\t\t\treturn;\n\n\t\tpSpectatorInfo->m_SpectatorID = m_SpectatorID;\n\t\tpSpectatorInfo->m_X = m_ViewPos.x;\n\t\tpSpectatorInfo->m_Y = m_ViewPos.y;\n\t}\n\n\t// demo recording\n\tif(SnappingClient == -1)\n\t{\n\t\tCNetObj_De_ClientInfo *pClientInfo = static_cast<CNetObj_De_ClientInfo *>(Server()->SnapNewItem(NETOBJTYPE_DE_CLIENTINFO, m_ClientID, sizeof(CNetObj_De_ClientInfo)));\n\t\tif(!pClientInfo)\n\t\t\treturn;\n\n\t\tpClientInfo->m_Local = 0;\n\t\tpClientInfo->m_Team = m_Team;\n\t\tStrToInts(pClientInfo->m_aName, 4, Server()->ClientName(m_ClientID));\n\t\tStrToInts(pClientInfo->m_aClan, 3, Server()->ClientClan(m_ClientID));\n\t\tpClientInfo->m_Country = Server()->ClientCountry(m_ClientID);\n\n\t\tfor(int p = 0; p < 6; p++)\n\t\t{\n\t\t\tStrToInts(pClientInfo->m_aaSkinPartNames[p], 6, m_TeeInfos.m_aaSkinPartNames[p]);\n\t\t\tpClientInfo->m_aUseCustomColors[p] = m_TeeInfos.m_aUseCustomColors[p];\n\t\t\tpClientInfo->m_aSkinPartColors[p] = m_TeeInfos.m_aSkinPartColors[p];\n\t\t}\n\t}\n}\n\nvoid CPlayer::OnDisconnect()\n{\n\tKillCharacter();\n\n\tif(m_Team != TEAM_SPECTATORS)\n\t{\n\t\t// update spectator modes\n\t\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t\t{\n\t\t\tif(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->m_SpectatorID == m_ClientID)\n\t\t\t{\n\t\t\t\tif(GameServer()->m_apPlayers[i]->m_DeadSpecMode)\n\t\t\t\t\tGameServer()->m_apPlayers[i]->UpdateDeadSpecMode();\n\t\t\t\telse\n\t\t\t\t\tGameServer()->m_apPlayers[i]->m_SpectatorID = SPEC_FREEVIEW;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid CPlayer::OnPredictedInput(CNetObj_PlayerInput *NewInput)\n{\n\t// skip the input if chat is active\n\tif((m_PlayerFlags&PLAYERFLAG_CHATTING) && (NewInput->m_PlayerFlags&PLAYERFLAG_CHATTING))\n\t\treturn;\n\n\tif(m_pCharacter)\n\t\tm_pCharacter->OnPredictedInput(NewInput);\n}\n\nvoid CPlayer::OnDirectInput(CNetObj_PlayerInput *NewInput)\n{\n\tif(GameServer()->m_World.m_Paused)\n\t{\n\t\tm_PlayerFlags = NewInput->m_PlayerFlags;\n\t\treturn;\n\t}\n\n\tif(NewInput->m_PlayerFlags&PLAYERFLAG_CHATTING)\n\t{\n\t\t// skip the input if chat is active\n\t\tif(m_PlayerFlags&PLAYERFLAG_CHATTING)\n\t\t\treturn;\n\n\t\t// reset input\n\t\tif(m_pCharacter)\n\t\t\tm_pCharacter->ResetInput();\n\n\t\tm_PlayerFlags = NewInput->m_PlayerFlags;\n \t\treturn;\n\t}\n\n\tm_PlayerFlags = NewInput->m_PlayerFlags;\n\n\tif(m_pCharacter)\n\t\tm_pCharacter->OnDirectInput(NewInput);\n\n\tif(!m_pCharacter && m_Team != TEAM_SPECTATORS && (NewInput->m_Fire&1))\n\t\tRespawn();\n\n\t// check for activity\n\tif(NewInput->m_Direction || m_LatestActivity.m_TargetX != NewInput->m_TargetX ||\n\t\tm_LatestActivity.m_TargetY != NewInput->m_TargetY || NewInput->m_Jump ||\n\t\tNewInput->m_Fire&1 || NewInput->m_Hook)\n\t{\n\t\tm_LatestActivity.m_TargetX = NewInput->m_TargetX;\n\t\tm_LatestActivity.m_TargetY = NewInput->m_TargetY;\n\t\tm_LastActionTick = Server()->Tick();\n\t\tm_InactivityTickCounter = 0;\n\t}\n}\n\nCCharacter *CPlayer::GetCharacter()\n{\n\tif(m_pCharacter && m_pCharacter->IsAlive())\n\t\treturn m_pCharacter;\n\treturn 0;\n}\n\nvoid CPlayer::KillCharacter(int Weapon)\n{\n\tif(m_pCharacter)\n\t{\n\t\tm_pCharacter->Die(m_ClientID, Weapon);\n\t\tdelete m_pCharacter;\n\t\tm_pCharacter = 0;\n\t}\n}\n\nvoid CPlayer::Respawn()\n{\n\tif(m_RespawnDisabled)\n\t{\n\t\t// enable spectate mode for dead players\n\t\tm_DeadSpecMode = true;\n\t\tm_IsReadyToPlay = true;\n\t\tUpdateDeadSpecMode();\n\t\treturn;\n\t}\n\n\tm_DeadSpecMode = false;\n\n\tif(m_Team != TEAM_SPECTATORS)\n\t\tm_Spawning = true;\n}\n\nbool CPlayer::SetSpectatorID(int SpectatorID)\n{\n\tif(m_SpectatorID == SpectatorID || m_ClientID == SpectatorID)\n\t\treturn false;\n\n\tif(m_Team == TEAM_SPECTATORS)\n\t{\n\t\t// check for freeview or if wanted player is playing\n\t\tif(SpectatorID == SPEC_FREEVIEW || (GameServer()->m_apPlayers[SpectatorID] && GameServer()->m_apPlayers[SpectatorID]->GetTeam() != TEAM_SPECTATORS))\n\t\t{\n\t\t\tm_SpectatorID = SpectatorID;\n\t\t\treturn true;\n\t\t}\n\t}\n\telse if(m_DeadSpecMode)\n\t{\n\t\t// check if wanted player can be followed\n\t\tif(GameServer()->m_apPlayers[SpectatorID] && DeadCanFollow(GameServer()->m_apPlayers[SpectatorID]))\n\t\t{\n\t\t\tm_SpectatorID = SpectatorID;\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nbool CPlayer::DeadCanFollow(CPlayer *pPlayer) const\n{\n\t// check if wanted player is in the same team and alive\n\treturn (!pPlayer->m_RespawnDisabled || (pPlayer->GetCharacter() && pPlayer->GetCharacter()->IsAlive())) && pPlayer->GetTeam() == m_Team;\n}\n\nvoid CPlayer::UpdateDeadSpecMode()\n{\n\t// check if actual spectator id is valid\n\tif(m_SpectatorID != SPEC_FREEVIEW && GameServer()->m_apPlayers[m_SpectatorID] && DeadCanFollow(GameServer()->m_apPlayers[m_SpectatorID]))\n\t\treturn;\n\n\t// find player to follow\n\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t{\n\t\tif(GameServer()->m_apPlayers[i] && DeadCanFollow(GameServer()->m_apPlayers[i]))\n\t\t{\n\t\t\tm_SpectatorID = i;\n\t\t\treturn;\n\t\t}\n\t}\n\n\t// no one available to follow -> turn spectator mode off\n\tm_DeadSpecMode = false;\n}\n\nvoid CPlayer::SetTeam(int Team, bool DoChatMsg)\n{\n\tKillCharacter();\n\n\tm_Team = Team;\n\tm_LastActionTick = Server()->Tick();\n\tm_SpectatorID = SPEC_FREEVIEW;\n\tm_DeadSpecMode = false;\n\t\n\t// we got to wait 0.5 secs before respawning\n\tm_RespawnTick = Server()->Tick()+Server()->TickSpeed()/2;\n\t\n\tif(Team == TEAM_SPECTATORS)\n\t{\n\t\t// update spectator modes\n\t\tfor(int i = 0; i < MAX_CLIENTS; ++i)\n\t\t{\n\t\t\tif(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->m_SpectatorID == m_ClientID)\n\t\t\t{\n\t\t\t\tif(GameServer()->m_apPlayers[i]->m_DeadSpecMode)\n\t\t\t\t\tGameServer()->m_apPlayers[i]->UpdateDeadSpecMode();\n\t\t\t\telse\n\t\t\t\t\tGameServer()->m_apPlayers[i]->m_SpectatorID = SPEC_FREEVIEW;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid CPlayer::TryRespawn()\n{\n\tvec2 SpawnPos;\n\n\tif(!GameServer()->m_pController->CanSpawn(m_Team, &SpawnPos))\n\t\treturn;\n\n\tm_Spawning = false;\n\tm_pCharacter = new(m_ClientID) CCharacter(&GameServer()->m_World);\n\tm_pCharacter->Spawn(this, SpawnPos);\n\tGameServer()->CreatePlayerSpawn(SpawnPos);\n}\n"
  },
  {
    "path": "src/game/server/player.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_SERVER_PLAYER_H\n#define GAME_SERVER_PLAYER_H\n\n#include \"alloc.h\"\n\n\nenum\n{\n\tWEAPON_GAME = -3, // team switching etc\n\tWEAPON_SELF = -2, // console kill command\n\tWEAPON_WORLD = -1, // death tiles etc\n};\n\n// player object\nclass CPlayer\n{\n\tMACRO_ALLOC_POOL_ID()\n\npublic:\n\tCPlayer(CGameContext *pGameServer, int ClientID, bool Dummy);\n\t~CPlayer();\n\n\tvoid Init(int CID);\n\n\tvoid TryRespawn();\n\tvoid Respawn();\n\tvoid SetTeam(int Team, bool DoChatMsg=true);\n\tint GetTeam() const { return m_Team; };\n\tint GetCID() const { return m_ClientID; };\n\tbool IsDummy() const { return m_Dummy; }\n\n\tvoid Tick();\n\tvoid PostTick();\n\tvoid Snap(int SnappingClient);\n\n\tvoid OnDirectInput(CNetObj_PlayerInput *NewInput);\n\tvoid OnPredictedInput(CNetObj_PlayerInput *NewInput);\n\tvoid OnDisconnect();\n\n\tvoid KillCharacter(int Weapon = WEAPON_GAME);\n\tCCharacter *GetCharacter();\n\n\t//---------------------------------------------------------\n\t// this is used for snapping so we know how we can clip the view for the player\n\tvec2 m_ViewPos;\n\n\t// states if the client is chatting, accessing a menu etc.\n\tint m_PlayerFlags;\n\n\t// used for snapping to just update latency if the scoreboard is active\n\tint m_aActLatency[MAX_CLIENTS];\n\n\t// used for spectator mode\n\tint GetSpectatorID() const { return m_SpectatorID; }\n\tbool SetSpectatorID(int SpectatorID);\n\tbool m_DeadSpecMode;\n\tbool DeadCanFollow(CPlayer *pPlayer) const;\n\tvoid UpdateDeadSpecMode();\n\n\tbool m_IsReadyToEnter;\n\tbool m_IsReadyToPlay;\n\n\tbool m_RespawnDisabled;\n\n\t//\n\tint m_Vote;\n\tint m_VotePos;\n\t//\n\tint m_LastVoteCall;\n\tint m_LastVoteTry;\n\tint m_LastChat;\n\tint m_LastSetTeam;\n\tint m_LastSetSpectatorMode;\n\tint m_LastChangeInfo;\n\tint m_LastEmote;\n\tint m_LastKill;\n\tint m_LastReadyChange;\n\n\t// TODO: clean this up\n\tstruct\n\t{\n\t\tchar m_aaSkinPartNames[6][24];\n\t\tint m_aUseCustomColors[6];\n\t\tint m_aSkinPartColors[6];\n\t} m_TeeInfos;\n\n\tint m_RespawnTick;\n\tint m_DieTick;\n\tint m_Score;\n\tint m_ScoreStartTick;\n\tint m_LastActionTick;\n\tint m_TeamChangeTick;\n\n\tint m_InactivityTickCounter;\n\n\tstruct\n\t{\n\t\tint m_TargetX;\n\t\tint m_TargetY;\n\t} m_LatestActivity;\n\n\t// network latency calculations\n\tstruct\n\t{\n\t\tint m_Accum;\n\t\tint m_AccumMin;\n\t\tint m_AccumMax;\n\t\tint m_Avg;\n\t\tint m_Min;\n\t\tint m_Max;\n\t} m_Latency;\n\nprivate:\n\tCCharacter *m_pCharacter;\n\tCGameContext *m_pGameServer;\n\n\tCGameContext *GameServer() const { return m_pGameServer; }\n\tIServer *Server() const;\n\n\t//\n\tbool m_Spawning;\n\tint m_ClientID;\n\tint m_Team;\n\tbool m_Dummy;\n\n\t// used for spectator mode\n\tint m_SpectatorID;\n};\n\n#endif\n"
  },
  {
    "path": "src/game/tuning.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_TUNING_H\n#define GAME_TUNING_H\n#undef GAME_TUNING_H // this file will be included several times\n\n// physics tuning\nMACRO_TUNING_PARAM(GroundControlSpeed, ground_control_speed, 10.0f)\nMACRO_TUNING_PARAM(GroundControlAccel, ground_control_accel, 100.0f / TicksPerSecond)\nMACRO_TUNING_PARAM(GroundFriction, ground_friction, 0.5f)\nMACRO_TUNING_PARAM(GroundJumpImpulse, ground_jump_impulse, 13.2f)\nMACRO_TUNING_PARAM(AirJumpImpulse, air_jump_impulse, 12.0f)\nMACRO_TUNING_PARAM(AirControlSpeed, air_control_speed, 250.0f / TicksPerSecond)\nMACRO_TUNING_PARAM(AirControlAccel, air_control_accel, 1.5f)\nMACRO_TUNING_PARAM(AirFriction, air_friction, 0.95f)\nMACRO_TUNING_PARAM(HookLength, hook_length, 380.0f)\nMACRO_TUNING_PARAM(HookFireSpeed, hook_fire_speed, 80.0f)\nMACRO_TUNING_PARAM(HookDragAccel, hook_drag_accel, 3.0f)\nMACRO_TUNING_PARAM(HookDragSpeed, hook_drag_speed, 15.0f)\nMACRO_TUNING_PARAM(Gravity, gravity, 0.5f)\n\nMACRO_TUNING_PARAM(VelrampStart, velramp_start, 550)\nMACRO_TUNING_PARAM(VelrampRange, velramp_range, 2000)\nMACRO_TUNING_PARAM(VelrampCurvature, velramp_curvature, 1.4f)\n\n// weapon tuning\nMACRO_TUNING_PARAM(GunCurvature, gun_curvature, 1.25f)\nMACRO_TUNING_PARAM(GunSpeed, gun_speed, 2200.0f)\nMACRO_TUNING_PARAM(GunLifetime, gun_lifetime, 2.0f)\n\nMACRO_TUNING_PARAM(ShotgunCurvature, shotgun_curvature, 1.25f)\nMACRO_TUNING_PARAM(ShotgunSpeed, shotgun_speed, 2750.0f)\nMACRO_TUNING_PARAM(ShotgunSpeeddiff, shotgun_speeddiff, 0.8f)\nMACRO_TUNING_PARAM(ShotgunLifetime, shotgun_lifetime, 0.20f)\n\nMACRO_TUNING_PARAM(GrenadeCurvature, grenade_curvature, 7.0f)\nMACRO_TUNING_PARAM(GrenadeSpeed, grenade_speed, 1000.0f)\nMACRO_TUNING_PARAM(GrenadeLifetime, grenade_lifetime, 2.0f)\n\nMACRO_TUNING_PARAM(LaserReach, laser_reach, 800.0f)\nMACRO_TUNING_PARAM(LaserBounceDelay, laser_bounce_delay, 150)\nMACRO_TUNING_PARAM(LaserBounceNum, laser_bounce_num, 1)\nMACRO_TUNING_PARAM(LaserBounceCost, laser_bounce_cost, 0)\nMACRO_TUNING_PARAM(LaserDamage, laser_damage, 5)\n\nMACRO_TUNING_PARAM(PlayerCollision, player_collision, 1)\nMACRO_TUNING_PARAM(PlayerHooking, player_hooking, 1)\n#endif\n"
  },
  {
    "path": "src/game/variables.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_VARIABLES_H\n#define GAME_VARIABLES_H\n#undef GAME_VARIABLES_H // this file will be included several times\n\n\n// client\nMACRO_CONFIG_INT(ClPredict, cl_predict, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Predict client movements\")\nMACRO_CONFIG_INT(ClNameplates, cl_nameplates, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Show name plates\")\nMACRO_CONFIG_INT(ClNameplatesAlways, cl_nameplates_always, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Always show name plates disregarding of distance\")\nMACRO_CONFIG_INT(ClNameplatesTeamcolors, cl_nameplates_teamcolors, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Use team colors for name plates\")\nMACRO_CONFIG_INT(ClNameplatesSize, cl_nameplates_size, 50, 0, 100, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Size of the name plates from 0 to 100%\")\nMACRO_CONFIG_INT(ClAutoswitchWeapons, cl_autoswitch_weapons, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Auto switch weapon on pickup\")\n\nMACRO_CONFIG_INT(ClShowhud, cl_showhud, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Show ingame HUD\")\nMACRO_CONFIG_INT(ClShowChatFriends, cl_show_chat_friends, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Show only chat messages from friends\")\nMACRO_CONFIG_INT(ClShowfps, cl_showfps, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Show ingame FPS counter\")\n\nMACRO_CONFIG_INT(ClAirjumpindicator, cl_airjumpindicator, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"\")\nMACRO_CONFIG_INT(ClThreadsoundloading, cl_threadsoundloading, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Load sound files threaded\")\n\nMACRO_CONFIG_INT(ClWarningTeambalance, cl_warning_teambalance, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Warn about team balance\")\n\nMACRO_CONFIG_INT(ClMouseDeadzone, cl_mouse_deadzone, 300, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"\")\nMACRO_CONFIG_INT(ClMouseFollowfactor, cl_mouse_followfactor, 60, 0, 200, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"\")\nMACRO_CONFIG_INT(ClMouseMaxDistance, cl_mouse_max_distance, 800, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"\")\n\nMACRO_CONFIG_INT(ClCustomizeSkin, cl_customize_skin, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"\")\n\nMACRO_CONFIG_INT(EdShowkeys, ed_showkeys, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"\")\n\n//MACRO_CONFIG_INT(ClFlow, cl_flow, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"\")\n\nMACRO_CONFIG_INT(ClShowWelcome, cl_show_welcome, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"\")\nMACRO_CONFIG_INT(ClMotdTime, cl_motd_time, 10, 0, 100, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"How long to show the server message of the day\")\n\nMACRO_CONFIG_STR(ClVersionServer, cl_version_server, 100, \"version.teeworlds.com\", CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Server to use to check for new versions\")\n\nMACRO_CONFIG_STR(ClFontfile, cl_fontfile, 255, \"DejaVuSans.ttf\", CFGFLAG_CLIENT|CFGFLAG_SAVE, \"What font file to use\")\nMACRO_CONFIG_STR(ClLanguagefile, cl_languagefile, 255, \"\", CFGFLAG_CLIENT|CFGFLAG_SAVE, \"What language file to use\")\n\nMACRO_CONFIG_INT(PlayerColorBody, player_color_body, 0x1B6F74, 0, 0xFFFFFF, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Player body color\")\nMACRO_CONFIG_INT(PlayerColorTattoo, player_color_tattoo, 0xFF0000FF, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Player tattoo color\")\nMACRO_CONFIG_INT(PlayerColorDecoration, player_color_decoration, 0x1B6F74, 0, 0xFFFFFF, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Player decoration color\")\nMACRO_CONFIG_INT(PlayerColorHands, player_color_hands, 0x1B759E, 0, 0xFFFFFF, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Player hands color\")\nMACRO_CONFIG_INT(PlayerColorFeet, player_color_feet, 0x1C873E, 0, 0xFFFFFF, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Player feet color\")\nMACRO_CONFIG_INT(PlayerColorEyes, player_color_eyes, 0x0000FF, 0, 0xFFFFFF, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Player eyes color\")\nMACRO_CONFIG_INT(PlayerUseCustomColorBody, player_use_custom_color_body, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Toggles usage of custom colors for body\")\nMACRO_CONFIG_INT(PlayerUseCustomColorTattoo, player_use_custom_color_tattoo, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Toggles usage of custom colors for tattoo\")\nMACRO_CONFIG_INT(PlayerUseCustomColorDecoration, player_use_custom_color_decoration, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Toggles usage of custom colors for decoration\")\nMACRO_CONFIG_INT(PlayerUseCustomColorHands, player_use_custom_color_hands, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Toggles usage of custom colors for hands\")\nMACRO_CONFIG_INT(PlayerUseCustomColorFeet, player_use_custom_color_feet, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Toggles usage of custom colors for feet\")\nMACRO_CONFIG_INT(PlayerUseCustomColorEyes, player_use_custom_color_eyes, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Toggles usage of custom colors for eyes\")\nMACRO_CONFIG_STR(PlayerSkin, player_skin, 24, \"default\", CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Player skin\")\nMACRO_CONFIG_STR(PlayerSkinBody, player_skin_body, 24, \"standard\", CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Player skin body\")\nMACRO_CONFIG_STR(PlayerSkinTattoo, player_skin_tattoo, 24, \"\", CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Player skin tattoo\")\nMACRO_CONFIG_STR(PlayerSkinDecoration, player_skin_decoration, 24, \"\", CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Player skin decoration\")\nMACRO_CONFIG_STR(PlayerSkinHands, player_skin_hands, 24, \"standard\", CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Player skin hands\")\nMACRO_CONFIG_STR(PlayerSkinFeet, player_skin_feet, 24, \"standard\", CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Player skin feet\")\nMACRO_CONFIG_STR(PlayerSkinEyes, player_skin_eyes, 24, \"standard\", CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Player skin eyes\")\n\n//MACRO_CONFIG_INT(UiPage, ui_page, 6, 0, 10, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Interface page\")\nMACRO_CONFIG_INT(UiBrowserPage, ui_browser_page, 5, 5, 8, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Interface serverbrowser page\")\nMACRO_CONFIG_INT(UiSettingsPage, ui_settings_page, 0, 0, 5, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Interface settings page\")\n//MACRO_CONFIG_INT(UiToolboxPage, ui_toolbox_page, 0, 0, 2, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Toolbox page\")\nMACRO_CONFIG_STR(UiServerAddress, ui_server_address, 64, \"localhost:8303\", CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Interface server address\")\nMACRO_CONFIG_INT(UiMousesens, ui_mousesens, 100, 5, 100000, CFGFLAG_SAVE|CFGFLAG_CLIENT, \"Mouse sensitivity for menus/editor\")\n\nMACRO_CONFIG_INT(GfxNoclip, gfx_noclip, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Disable clipping\")\n\nMACRO_CONFIG_STR(ClBackgroundMap, cl_background_map, 64, \"menu_night\", CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Background map\")\nMACRO_CONFIG_INT(ClRotationRadius, cl_rotation_radius, 30, 1, 500, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Camera rotation radius\")\nMACRO_CONFIG_INT(ClRotationSpeed, cl_rotation_speed, 40, 1, 120, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Camera rotations in seconds\")\n\nMACRO_CONFIG_INT(ClShowStartMenuImages, cl_show_start_menu_images, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, \"Show start menu images\")\n\n// server\nMACRO_CONFIG_INT(SvWarmup, sv_warmup, 0, -1, 1000, CFGFLAG_SERVER, \"Number of seconds to do warmup before match starts (0 disables, -1 all players ready)\")\nMACRO_CONFIG_STR(SvMotd, sv_motd, 900, \"\", CFGFLAG_SERVER, \"Message of the day to display for the clients\")\nMACRO_CONFIG_INT(SvTeamdamage, sv_teamdamage, 0, 0, 1, CFGFLAG_SERVER, \"Team damage\")\nMACRO_CONFIG_STR(SvMaprotation, sv_maprotation, 768, \"\", CFGFLAG_SERVER, \"Maps to rotate between\")\nMACRO_CONFIG_INT(SvMatchesPerMap, sv_matches_per_map, 1, 1, 100, CFGFLAG_SERVER, \"Number of matches on each map before rotating\")\nMACRO_CONFIG_INT(SvMatchSwap, sv_match_swap, 1, 0, 1, CFGFLAG_SERVER, \"Swap teams between matches\")\nMACRO_CONFIG_INT(SvPowerups, sv_powerups, 1, 0, 1, CFGFLAG_SERVER, \"Allow powerups like ninja\")\nMACRO_CONFIG_INT(SvScorelimit, sv_scorelimit, 20, 0, 1000, CFGFLAG_SERVER, \"Score limit (0 disables)\")\nMACRO_CONFIG_INT(SvTimelimit, sv_timelimit, 0, 0, 1000, CFGFLAG_SERVER, \"Time limit in minutes (0 disables)\")\nMACRO_CONFIG_STR(SvGametype, sv_gametype, 32, \"dm\", CFGFLAG_SERVER, \"Game type (dm, tdm, ctf, lms, sur)\")\nMACRO_CONFIG_INT(SvTournamentMode, sv_tournament_mode, 0, 0, 1, CFGFLAG_SERVER, \"Tournament mode. When enabled, players joins the server as spectator\")\nMACRO_CONFIG_INT(SvPlayerReadyMode, sv_player_ready_mode, 0, 0, 1, CFGFLAG_SERVER, \"When enabled, players can pause/unpause the game and start the game on warmup via their ready state\")\nMACRO_CONFIG_INT(SvSpamprotection, sv_spamprotection, 1, 0, 1, CFGFLAG_SERVER, \"Spam protection\")\n\nMACRO_CONFIG_INT(SvRespawnDelayTDM, sv_respawn_delay_tdm, 3, 0, 10, CFGFLAG_SERVER, \"Time needed to respawn after death in tdm gametype\")\n\nMACRO_CONFIG_INT(SvSpectatorSlots, sv_spectator_slots, 0, 0, MAX_CLIENTS, CFGFLAG_SERVER, \"Number of slots to reserve for spectators\")\nMACRO_CONFIG_INT(SvSkillLevel, sv_skill_level, 1, SERVERINFO_LEVEL_MIN, SERVERINFO_LEVEL_MAX, CFGFLAG_SERVER, \"Supposed player skill level\")\nMACRO_CONFIG_INT(SvTeambalanceTime, sv_teambalance_time, 1, 0, 1000, CFGFLAG_SERVER, \"How many minutes to wait before autobalancing teams\")\nMACRO_CONFIG_INT(SvInactiveKickTime, sv_inactivekick_time, 3, 0, 1000, CFGFLAG_SERVER, \"How many minutes to wait before taking care of inactive players\")\nMACRO_CONFIG_INT(SvInactiveKick, sv_inactivekick, 1, 0, 2, CFGFLAG_SERVER, \"How to deal with inactive players (0=move to spectator, 1=move to free spectator slot/kick, 2=kick)\")\n\nMACRO_CONFIG_INT(SvStrictSpectateMode, sv_strict_spectate_mode, 0, 0, 1, CFGFLAG_SERVER, \"Restricts information in spectator mode\")\nMACRO_CONFIG_INT(SvVoteSpectate, sv_vote_spectate, 1, 0, 1, CFGFLAG_SERVER, \"Allow voting to move players to spectators\")\nMACRO_CONFIG_INT(SvVoteSpectateRejoindelay, sv_vote_spectate_rejoindelay, 3, 0, 1000, CFGFLAG_SERVER, \"How many minutes to wait before a player can rejoin after being moved to spectators by vote\")\nMACRO_CONFIG_INT(SvVoteKick, sv_vote_kick, 1, 0, 1, CFGFLAG_SERVER, \"Allow voting to kick players\")\nMACRO_CONFIG_INT(SvVoteKickMin, sv_vote_kick_min, 0, 0, MAX_CLIENTS, CFGFLAG_SERVER, \"Minimum number of players required to start a kick vote\")\nMACRO_CONFIG_INT(SvVoteKickBantime, sv_vote_kick_bantime, 5, 0, 1440, CFGFLAG_SERVER, \"The time to ban a player if kicked by vote. 0 makes it just use kick\")\n\n// debug\n#ifdef CONF_DEBUG // this one can crash the server if not used correctly\n\tMACRO_CONFIG_INT(DbgDummies, dbg_dummies, 0, 0, 15, CFGFLAG_SERVER, \"\")\n#endif\n\nMACRO_CONFIG_INT(DbgFocus, dbg_focus, 0, 0, 1, CFGFLAG_CLIENT, \"\")\nMACRO_CONFIG_INT(DbgTuning, dbg_tuning, 0, 0, 1, CFGFLAG_CLIENT, \"\")\n#endif\n"
  },
  {
    "path": "src/game/version.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_VERSION_H\n#define GAME_VERSION_H\n#include \"generated/nethash.cpp\"\n#define GAME_VERSION \"0.7 trunk\"\n#define GAME_NETVERSION \"0.7 \" GAME_NETVERSION_HASH\nstatic const char GAME_RELEASE_VERSION[8] = {'0', '.', '6', '1', 0};\n#endif\n"
  },
  {
    "path": "src/game/voting.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef GAME_VOTING_H\n#define GAME_VOTING_H\n\nenum\n{\n\tVOTE_DESC_LENGTH=64,\n\tVOTE_CMD_LENGTH=512,\n\tVOTE_REASON_LENGTH=16,\n\n\tMAX_VOTE_OPTIONS=128,\n\tMAX_VOTE_OPTION_ADD=21,\n\n\tVOTE_COOLDOWN=60,\n};\n\nstruct CVoteOptionClient\n{\n\tCVoteOptionClient *m_pNext;\n\tCVoteOptionClient *m_pPrev;\n\tchar m_aDescription[VOTE_DESC_LENGTH];\n};\n\nstruct CVoteOptionServer\n{\n\tCVoteOptionServer *m_pNext;\n\tCVoteOptionServer *m_pPrev;\n\tchar m_aDescription[VOTE_DESC_LENGTH];\n\tchar m_aCommand[1];\n};\n\n#endif\n"
  },
  {
    "path": "src/mastersrv/mastersrv.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n\n#include <engine/config.h>\n#include <engine/console.h>\n#include <engine/kernel.h>\n#include <engine/storage.h>\n\n#include <engine/shared/config.h>\n#include <engine/shared/netban.h>\n#include <engine/shared/network.h>\n\n#include \"mastersrv.h\"\n\n\nenum {\n\tMTU = 1400,\n\tMAX_SERVERS_PER_PACKET=75,\n\tMAX_PACKETS=16,\n\tMAX_SERVERS=MAX_SERVERS_PER_PACKET*MAX_PACKETS,\n\tEXPIRE_TIME = 90\n};\n\nstruct CCheckServer\n{\n\tenum ServerType m_Type;\n\tNETADDR m_Address;\n\tNETADDR m_AltAddress;\n\tint m_TryCount;\n\tint64 m_TryTime;\n};\n\nstatic CCheckServer m_aCheckServers[MAX_SERVERS];\nstatic int m_NumCheckServers = 0;\n\nstruct CServerEntry\n{\n\tenum ServerType m_Type;\n\tNETADDR m_Address;\n\tint64 m_Expire;\n};\n\nstatic CServerEntry m_aServers[MAX_SERVERS];\nstatic int m_NumServers = 0;\n\nstruct CPacketData\n{\n\tint m_Size;\n\tstruct {\n\t\tunsigned char m_aHeader[sizeof(SERVERBROWSE_LIST)];\n\t\tCMastersrvAddr m_aServers[MAX_SERVERS_PER_PACKET];\n\t} m_Data;\n};\n\nCPacketData m_aPackets[MAX_PACKETS];\nstatic int m_NumPackets = 0;\n\n// legacy code\nstruct CPacketDataLegacy\n{\n\tint m_Size;\n\tstruct {\n\t\tunsigned char m_aHeader[sizeof(SERVERBROWSE_LIST_LEGACY)];\n\t\tCMastersrvAddrLegacy m_aServers[MAX_SERVERS_PER_PACKET];\n\t} m_Data;\n};\n\nCPacketDataLegacy m_aPacketsLegacy[MAX_PACKETS];\nstatic int m_NumPacketsLegacy = 0;\n\n\nstruct CCountPacketData\n{\n\tunsigned char m_Header[sizeof(SERVERBROWSE_COUNT)];\n\tunsigned char m_High;\n\tunsigned char m_Low;\n};\n\nstatic CCountPacketData m_CountData;\nstatic CCountPacketData m_CountDataLegacy;\n\n\nCNetBan m_NetBan;\n\nstatic CNetClient m_NetChecker; // NAT/FW checker\nstatic CNetClient m_NetOp; // main\n\nIConsole *m_pConsole;\n\nvoid BuildPackets()\n{\n\tCServerEntry *pCurrent = &m_aServers[0];\n\tint ServersLeft = m_NumServers;\n\tm_NumPackets = 0;\n\tm_NumPacketsLegacy = 0;\n\tint PacketIndex = 0;\n\tint PacketIndexLegacy = 0;\n\twhile(ServersLeft-- && (m_NumPackets + m_NumPacketsLegacy) < MAX_PACKETS)\n\t{\n\t\tif(pCurrent->m_Type == SERVERTYPE_NORMAL)\n\t\t{\n\t\t\tif(PacketIndex % MAX_SERVERS_PER_PACKET == 0)\n\t\t\t{\n\t\t\t\tPacketIndex = 0;\n\t\t\t\tm_NumPackets++;\n\t\t\t}\n\n\t\t\t// copy header\n\t\t\tmem_copy(m_aPackets[m_NumPackets-1].m_Data.m_aHeader, SERVERBROWSE_LIST, sizeof(SERVERBROWSE_LIST));\n\n\t\t\t// copy server addresses\n\t\t\tif(pCurrent->m_Address.type == NETTYPE_IPV6)\n\t\t\t{\n\t\t\t\tmem_copy(m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp, pCurrent->m_Address.ip,\n\t\t\t\t\tsizeof(m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstatic unsigned char s_aIPV4Mapping[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF};\n\n\t\t\t\tmem_copy(m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp, s_aIPV4Mapping, sizeof(s_aIPV4Mapping));\n\t\t\t\tm_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp[12] = pCurrent->m_Address.ip[0];\n\t\t\t\tm_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp[13] = pCurrent->m_Address.ip[1];\n\t\t\t\tm_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp[14] = pCurrent->m_Address.ip[2];\n\t\t\t\tm_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp[15] = pCurrent->m_Address.ip[3];\n\t\t\t}\n\n\t\t\tm_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aPort[0] = (pCurrent->m_Address.port>>8)&0xff;\n\t\t\tm_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aPort[1] = pCurrent->m_Address.port&0xff;\n\n\t\t\tPacketIndex++;\n\n\t\t\tm_aPackets[m_NumPackets-1].m_Size = sizeof(SERVERBROWSE_LIST) + sizeof(CMastersrvAddr)*PacketIndex;\n\n\t\t\tpCurrent++;\n\t\t}\n\t\telse if(pCurrent->m_Type == SERVERTYPE_LEGACY)\n\t\t{\n\t\t\tif(PacketIndexLegacy % MAX_SERVERS_PER_PACKET == 0)\n\t\t\t{\n\t\t\t\tPacketIndexLegacy = 0;\n\t\t\t\tm_NumPacketsLegacy++;\n\t\t\t}\n\n\t\t\t// copy header\n\t\t\tmem_copy(m_aPacketsLegacy[m_NumPacketsLegacy-1].m_Data.m_aHeader, SERVERBROWSE_LIST_LEGACY, sizeof(SERVERBROWSE_LIST_LEGACY));\n\n\t\t\t// copy server addresses\n\t\t\tmem_copy(m_aPacketsLegacy[m_NumPacketsLegacy-1].m_Data.m_aServers[PacketIndexLegacy].m_aIp, pCurrent->m_Address.ip,\n\t\t\t\tsizeof(m_aPacketsLegacy[m_NumPacketsLegacy-1].m_Data.m_aServers[PacketIndexLegacy].m_aIp));\n\t\t\t// 0.5 has the port in little endian on the network\n\t\t\tm_aPacketsLegacy[m_NumPacketsLegacy-1].m_Data.m_aServers[PacketIndexLegacy].m_aPort[0] = pCurrent->m_Address.port&0xff;\n\t\t\tm_aPacketsLegacy[m_NumPacketsLegacy-1].m_Data.m_aServers[PacketIndexLegacy].m_aPort[1] = (pCurrent->m_Address.port>>8)&0xff;\n\n\t\t\tPacketIndexLegacy++;\n\n\t\t\tm_aPacketsLegacy[m_NumPacketsLegacy-1].m_Size = sizeof(SERVERBROWSE_LIST_LEGACY) + sizeof(CMastersrvAddrLegacy)*PacketIndexLegacy;\n\n\t\t\tpCurrent++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t*pCurrent = m_aServers[m_NumServers-1];\n\t\t\tm_NumServers--;\n\t\t\tdbg_msg(\"mastersrv\", \"error: server of invalid type, dropping it\");\n\t\t}\n\t}\n}\n\nvoid SendOk(NETADDR *pAddr)\n{\n\tCNetChunk p;\n\tp.m_ClientID = -1;\n\tp.m_Address = *pAddr;\n\tp.m_Flags = NETSENDFLAG_CONNLESS;\n\tp.m_DataSize = sizeof(SERVERBROWSE_FWOK);\n\tp.m_pData = SERVERBROWSE_FWOK;\n\n\t// send on both to be sure\n\tm_NetChecker.Send(&p);\n\tm_NetOp.Send(&p);\n}\n\nvoid SendError(NETADDR *pAddr)\n{\n\tCNetChunk p;\n\tp.m_ClientID = -1;\n\tp.m_Address = *pAddr;\n\tp.m_Flags = NETSENDFLAG_CONNLESS;\n\tp.m_DataSize = sizeof(SERVERBROWSE_FWERROR);\n\tp.m_pData = SERVERBROWSE_FWERROR;\n\tm_NetOp.Send(&p);\n}\n\nvoid SendCheck(NETADDR *pAddr)\n{\n\tCNetChunk p;\n\tp.m_ClientID = -1;\n\tp.m_Address = *pAddr;\n\tp.m_Flags = NETSENDFLAG_CONNLESS;\n\tp.m_DataSize = sizeof(SERVERBROWSE_FWCHECK);\n\tp.m_pData = SERVERBROWSE_FWCHECK;\n\tm_NetChecker.Send(&p);\n}\n\nvoid AddCheckserver(NETADDR *pInfo, NETADDR *pAlt, ServerType Type)\n{\n\t// add server\n\tif(m_NumCheckServers == MAX_SERVERS)\n\t{\n\t\tdbg_msg(\"mastersrv\", \"error: mastersrv is full\");\n\t\treturn;\n\t}\n\n\tchar aAddrStr[NETADDR_MAXSTRSIZE];\n\tnet_addr_str(pInfo, aAddrStr, sizeof(aAddrStr), true);\n\tchar aAltAddrStr[NETADDR_MAXSTRSIZE];\n\tnet_addr_str(pAlt, aAltAddrStr, sizeof(aAltAddrStr), true);\n\tdbg_msg(\"mastersrv\", \"checking: %s (%s)\", aAddrStr, aAltAddrStr);\n\tm_aCheckServers[m_NumCheckServers].m_Address = *pInfo;\n\tm_aCheckServers[m_NumCheckServers].m_AltAddress = *pAlt;\n\tm_aCheckServers[m_NumCheckServers].m_TryCount = 0;\n\tm_aCheckServers[m_NumCheckServers].m_TryTime = 0;\n\tm_aCheckServers[m_NumCheckServers].m_Type = Type;\n\tm_NumCheckServers++;\n}\n\nvoid AddServer(NETADDR *pInfo, ServerType Type)\n{\n\t// see if server already exists in list\n\tfor(int i = 0; i < m_NumServers; i++)\n\t{\n\t\tif(net_addr_comp(&m_aServers[i].m_Address, pInfo) == 0)\n\t\t{\n\t\t\tchar aAddrStr[NETADDR_MAXSTRSIZE];\n\t\t\tnet_addr_str(pInfo, aAddrStr, sizeof(aAddrStr), true);\n\t\t\tdbg_msg(\"mastersrv\", \"updated: %s\", aAddrStr);\n\t\t\tm_aServers[i].m_Expire = time_get()+time_freq()*EXPIRE_TIME;\n\t\t\treturn;\n\t\t}\n\t}\n\n\t// add server\n\tif(m_NumServers == MAX_SERVERS)\n\t{\n\t\tdbg_msg(\"mastersrv\", \"error: mastersrv is full\");\n\t\treturn;\n\t}\n\n\tchar aAddrStr[NETADDR_MAXSTRSIZE];\n\tnet_addr_str(pInfo, aAddrStr, sizeof(aAddrStr), true);\n\tdbg_msg(\"mastersrv\", \"added: %s\", aAddrStr);\n\tm_aServers[m_NumServers].m_Address = *pInfo;\n\tm_aServers[m_NumServers].m_Expire = time_get()+time_freq()*EXPIRE_TIME;\n\tm_aServers[m_NumServers].m_Type = Type;\n\tm_NumServers++;\n}\n\nvoid UpdateServers()\n{\n\tint64 Now = time_get();\n\tint64 Freq = time_freq();\n\tfor(int i = 0; i < m_NumCheckServers; i++)\n\t{\n\t\tif(Now > m_aCheckServers[i].m_TryTime+Freq)\n\t\t{\n\t\t\tif(m_aCheckServers[i].m_TryCount == 10)\n\t\t\t{\n\t\t\t\tchar aAddrStr[NETADDR_MAXSTRSIZE];\n\t\t\t\tnet_addr_str(&m_aCheckServers[i].m_Address, aAddrStr, sizeof(aAddrStr), true);\n\t\t\t\tchar aAltAddrStr[NETADDR_MAXSTRSIZE];\n\t\t\t\tnet_addr_str(&m_aCheckServers[i].m_AltAddress, aAltAddrStr, sizeof(aAltAddrStr), true);\n\t\t\t\tdbg_msg(\"mastersrv\", \"check failed: %s (%s)\", aAddrStr, aAltAddrStr);\n\n\t\t\t\t// FAIL!!\n\t\t\t\tSendError(&m_aCheckServers[i].m_Address);\n\t\t\t\tm_aCheckServers[i] = m_aCheckServers[m_NumCheckServers-1];\n\t\t\t\tm_NumCheckServers--;\n\t\t\t\ti--;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_aCheckServers[i].m_TryCount++;\n\t\t\t\tm_aCheckServers[i].m_TryTime = Now;\n\t\t\t\tif(m_aCheckServers[i].m_TryCount&1)\n\t\t\t\t\tSendCheck(&m_aCheckServers[i].m_Address);\n\t\t\t\telse\n\t\t\t\t\tSendCheck(&m_aCheckServers[i].m_AltAddress);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid PurgeServers()\n{\n\tint64 Now = time_get();\n\tint i = 0;\n\twhile(i < m_NumServers)\n\t{\n\t\tif(m_aServers[i].m_Expire < Now)\n\t\t{\n\t\t\t// remove server\n\t\t\tchar aAddrStr[NETADDR_MAXSTRSIZE];\n\t\t\tnet_addr_str(&m_aServers[i].m_Address, aAddrStr, sizeof(aAddrStr), true);\n\t\t\tdbg_msg(\"mastersrv\", \"expired: %s\", aAddrStr);\n\t\t\tm_aServers[i] = m_aServers[m_NumServers-1];\n\t\t\tm_NumServers--;\n\t\t}\n\t\telse\n\t\t\ti++;\n\t}\n}\n\nvoid ReloadBans()\n{\n\tm_NetBan.UnbanAll();\n\tm_pConsole->ExecuteFile(\"master.cfg\");\n}\n\nint main(int argc, const char **argv) // ignore_convention\n{\n\tint64 LastBuild = 0, LastBanReload = 0;\n\tServerType Type = SERVERTYPE_INVALID;\n\tNETADDR BindAddr;\n\n\tdbg_logger_stdout();\n\tnet_init();\n\n\tmem_copy(m_CountData.m_Header, SERVERBROWSE_COUNT, sizeof(SERVERBROWSE_COUNT));\n\tmem_copy(m_CountDataLegacy.m_Header, SERVERBROWSE_COUNT_LEGACY, sizeof(SERVERBROWSE_COUNT_LEGACY));\n\n\tIKernel *pKernel = IKernel::Create();\n\tIStorage *pStorage = CreateStorage(\"Teeworlds\", IStorage::STORAGETYPE_BASIC, argc, argv);\n\tIConfig *pConfig = CreateConfig();\n\tm_pConsole = CreateConsole(CFGFLAG_MASTER);\n\t\n\tbool RegisterFail = !pKernel->RegisterInterface(pStorage);\n\tRegisterFail |= !pKernel->RegisterInterface(m_pConsole);\n\tRegisterFail |= !pKernel->RegisterInterface(pConfig);\n\n\tif(RegisterFail)\n\t\treturn -1;\n\n\tpConfig->Init();\n\tm_NetBan.Init(m_pConsole, pStorage);\n\tif(argc > 1) // ignore_convention\n\t\tm_pConsole->ParseArguments(argc-1, &argv[1]); // ignore_convention\n\n\tif(g_Config.m_Bindaddr[0] && net_host_lookup(g_Config.m_Bindaddr, &BindAddr, NETTYPE_ALL) == 0)\n\t{\n\t\t// got bindaddr\n\t\tBindAddr.type = NETTYPE_ALL;\n\t\tBindAddr.port = MASTERSERVER_PORT;\n\t}\n\telse\n\t{\n\t\tmem_zero(&BindAddr, sizeof(BindAddr));\n\t\tBindAddr.type = NETTYPE_ALL;\n\t\tBindAddr.port = MASTERSERVER_PORT;\n\t}\n\n\tif(!m_NetOp.Open(BindAddr, 0))\n\t{\n\t\tdbg_msg(\"mastersrv\", \"couldn't start network (op)\");\n\t\treturn -1;\n\t}\n\tBindAddr.port = MASTERSERVER_PORT+1;\n\tif(!m_NetChecker.Open(BindAddr, 0))\n\t{\n\t\tdbg_msg(\"mastersrv\", \"couldn't start network (checker)\");\n\t\treturn -1;\n\t}\n\n\t// process pending commands\n\tm_pConsole->StoreCommands(false);\n\n\tdbg_msg(\"mastersrv\", \"started\");\n\n\twhile(1)\n\t{\n\t\tm_NetOp.Update();\n\t\tm_NetChecker.Update();\n\n\t\t// process m_aPackets\n\t\tCNetChunk Packet;\n\t\twhile(m_NetOp.Recv(&Packet))\n\t\t{\n\t\t\t// check if the server is banned\n\t\t\tif(m_NetBan.IsBanned(&Packet.m_Address, 0, 0))\n\t\t\t\tcontinue;\n\n\t\t\tif(Packet.m_DataSize == sizeof(SERVERBROWSE_HEARTBEAT)+2 &&\n\t\t\t\tmem_comp(Packet.m_pData, SERVERBROWSE_HEARTBEAT, sizeof(SERVERBROWSE_HEARTBEAT)) == 0)\n\t\t\t{\n\t\t\t\tNETADDR Alt;\n\t\t\t\tunsigned char *d = (unsigned char *)Packet.m_pData;\n\t\t\t\tAlt = Packet.m_Address;\n\t\t\t\tAlt.port =\n\t\t\t\t\t(d[sizeof(SERVERBROWSE_HEARTBEAT)]<<8) |\n\t\t\t\t\td[sizeof(SERVERBROWSE_HEARTBEAT)+1];\n\n\t\t\t\t// add it\n\t\t\t\tAddCheckserver(&Packet.m_Address, &Alt, SERVERTYPE_NORMAL);\n\t\t\t}\n\t\t\telse if(Packet.m_DataSize == sizeof(SERVERBROWSE_HEARTBEAT_LEGACY)+2 &&\n\t\t\t\tmem_comp(Packet.m_pData, SERVERBROWSE_HEARTBEAT_LEGACY, sizeof(SERVERBROWSE_HEARTBEAT_LEGACY)) == 0)\n\t\t\t{\n\t\t\t\tNETADDR Alt;\n\t\t\t\tunsigned char *d = (unsigned char *)Packet.m_pData;\n\t\t\t\tAlt = Packet.m_Address;\n\t\t\t\tAlt.port =\n\t\t\t\t\t(d[sizeof(SERVERBROWSE_HEARTBEAT)]<<8) |\n\t\t\t\t\td[sizeof(SERVERBROWSE_HEARTBEAT)+1];\n\n\t\t\t\t// add it\n\t\t\t\tAddCheckserver(&Packet.m_Address, &Alt, SERVERTYPE_LEGACY);\n\t\t\t}\n\n\t\t\telse if(Packet.m_DataSize == sizeof(SERVERBROWSE_GETCOUNT) &&\n\t\t\t\tmem_comp(Packet.m_pData, SERVERBROWSE_GETCOUNT, sizeof(SERVERBROWSE_GETCOUNT)) == 0)\n\t\t\t{\n\t\t\t\tdbg_msg(\"mastersrv\", \"count requested, responding with %d\", m_NumServers);\n\n\t\t\t\tCNetChunk p;\n\t\t\t\tp.m_ClientID = -1;\n\t\t\t\tp.m_Address = Packet.m_Address;\n\t\t\t\tp.m_Flags = NETSENDFLAG_CONNLESS;\n\t\t\t\tp.m_DataSize = sizeof(m_CountData);\n\t\t\t\tp.m_pData = &m_CountData;\n\t\t\t\tm_CountData.m_High = (m_NumServers>>8)&0xff;\n\t\t\t\tm_CountData.m_Low = m_NumServers&0xff;\n\t\t\t\tm_NetOp.Send(&p);\n\t\t\t}\n\t\t\telse if(Packet.m_DataSize == sizeof(SERVERBROWSE_GETCOUNT_LEGACY) &&\n\t\t\t\tmem_comp(Packet.m_pData, SERVERBROWSE_GETCOUNT_LEGACY, sizeof(SERVERBROWSE_GETCOUNT_LEGACY)) == 0)\n\t\t\t{\n\t\t\t\tdbg_msg(\"mastersrv\", \"count requested, responding with %d\", m_NumServers);\n\n\t\t\t\tCNetChunk p;\n\t\t\t\tp.m_ClientID = -1;\n\t\t\t\tp.m_Address = Packet.m_Address;\n\t\t\t\tp.m_Flags = NETSENDFLAG_CONNLESS;\n\t\t\t\tp.m_DataSize = sizeof(m_CountData);\n\t\t\t\tp.m_pData = &m_CountDataLegacy;\n\t\t\t\tm_CountDataLegacy.m_High = (m_NumServers>>8)&0xff;\n\t\t\t\tm_CountDataLegacy.m_Low = m_NumServers&0xff;\n\t\t\t\tm_NetOp.Send(&p);\n\t\t\t}\n\t\t\telse if(Packet.m_DataSize == sizeof(SERVERBROWSE_GETLIST) &&\n\t\t\t\tmem_comp(Packet.m_pData, SERVERBROWSE_GETLIST, sizeof(SERVERBROWSE_GETLIST)) == 0)\n\t\t\t{\n\t\t\t\t// someone requested the list\n\t\t\t\tdbg_msg(\"mastersrv\", \"requested, responding with %d m_aServers\", m_NumServers);\n\n\t\t\t\tCNetChunk p;\n\t\t\t\tp.m_ClientID = -1;\n\t\t\t\tp.m_Address = Packet.m_Address;\n\t\t\t\tp.m_Flags = NETSENDFLAG_CONNLESS;\n\n\t\t\t\tfor(int i = 0; i < m_NumPackets; i++)\n\t\t\t\t{\n\t\t\t\t\tp.m_DataSize = m_aPackets[i].m_Size;\n\t\t\t\t\tp.m_pData = &m_aPackets[i].m_Data;\n\t\t\t\t\tm_NetOp.Send(&p);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(Packet.m_DataSize == sizeof(SERVERBROWSE_GETLIST_LEGACY) &&\n\t\t\t\tmem_comp(Packet.m_pData, SERVERBROWSE_GETLIST_LEGACY, sizeof(SERVERBROWSE_GETLIST_LEGACY)) == 0)\n\t\t\t{\n\t\t\t\t// someone requested the list\n\t\t\t\tdbg_msg(\"mastersrv\", \"requested, responding with %d m_aServers\", m_NumServers);\n\n\t\t\t\tCNetChunk p;\n\t\t\t\tp.m_ClientID = -1;\n\t\t\t\tp.m_Address = Packet.m_Address;\n\t\t\t\tp.m_Flags = NETSENDFLAG_CONNLESS;\n\n\t\t\t\tfor(int i = 0; i < m_NumPacketsLegacy; i++)\n\t\t\t\t{\n\t\t\t\t\tp.m_DataSize = m_aPacketsLegacy[i].m_Size;\n\t\t\t\t\tp.m_pData = &m_aPacketsLegacy[i].m_Data;\n\t\t\t\t\tm_NetOp.Send(&p);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// process m_aPackets\n\t\twhile(m_NetChecker.Recv(&Packet))\n\t\t{\n\t\t\t// check if the server is banned\n\t\t\tif(m_NetBan.IsBanned(&Packet.m_Address, 0, 0))\n\t\t\t\tcontinue;\n\n\t\t\tif(Packet.m_DataSize == sizeof(SERVERBROWSE_FWRESPONSE) &&\n\t\t\t\tmem_comp(Packet.m_pData, SERVERBROWSE_FWRESPONSE, sizeof(SERVERBROWSE_FWRESPONSE)) == 0)\n\t\t\t{\n\t\t\t\tType = SERVERTYPE_INVALID;\n\t\t\t\t// remove it from checking\n\t\t\t\tfor(int i = 0; i < m_NumCheckServers; i++)\n\t\t\t\t{\n\t\t\t\t\tif(net_addr_comp(&m_aCheckServers[i].m_Address, &Packet.m_Address) == 0 ||\n\t\t\t\t\t\tnet_addr_comp(&m_aCheckServers[i].m_AltAddress, &Packet.m_Address) == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tType = m_aCheckServers[i].m_Type;\n\t\t\t\t\t\tm_NumCheckServers--;\n\t\t\t\t\t\tm_aCheckServers[i] = m_aCheckServers[m_NumCheckServers];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// drops servers that were not in the CheckServers list\n\t\t\t\tif(Type == SERVERTYPE_INVALID)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tAddServer(&Packet.m_Address, Type);\n\t\t\t\tSendOk(&Packet.m_Address);\n\t\t\t}\n\t\t}\n\n\t\tif(time_get()-LastBanReload > time_freq()*300)\n\t\t{\n\t\t\tLastBanReload = time_get();\n\n\t\t\tReloadBans();\n\t\t}\n\n\t\tif(time_get()-LastBuild > time_freq()*5)\n\t\t{\n\t\t\tLastBuild = time_get();\n\n\t\t\tPurgeServers();\n\t\t\tUpdateServers();\n\t\t\tBuildPackets();\n\t\t}\n\n\t\t// be nice to the CPU\n\t\tthread_sleep(1);\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "src/mastersrv/mastersrv.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef MASTERSRV_MASTERSRV_H\n#define MASTERSRV_MASTERSRV_H\nstatic const int MASTERSERVER_PORT = 8300;\n\nenum ServerType\n{\n\tSERVERTYPE_INVALID = -1,\n\tSERVERTYPE_NORMAL,\n\tSERVERTYPE_LEGACY\n};\n\nstruct CMastersrvAddr\n{\n\tunsigned char m_aIp[16];\n\tunsigned char m_aPort[2];\n};\n\nstatic const unsigned char SERVERBROWSE_HEARTBEAT[] = {255, 255, 255, 255, 'b', 'e', 'a', '2'};\n\nstatic const unsigned char SERVERBROWSE_GETLIST[] = {255, 255, 255, 255, 'r', 'e', 'q', '2'};\nstatic const unsigned char SERVERBROWSE_LIST[] = {255, 255, 255, 255, 'l', 'i', 's', '2'};\n\nstatic const unsigned char SERVERBROWSE_GETCOUNT[] = {255, 255, 255, 255, 'c', 'o', 'u', '2'};\nstatic const unsigned char SERVERBROWSE_COUNT[] = {255, 255, 255, 255, 's', 'i', 'z', '2'};\n\nstatic const unsigned char SERVERBROWSE_GETINFO[] = {255, 255, 255, 255, 'g', 'i', 'e', '3'};\nstatic const unsigned char SERVERBROWSE_INFO[] = {255, 255, 255, 255, 'i', 'n', 'f', '3'};\n\nstatic const unsigned char SERVERBROWSE_FWCHECK[] = {255, 255, 255, 255, 'f', 'w', '?', '?'};\nstatic const unsigned char SERVERBROWSE_FWRESPONSE[] = {255, 255, 255, 255, 'f', 'w', '!', '!'};\nstatic const unsigned char SERVERBROWSE_FWOK[] = {255, 255, 255, 255, 'f', 'w', 'o', 'k'};\nstatic const unsigned char SERVERBROWSE_FWERROR[] = {255, 255, 255, 255, 'f', 'w', 'e', 'r'};\n\n\n// packet headers for the 0.5 branch\n\nstruct CMastersrvAddrLegacy\n{\n\tunsigned char m_aIp[4];\n\tunsigned char m_aPort[2];\n};\n\nstatic const unsigned char SERVERBROWSE_HEARTBEAT_LEGACY[] = {255, 255, 255, 255, 'b', 'e', 'a', 't'};\n\nstatic const unsigned char SERVERBROWSE_GETLIST_LEGACY[] = {255, 255, 255, 255, 'r', 'e', 'q', 't'};\nstatic const unsigned char SERVERBROWSE_LIST_LEGACY[] = {255, 255, 255, 255, 'l', 'i', 's', 't'};\n\nstatic const unsigned char SERVERBROWSE_GETCOUNT_LEGACY[] = {255, 255, 255, 255, 'c', 'o', 'u', 'n'};\nstatic const unsigned char SERVERBROWSE_COUNT_LEGACY[] = {255, 255, 255, 255, 's', 'i', 'z', 'e'};\n#endif\n"
  },
  {
    "path": "src/osxlaunch/client.h",
    "content": "#ifndef OSXLAUNCH_CLIENT_H\n#define OSXLAUNCH_CLIENT_H\n/*\tSDLMain.m - main entry point for our Cocoa-ized SDL app\n\t\tInitial Version: Darrell Walisser <dwaliss1@purdue.edu>\n\t\tNon-NIB-Code & other changes: Max Horn <max@quendi.de>\n\n\tFeel free to customize this file to suit your needs\n*/\n\n#import <Cocoa/Cocoa.h>\n\n@interface SDLMain : NSObject\n@end\n#endif\n"
  },
  {
    "path": "src/osxlaunch/client.m",
    "content": "/*\tSDLMain.m - main entry point for our Cocoa-ized SDL app\n\t\tInitial Version: Darrell Walisser <dwaliss1@purdue.edu>\n\t\tNon-NIB-Code & other changes: Max Horn <max@quendi.de>\n\n\tFeel free to customize this file to suit your needs\n*/\n\n#import <SDL.h>\n#import \"client.h\"\n#import <sys/param.h> /* for MAXPATHLEN */\n#import <unistd.h>\n\n/* For some reaon, Apple removed setAppleMenu from the headers in 10.4,\n but the method still is there and works. To avoid warnings, we declare\n it ourselves here. */\n@interface NSApplication(SDL_Missing_Methods)\n- (void)setAppleMenu:(NSMenu *)menu;\n@end\n\n/* Use this flag to determine whether we use SDLMain.nib or not */\n#define\t\tSDL_USE_NIB_FILE\t0\n\n/* Use this flag to determine whether we use CPS (docking) or not */\n#define\t\tSDL_USE_CPS\t\t1\n#ifdef SDL_USE_CPS\n/* Portions of CPS.h */\ntypedef struct CPSProcessSerNum\n{\n\tUInt32\t\tlo;\n\tUInt32\t\thi;\n} CPSProcessSerNum;\n\nextern OSErr\tCPSGetCurrentProcess( CPSProcessSerNum *psn);\nextern OSErr \tCPSEnableForegroundOperation( CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5);\nextern OSErr\tCPSSetFrontProcess( CPSProcessSerNum *psn);\n\n#endif /* SDL_USE_CPS */\n\nstatic int gArgc;\nstatic char **gArgv;\nstatic BOOL gFinderLaunch;\nstatic BOOL gCalledAppMainline = FALSE;\n\nstatic NSString *getApplicationName(void)\n{\n\tNSDictionary *dict;\n\tNSString *appName = 0;\n\n\t/* Determine the application name */\n\tdict = (NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle());\n\tif (dict)\n\t\tappName = [dict objectForKey: @\"CFBundleName\"];\n\n\tif (![appName length])\n\t\tappName = [[NSProcessInfo processInfo] processName];\n\n\treturn appName;\n}\n\n#if SDL_USE_NIB_FILE\n/* A helper category for NSString */\n@interface NSString (ReplaceSubString)\n- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString;\n@end\n#endif\n\n@interface SDLApplication : NSApplication\n@end\n\n@implementation SDLApplication\n/* Invoked from the Quit menu item */\n- (void)terminate:(id)sender\n{\n\t/* Post a SDL_QUIT event */\n\tSDL_Event event;\n\tevent.type = SDL_QUIT;\n\tSDL_PushEvent(&event);\n}\n@end\n\n/* The main class of the application, the application's delegate */\n@implementation SDLMain\n\n/* Set the working directory to the .app's parent directory */\n- (void) setupWorkingDirectory:(BOOL)shouldChdir\n{\n\tNSString *resourcePath = [[NSBundle mainBundle] resourcePath];\n\t[[NSFileManager defaultManager] changeCurrentDirectoryPath:resourcePath];\n}\n\n#if SDL_USE_NIB_FILE\n\n/* Fix menu to contain the real app name instead of \"SDL App\" */\n- (void)fixMenu:(NSMenu *)aMenu withAppName:(NSString *)appName\n{\n\tNSRange aRange;\n\tNSEnumerator *enumerator;\n\tNSMenuItem *menuItem;\n\n\taRange = [[aMenu title] rangeOfString:@\"SDL App\"];\n\tif (aRange.length != 0)\n\t\t[aMenu setTitle: [[aMenu title] stringByReplacingRange:aRange with:appName]];\n\n\tenumerator = [[aMenu itemArray] objectEnumerator];\n\twhile ((menuItem = [enumerator nextObject]))\n\t{\n\t\taRange = [[menuItem title] rangeOfString:@\"SDL App\"];\n\t\tif (aRange.length != 0)\n\t\t\t[menuItem setTitle: [[menuItem title] stringByReplacingRange:aRange with:appName]];\n\t\tif ([menuItem hasSubmenu])\n\t\t\t[self fixMenu:[menuItem submenu] withAppName:appName];\n\t}\n\t[ aMenu sizeToFit ];\n}\n\n#else\n\nstatic void setApplicationMenu(void)\n{\n\t/* warning: this code is very odd */\n\tNSMenu *appleMenu;\n\tNSMenuItem *menuItem;\n\tNSString *title;\n\tNSString *appName;\n\n\tappName = getApplicationName();\n\tappleMenu = [[NSMenu alloc] initWithTitle:@\"\"];\n\n\t/* Add menu items */\n\ttitle = [@\"About \" stringByAppendingString:appName];\n\t[appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@\"\"];\n\n\t[appleMenu addItem:[NSMenuItem separatorItem]];\n\n\ttitle = [@\"Hide \" stringByAppendingString:appName];\n\t[appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@\"h\"];\n\n\tmenuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@\"Hide Others\" action:@selector(hideOtherApplications:) keyEquivalent:@\"h\"];\n\t[menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];\n\n\t[appleMenu addItemWithTitle:@\"Show All\" action:@selector(unhideAllApplications:) keyEquivalent:@\"\"];\n\n\t[appleMenu addItem:[NSMenuItem separatorItem]];\n\n\ttitle = [@\"Quit \" stringByAppendingString:appName];\n\t[appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@\"q\"];\n\n\n\t/* Put menu into the menubar */\n\tmenuItem = [[NSMenuItem alloc] initWithTitle:@\"\" action:nil keyEquivalent:@\"\"];\n\t[menuItem setSubmenu:appleMenu];\n\t[[NSApp mainMenu] addItem:menuItem];\n\n\t/* Tell the application object that this is now the application menu */\n\t[NSApp setAppleMenu:appleMenu];\n\n\t/* Finally give up our references to the objects */\n\t[appleMenu release];\n\t[menuItem release];\n}\n\n/* Create a window menu */\nstatic void setupWindowMenu(void)\n{\n\tNSMenu\t\t*windowMenu;\n\tNSMenuItem\t*windowMenuItem;\n\tNSMenuItem\t*menuItem;\n\n\twindowMenu = [[NSMenu alloc] initWithTitle:@\"Window\"];\n\n\t/* \"Minimize\" item */\n\tmenuItem = [[NSMenuItem alloc] initWithTitle:@\"Minimize\" action:@selector(performMiniaturize:) keyEquivalent:@\"m\"];\n\t[windowMenu addItem:menuItem];\n\t[menuItem release];\n\n\t/* Put menu into the menubar */\n\twindowMenuItem = [[NSMenuItem alloc] initWithTitle:@\"Window\" action:nil keyEquivalent:@\"\"];\n\t[windowMenuItem setSubmenu:windowMenu];\n\t[[NSApp mainMenu] addItem:windowMenuItem];\n\n\t/* Tell the application object that this is now the window menu */\n\t[NSApp setWindowsMenu:windowMenu];\n\n\t/* Finally give up our references to the objects */\n\t[windowMenu release];\n\t[windowMenuItem release];\n}\n\n/* Replacement for NSApplicationMain */\nstatic void CustomApplicationMain (int argc, char **argv)\n{\n\tNSAutoreleasePool\t*pool = [[NSAutoreleasePool alloc] init];\n\tSDLMain\t\t\t\t*sdlMain;\n\n\t/* Ensure the application object is initialised */\n\t[SDLApplication sharedApplication];\n\n#ifdef SDL_USE_CPS\n\t{\n\t\tCPSProcessSerNum PSN;\n\t\t/* Tell the dock about us */\n\t\tif (!CPSGetCurrentProcess(&PSN))\n\t\t\tif (!CPSEnableForegroundOperation(&PSN,0x03,0x3C,0x2C,0x1103))\n\t\t\t\tif (!CPSSetFrontProcess(&PSN))\n\t\t\t\t\t[SDLApplication sharedApplication];\n\t}\n#endif /* SDL_USE_CPS */\n\n\t/* Set up the menubar */\n\t[NSApp setMainMenu:[[NSMenu alloc] init]];\n\tsetApplicationMenu();\n\tsetupWindowMenu();\n\n\t/* Create SDLMain and make it the app delegate */\n\tsdlMain = [[SDLMain alloc] init];\n\t[NSApp setDelegate:sdlMain];\n\n\t/* Start the main event loop */\n\t[NSApp run];\n\n\t[sdlMain release];\n\t[pool release];\n}\n\n#endif\n\n\n/*\n * Catch document open requests...this lets us notice files when the app\n * was launched by double-clicking a document, or when a document was\n * dragged/dropped on the app's icon. You need to have a\n * CFBundleDocumentsType section in your Info.plist to get this message,\n * apparently.\n *\n * Files are added to gArgv, so to the app, they'll look like command line\n * arguments. Previously, apps launched from the finder had nothing but\n * an argv[0].\n *\n * This message may be received multiple times to open several docs on launch.\n *\n * This message is ignored once the app's mainline has been called.\n */\n- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename\n{\n\tconst char *temparg;\n\tsize_t arglen;\n\tchar *arg;\n\tchar **newargv;\n\n\tif (!gFinderLaunch) /* MacOS is passing command line args. */\n\t\treturn FALSE;\n\n\tif (gCalledAppMainline) /* app has started, ignore this document. */\n\t\treturn FALSE;\n\n\ttemparg = [filename UTF8String];\n\targlen = SDL_strlen(temparg) + 1;\n\targ = (char *) SDL_malloc(arglen);\n\tif (arg == NULL)\n\t\treturn FALSE;\n\n\tnewargv = (char **) realloc(gArgv, sizeof (char *) * (gArgc + 2));\n\tif (newargv == NULL)\n\t{\n\t\tSDL_free(arg);\n\t\treturn FALSE;\n\t}\n\tgArgv = newargv;\n\n\tSDL_strlcpy(arg, temparg, arglen);\n\tgArgv[gArgc++] = arg;\n\tgArgv[gArgc] = NULL;\n\treturn TRUE;\n}\n\n\n/* Called when the internal event loop has just started running */\n- (void) applicationDidFinishLaunching: (NSNotification *) note\n{\n\tint status;\n\n\t/* Set the working directory to the .app's parent directory */\n\t[self setupWorkingDirectory:gFinderLaunch];\n\n#if SDL_USE_NIB_FILE\n\t/* Set the main menu to contain the real app name instead of \"SDL App\" */\n\t[self fixMenu:[NSApp mainMenu] withAppName:getApplicationName()];\n#endif\n\n\t/* Hand off to main application code */\n\tgCalledAppMainline = TRUE;\n\tstatus = SDL_main (gArgc, gArgv);\n\n\t/* We're done, thank you for playing */\n\texit(status);\n}\n@end\n\n\n@implementation NSString (ReplaceSubString)\n\n- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString\n{\n\tunsigned int bufferSize;\n\tunsigned int selfLen = [self length];\n\tunsigned int aStringLen = [aString length];\n\tunichar *buffer;\n\tNSRange localRange;\n\tNSString *result;\n\n\tbufferSize = selfLen + aStringLen - aRange.length;\n\tbuffer = NSAllocateMemoryPages(bufferSize*sizeof(unichar));\n\n\t/* Get first part into buffer */\n\tlocalRange.location = 0;\n\tlocalRange.length = aRange.location;\n\t[self getCharacters:buffer range:localRange];\n\n\t/* Get middle part into buffer */\n\tlocalRange.location = 0;\n\tlocalRange.length = aStringLen;\n\t[aString getCharacters:(buffer+aRange.location) range:localRange];\n\n\t/* Get last part into buffer */\n\tlocalRange.location = aRange.location + aRange.length;\n\tlocalRange.length = selfLen - localRange.location;\n\t[self getCharacters:(buffer+aRange.location+aStringLen) range:localRange];\n\n\t/* Build output string */\n\tresult = [NSString stringWithCharacters:buffer length:bufferSize];\n\n\tNSDeallocateMemoryPages(buffer, bufferSize);\n\n\treturn result;\n}\n\n@end\n\n#ifdef main\n#undef main\n#endif\n\n\n/* Main entry point to executable - should *not* be SDL_main! */\nint main (int argc, char **argv)\n{\n\t/* Copy the arguments into a global variable */\n\t/* This is passed if we are launched by double-clicking */\n\tif ( argc >= 2 && strncmp (argv[1], \"-psn\", 4) == 0 ) {\n\t\tgArgv = (char **) SDL_malloc(sizeof (char *) * 2);\n\t\tgArgv[0] = argv[0];\n\t\tgArgv[1] = NULL;\n\t\tgArgc = 1;\n\t\tgFinderLaunch = YES;\n\t} else {\n\t\tint i;\n\t\tgArgc = argc;\n\t\tgArgv = (char **) SDL_malloc(sizeof (char *) * (argc+1));\n\t\tfor (i = 0; i <= argc; i++)\n\t\t\tgArgv[i] = argv[i];\n\t\tgFinderLaunch = NO;\n\t}\n\n#if SDL_USE_NIB_FILE\n\t[SDLApplication poseAsClass:[NSApplication class]];\n\tNSApplicationMain (argc, argv);\n#else\n\tCustomApplicationMain (argc, argv);\n#endif\n\n\treturn 0;\n}\n\n"
  },
  {
    "path": "src/osxlaunch/server.m",
    "content": "#import <Cocoa/Cocoa.h>\n\n@interface ServerView : NSTextView\n{\n\tNSTask *task;\n\tNSFileHandle *file;\n}\n- (void)listenTo: (NSTask*)t;\n@end\n\n@implementation ServerView\n- (void)listenTo: (NSTask*)t;\n{\n\tNSPipe *pipe;\n\ttask = t;\n\tpipe = [NSPipe pipe];\n\t[task setStandardOutput: pipe];\n\tfile = [pipe fileHandleForReading];\n\n\t[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(outputNotification:) name: NSFileHandleReadCompletionNotification object: file];\n\n\t[file readInBackgroundAndNotify];\n}\n\n- (void) outputNotification: (NSNotification *) notification\n{\n\tNSData *data = [[[notification userInfo] objectForKey: NSFileHandleNotificationDataItem] retain];\n\tNSString *string = [[NSString alloc] initWithData: data encoding: NSASCIIStringEncoding];\n\tNSAttributedString *attrstr = [[NSAttributedString alloc] initWithString: string];\n\n\t[[self textStorage] appendAttributedString: attrstr];\n\tint length = [[self textStorage] length];\n\tNSRange range = NSMakeRange(length, 0);\n\t[self scrollRangeToVisible: range];\n\n\t[attrstr release];\n\t[string release];\n\t[file readInBackgroundAndNotify];\n}\n\n-(void)windowWillClose:(NSNotification *)notification\n{\n\t[task terminate];\n\t[NSApp terminate:self];\n}\n@end\n\nvoid runServer()\n{\n\tNSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];\n\tNSApp = [NSApplication sharedApplication];\n\tNSBundle* mainBundle = [NSBundle mainBundle];\n\tNSTask *task;\n\ttask = [[NSTask alloc] init];\n\t[task setCurrentDirectoryPath: [mainBundle resourcePath]];\n\n\t// get a server config\n\tNSOpenPanel* openDlg = [NSOpenPanel openPanel];\n\t[openDlg setCanChooseFiles:YES];\n\n\tif([openDlg runModalForDirectory:nil file:nil] != NSOKButton)\n\t\treturn;\n\n\tNSArray* filenames = [openDlg filenames];\n\tif([filenames count] != 1)\n\t\treturn;\n\n\tNSString* filename = [filenames objectAtIndex: 0];\n\tNSArray* arguments = [NSArray arrayWithObjects: @\"-f\", filename, nil];\n\n\t// run server\n\tNSWindow *window;\n\tServerView *view;\n\tNSRect graphicsRect;\n\n\tgraphicsRect = NSMakeRect(100.0, 1000.0, 600.0, 400.0);\n\n\twindow = [[NSWindow alloc]\n\t\tinitWithContentRect: graphicsRect\n\t\tstyleMask: NSTitledWindowMask\n\t\t| NSClosableWindowMask\n\t\t| NSMiniaturizableWindowMask\n\t\tbacking: NSBackingStoreBuffered\n\t\tdefer: NO];\n\n\t[window setTitle: @\"Teeworlds Server\"];\n\n\tview = [[[ServerView alloc] initWithFrame: graphicsRect] autorelease];\n\t[view setEditable: NO];\n\t[view setRulerVisible: YES];\n\n\t[window setContentView: view];\n\t[window setDelegate: view];\n\t[window makeKeyAndOrderFront: nil];\n\n\t[view listenTo: task];\n\t[task setLaunchPath: [mainBundle pathForAuxiliaryExecutable: @\"teeworlds_srv\"]];\n\t[task setArguments: arguments];\n\t[task launch];\n\t[NSApp run];\n\t[task terminate];\n\n\t[NSApp release];\n\t[pool release];\n}\n\nint main (int argc, char **argv)\n{\n\trunServer();\n\n\treturn 0;\n}\n"
  },
  {
    "path": "src/tools/crapnet.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n\n#include <cstdlib>\n\nstruct CPacket\n{\n\tCPacket *m_pPrev;\n\tCPacket *m_pNext;\n\n\tNETADDR m_SendTo;\n\tint64 m_Timestamp;\n\tint m_ID;\n\tint m_DataSize;\n\tchar m_aData[1];\n};\n\nstatic CPacket *m_pFirst = (CPacket *)0;\nstatic CPacket *m_pLast = (CPacket *)0;\nstatic int m_CurrentLatency = 0;\n\nstruct CPingConfig\n{\n\tint m_Base;\n\tint m_Flux;\n\tint m_Spike;\n\tint m_Loss;\n\tint m_Delay;\n\tint m_DelayFreq;\n};\n\nstatic CPingConfig m_aConfigPings[] = {\n//\t\tbase\tflux\tspike\tloss\tdelay\tdelayfreq\n\t\t{0,\t\t0,\t\t0,\t\t0,\t\t0,\t\t0},\n\t\t{40,\t20,\t\t100,\t\t0,\t\t0,\t\t0},\n\t\t{140,\t40,\t\t200,\t\t0,\t\t0,\t\t0},\n};\n\nstatic int m_ConfigNumpingconfs = sizeof(m_aConfigPings)/sizeof(CPingConfig);\nstatic int m_ConfigInterval = 10; // seconds between different pingconfigs\nstatic int m_ConfigLog = 0;\nstatic int m_ConfigReorder = 0;\n\nvoid Run(unsigned short Port, NETADDR Dest)\n{\n\tNETADDR Src = {NETTYPE_IPV4, {0,0,0,0}, Port};\n\tNETSOCKET Socket = net_udp_create(Src);\n\n\tchar aBuffer[1024*2];\n\tint ID = 0;\n\tint Delaycounter = 0;\n\n\twhile(1)\n\t{\n\t\tstatic int Lastcfg = 0;\n\t\tint n = ((time_get()/time_freq())/m_ConfigInterval) % m_ConfigNumpingconfs;\n\t\tCPingConfig Ping = m_aConfigPings[n];\n\n\t\tif(n != Lastcfg)\n\t\t\tdbg_msg(\"crapnet\", \"cfg = %d\", n);\n\t\tLastcfg = n;\n\n\t\t// handle incomming packets\n\t\twhile(1)\n\t\t{\n\t\t\t// fetch data\n\t\t\tint DataTrash = 0;\n\t\t\tNETADDR From;\n\t\t\tint Bytes = net_udp_recv(Socket, &From, aBuffer, 1024*2);\n\t\t\tif(Bytes <= 0)\n\t\t\t\tbreak;\n\n\t\t\tif((rand()%100) < Ping.m_Loss) // drop the packet\n\t\t\t{\n\t\t\t\tif(m_ConfigLog)\n\t\t\t\t\tdbg_msg(\"crapnet\", \"dropped packet\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// create new packet\n\t\t\tCPacket *p = (CPacket *)mem_alloc(sizeof(CPacket)+Bytes, 1);\n\n\t\t\tif(net_addr_comp(&From, &Dest) == 0)\n\t\t\t\tp->m_SendTo = Src; // from the server\n\t\t\telse\n\t\t\t{\n\t\t\t\tSrc = From; // from the client\n\t\t\t\tp->m_SendTo = Dest;\n\t\t\t}\n\n\t\t\t// queue packet\n\t\t\tp->m_pPrev = m_pLast;\n\t\t\tp->m_pNext = 0;\n\t\t\tif(m_pLast)\n\t\t\t\tm_pLast->m_pNext = p;\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_pFirst = p;\n\t\t\t\tm_pLast = p;\n\t\t\t}\n\t\t\tm_pLast = p;\n\n\t\t\t// set data in packet\n\t\t\tp->m_Timestamp = time_get();\n\t\t\tp->m_DataSize = Bytes;\n\t\t\tp->m_ID = ID++;\n\t\t\tmem_copy(p->m_aData, aBuffer, Bytes);\n\n\t\t\tif(ID > 20 && Bytes > 6 && DataTrash)\n\t\t\t{\n\t\t\t\tp->m_aData[6+(rand()%(Bytes-6))] = rand()&255; // modify a byte\n\t\t\t\tif((rand()%10) == 0)\n\t\t\t\t{\n\t\t\t\t\tp->m_DataSize -= rand()%32;\n\t\t\t\t\tif(p->m_DataSize < 6)\n\t\t\t\t\t\tp->m_DataSize = 6;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(Delaycounter <= 0)\n\t\t\t{\n\t\t\t\tif(Ping.m_Delay)\n\t\t\t\t\tp->m_Timestamp += (time_freq()*1000)/Ping.m_Delay;\n\t\t\t\tDelaycounter = Ping.m_DelayFreq;\n\t\t\t}\n\t\t\tDelaycounter--;\n\n\t\t\tif(m_ConfigLog)\n\t\t\t{\n\t\t\t\tchar aAddrStr[NETADDR_MAXSTRSIZE];\n\t\t\t\tnet_addr_str(&From, aAddrStr, sizeof(aAddrStr), true);\n\t\t\t\tdbg_msg(\"crapnet\", \"<< %08d %s (%d)\", p->m_ID, aAddrStr, p->m_DataSize);\n\t\t\t}\n\t\t}\n\n\t\t//\n\t\t/*while(1)\n\t\t{*/\n\t\tCPacket *p = 0;\n\t\tCPacket *pNext = m_pFirst;\n\t\twhile(1)\n\t\t{\n\t\t\tp = pNext;\n\t\t\tif(!p)\n\t\t\t\tbreak;\n\t\t\tpNext = p->m_pNext;\n\n\t\t\tif((time_get()-p->m_Timestamp) > m_CurrentLatency)\n\t\t\t{\n\t\t\t\tchar aFlags[] = \"  \";\n\n\t\t\t\tif(m_ConfigReorder && (rand()%2) == 0 && p->m_pNext)\n\t\t\t\t{\n\t\t\t\t\taFlags[0] = 'R';\n\t\t\t\t\tp = m_pFirst->m_pNext;\n\t\t\t\t}\n\n\t\t\t\tif(p->m_pNext)\n\t\t\t\t\tp->m_pNext->m_pPrev = p->m_pPrev;\n\t\t\t\telse\n\t\t\t\t\tm_pLast = p->m_pPrev;\n\n\t\t\t\tif(p->m_pPrev)\n\t\t\t\t\tp->m_pPrev->m_pNext = p->m_pNext;\n\t\t\t\telse\n\t\t\t\t\tm_pFirst = p->m_pNext;\n\n\t\t\t\t/*CPacket *cur = first;\n\t\t\t\twhile(cur)\n\t\t\t\t{\n\t\t\t\t\tdbg_assert(cur != p, \"p still in list\");\n\t\t\t\t\tcur = cur->next;\n\t\t\t\t}*/\n\n\t\t\t\t// send and remove packet\n\t\t\t\t//if((rand()%20) != 0) // heavy packetloss\n\t\t\t\tnet_udp_send(Socket, &p->m_SendTo, p->m_aData, p->m_DataSize);\n\n\t\t\t\t// update lag\n\t\t\t\tdouble Flux = rand()/(double)RAND_MAX;\n\t\t\t\tint MsSpike = Ping.m_Spike;\n\t\t\t\tint MsFlux = Ping.m_Flux;\n\t\t\t\tint MsPing = Ping.m_Base;\n\t\t\t\tm_CurrentLatency = ((time_freq()*MsPing)/1000) + (int64)(((time_freq()*MsFlux)/1000)*Flux); // 50ms\n\n\t\t\t\tif(MsSpike && (p->m_ID%100) == 0)\n\t\t\t\t{\n\t\t\t\t\tm_CurrentLatency += (time_freq()*MsSpike)/1000;\n\t\t\t\t\taFlags[1] = 'S';\n\t\t\t\t}\n\n\t\t\t\tif(m_ConfigLog)\n\t\t\t\t{\n\t\t\t\t\tchar aAddrStr[NETADDR_MAXSTRSIZE];\n\t\t\t\t\tnet_addr_str(&p->m_SendTo, aAddrStr, sizeof(aAddrStr), true);\n\t\t\t\t\tdbg_msg(\"crapnet\", \">> %08d %s (%d) %s\", p->m_ID, aAddrStr, p->m_DataSize, aFlags);\n\t\t\t\t}\n\n\n\t\t\t\tmem_free(p);\n\t\t\t}\n\t\t}\n\n\t\tthread_sleep(1);\n\t}\n}\n\nint main(int argc, char **argv) // ignore_convention\n{\n\tNETADDR Addr = {NETTYPE_IPV4, {127,0,0,1},8303};\n\tdbg_logger_stdout();\n\tRun(8302, Addr);\n\treturn 0;\n}\n"
  },
  {
    "path": "src/tools/dilate.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n#include <base/math.h>\n#include <engine/external/pnglite/pnglite.h>\n\ntypedef struct\n{\n\tunsigned char r, g, b, a;\n} CPixel;\n\nstatic void Dilate(int w, int h, CPixel *pSrc, CPixel *pDest)\n{\n\tint ix, iy;\n\tconst int xo[] = {0, -1, 1, 0};\n\tconst int yo[] = {-1, 0, 0, 1};\n\n\tint m = 0;\n\tfor(int y = 0; y < h; y++)\n\t{\n\t\tfor(int x = 0; x < w; x++, m++)\n\t\t{\n\t\t\tpDest[m] = pSrc[m];\n\t\t\tif(pSrc[m].a)\n\t\t\t\tcontinue;\n\n\t\t\tfor(int c = 0; c < 4; c++)\n\t\t\t{\n\t\t\t\tix = clamp(x + xo[c], 0, w-1);\n\t\t\t\tiy = clamp(y + yo[c], 0, h-1);\n\t\t\t\tint k = iy*w+ix;\n\t\t\t\tif(pSrc[k].a)\n\t\t\t\t{\n\t\t\t\t\tpDest[m] = pSrc[k];\n\t\t\t\t\tpDest[m].a = 255;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nstatic void CopyAlpha(int w, int h, CPixel *pSrc, CPixel *pDest)\n{\n\tint m = 0;\n\tfor(int y = 0; y < h; y++)\n\t\tfor(int x = 0; x < w; x++, m++)\n\t\t\tpDest[m].a = pSrc[m].a;\n}\n\nint DilateFile(const char *pFileName)\n{\n\tpng_t Png;\n\tCPixel *pBuffer[3] = {0,0,0};\n\n\tpng_init(0, 0);\n\tpng_open_file(&Png, pFileName);\n\n\tif(Png.color_type != PNG_TRUECOLOR_ALPHA)\n\t{\n\t\tdbg_msg(\"dilate\", \"%s: not an RGBA image\", pFileName);\n\t\treturn 1;\n\t}\n\n\tpBuffer[0] = (CPixel*)mem_alloc(Png.width*Png.height*sizeof(CPixel), 1);\n\tpBuffer[1] = (CPixel*)mem_alloc(Png.width*Png.height*sizeof(CPixel), 1);\n\tpBuffer[2] = (CPixel*)mem_alloc(Png.width*Png.height*sizeof(CPixel), 1);\n\tpng_get_data(&Png, (unsigned char *)pBuffer[0]);\n\tpng_close_file(&Png);\n\n\tint w = Png.width;\n\tint h = Png.height;\n\n\tDilate(w, h, pBuffer[0], pBuffer[1]);\n\tfor(int i = 0; i < 5; i++)\n\t{\n\t\tDilate(w, h, pBuffer[1], pBuffer[2]);\n\t\tDilate(w, h, pBuffer[2], pBuffer[1]);\n\t}\n\n\tCopyAlpha(w, h, pBuffer[0], pBuffer[1]);\n\n\t// save here\n\tpng_open_file_write(&Png, pFileName);\n\tpng_set_data(&Png, w, h, 8, PNG_TRUECOLOR_ALPHA, (unsigned char *)pBuffer[1]);\n\tpng_close_file(&Png);\n\n\treturn 0;\n}\n\nint main(int argc, const char **argv)\n{\n\tdbg_logger_stdout();\n\tif(argc == 1)\n\t{\n\t\tdbg_msg(\"Usage\", \"%s FILE1 [ FILE2... ]\", argv[0]);\n\t\treturn -1;\n\t}\n\n\tfor(int i = 1; i < argc; i++)\n\t\tDilateFile(argv[i]);\n\treturn 0;\n}\n"
  },
  {
    "path": "src/tools/fake_server.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <stdlib.h> //rand\n#include <base/system.h>\n#include <engine/shared/config.h>\n#include <engine/shared/network.h>\n#include <mastersrv/mastersrv.h>\n\nCNetServer *pNet;\n\nint Progression = 50;\nint GameType = 0;\nint Flags = 0;\n\nconst char *pVersion = \"trunk\";\nconst char *pMap = \"somemap\";\nconst char *pServerName = \"unnamed server\";\n\nNETADDR aMasterServers[16] = {{0,{0},0}};\nint NumMasters = 0;\n\nconst char *PlayerNames[16] = {0};\nint PlayerScores[16] = {0};\nint NumPlayers = 0;\nint MaxPlayers = 0;\n\nchar aInfoMsg[1024];\nint aInfoMsgSize;\n\nstatic void SendHeartBeats()\n{\n\tstatic unsigned char aData[sizeof(SERVERBROWSE_HEARTBEAT) + 2];\n\tCNetChunk Packet;\n\n\tmem_copy(aData, SERVERBROWSE_HEARTBEAT, sizeof(SERVERBROWSE_HEARTBEAT));\n\n\tPacket.m_ClientID = -1;\n\tPacket.m_Flags = NETSENDFLAG_CONNLESS;\n\tPacket.m_DataSize = sizeof(SERVERBROWSE_HEARTBEAT) + 2;\n\tPacket.m_pData = &aData;\n\n\t/* supply the set port that the master can use if it has problems */\n\taData[sizeof(SERVERBROWSE_HEARTBEAT)] = 0;\n\taData[sizeof(SERVERBROWSE_HEARTBEAT)+1] = 0;\n\n\tfor(int i = 0; i < NumMasters; i++)\n\t{\n\t\tPacket.m_Address = aMasterServers[i];\n\t\tpNet->Send(&Packet);\n\t}\n}\n\nstatic void WriteStr(const char *pStr)\n{\n\tint l = str_length(pStr)+1;\n\tmem_copy(&aInfoMsg[aInfoMsgSize], pStr, l);\n\taInfoMsgSize += l;\n}\n\nstatic void WriteInt(int i)\n{\n\tchar aBuf[64];\n\tstr_format(aBuf, sizeof(aBuf), \"%d\", i);\n\tWriteStr(aBuf);\n}\n\nstatic void BuildInfoMsg()\n{\n\taInfoMsgSize = sizeof(SERVERBROWSE_INFO);\n\tmem_copy(aInfoMsg, SERVERBROWSE_INFO, aInfoMsgSize);\n\tWriteInt(-1);\n\n\tWriteStr(pVersion);\n\tWriteStr(pServerName);\n\tWriteStr(pMap);\n\tWriteInt(GameType);\n\tWriteInt(Flags);\n\tWriteInt(Progression);\n\tWriteInt(NumPlayers);\n\tWriteInt(MaxPlayers);\n\n\tfor(int i = 0; i < NumPlayers; i++)\n\t{\n\t\tWriteStr(PlayerNames[i]);\n\t\tWriteInt(PlayerScores[i]);\n\t}\n}\n\nstatic void SendServerInfo(NETADDR *pAddr)\n{\n\tCNetChunk p;\n\tp.m_ClientID = -1;\n\tp.m_Address = *pAddr;\n\tp.m_Flags = NETSENDFLAG_CONNLESS;\n\tp.m_DataSize = aInfoMsgSize;\n\tp.m_pData = aInfoMsg;\n\tpNet->Send(&p);\n}\n\nstatic void SendFWCheckResponse(NETADDR *pAddr)\n{\n\tCNetChunk p;\n\tp.m_ClientID = -1;\n\tp.m_Address = *pAddr;\n\tp.m_Flags = NETSENDFLAG_CONNLESS;\n\tp.m_DataSize = sizeof(SERVERBROWSE_FWRESPONSE);\n\tp.m_pData = SERVERBROWSE_FWRESPONSE;\n\tpNet->Send(&p);\n}\n\nstatic int Run()\n{\n\tint64 NextHeartBeat = 0;\n\tNETADDR BindAddr = {NETTYPE_IPV4, {0},0};\n\n\tif(!pNet->Open(BindAddr, 0, 0, 0, 0))\n\t\treturn 0;\n\n\twhile(1)\n\t{\n\t\tCNetChunk p;\n\t\tpNet->Update();\n\t\twhile(pNet->Recv(&p))\n\t\t{\n\t\t\tif(p.m_ClientID == -1)\n\t\t\t{\n\t\t\t\tif(p.m_DataSize == sizeof(SERVERBROWSE_GETINFO) &&\n\t\t\t\t\tmem_comp(p.m_pData, SERVERBROWSE_GETINFO, sizeof(SERVERBROWSE_GETINFO)) == 0)\n\t\t\t\t{\n\t\t\t\t\tSendServerInfo(&p.m_Address);\n\t\t\t\t}\n\t\t\t\telse if(p.m_DataSize == sizeof(SERVERBROWSE_FWCHECK) &&\n\t\t\t\t\tmem_comp(p.m_pData, SERVERBROWSE_FWCHECK, sizeof(SERVERBROWSE_FWCHECK)) == 0)\n\t\t\t\t{\n\t\t\t\t\tSendFWCheckResponse(&p.m_Address);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/* send heartbeats if needed */\n\t\tif(NextHeartBeat < time_get())\n\t\t{\n\t\t\tNextHeartBeat = time_get()+time_freq()*(15+(rand()%15));\n\t\t\tSendHeartBeats();\n\t\t}\n\n\t\tthread_sleep(100);\n\t}\n}\n\nint main(int argc, char **argv)\n{\n\tpNet = new CNetServer;\n\n\twhile(argc)\n\t{\n\t\t// ?\n\t\t/*if(str_comp(*argv, \"-m\") == 0)\n\t\t{\n\t\t\targc--; argv++;\n\t\t\tnet_host_lookup(*argv, &aMasterServers[NumMasters], NETTYPE_IPV4);\n\t\t\targc--; argv++;\n\t\t\taMasterServers[NumMasters].port = str_toint(*argv);\n\t\t\tNumMasters++;\n\t\t}\n\t\telse */if(str_comp(*argv, \"-p\") == 0)\n\t\t{\n\t\t\targc--; argv++;\n\t\t\tPlayerNames[NumPlayers++] = *argv;\n\t\t\targc--; argv++;\n\t\t\tPlayerScores[NumPlayers] = str_toint(*argv);\n\t\t}\n\t\telse if(str_comp(*argv, \"-a\") == 0)\n\t\t{\n\t\t\targc--; argv++;\n\t\t\tpMap = *argv;\n\t\t}\n\t\telse if(str_comp(*argv, \"-x\") == 0)\n\t\t{\n\t\t\targc--; argv++;\n\t\t\tMaxPlayers = str_toint(*argv);\n\t\t}\n\t\telse if(str_comp(*argv, \"-t\") == 0)\n\t\t{\n\t\t\targc--; argv++;\n\t\t\tGameType = str_toint(*argv);\n\t\t}\n\t\telse if(str_comp(*argv, \"-g\") == 0)\n\t\t{\n\t\t\targc--; argv++;\n\t\t\tProgression = str_toint(*argv);\n\t\t}\n\t\telse if(str_comp(*argv, \"-f\") == 0)\n\t\t{\n\t\t\targc--; argv++;\n\t\t\tFlags = str_toint(*argv);\n\t\t}\n\t\telse if(str_comp(*argv, \"-n\") == 0)\n\t\t{\n\t\t\targc--; argv++;\n\t\t\tpServerName = *argv;\n\t\t}\n\n\t\targc--; argv++;\n\t}\n\n\tBuildInfoMsg();\n\tint RunReturn = Run();\n\n\tdelete pNet;\n\treturn RunReturn;\n}\n\n"
  },
  {
    "path": "src/tools/map_resave.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n#include <engine/shared/datafile.h>\n#include <engine/storage.h>\n\nint main(int argc, const char **argv)\n{\n\tIStorage *pStorage = CreateStorage(\"Teeworlds\", IStorage::STORAGETYPE_BASIC, argc, argv);\n\tint Index, ID = 0, Type = 0, Size;\n\tvoid *pPtr;\n\tchar aFileName[1024];\n\tCDataFileReader DataFile;\n\tCDataFileWriter df;\n\n\tif(!pStorage || argc != 3)\n\t\treturn -1;\n\n\tstr_format(aFileName, sizeof(aFileName), \"%s\", argv[2]);\n\n\tif(!DataFile.Open(pStorage, argv[1], IStorage::TYPE_ALL))\n\t\treturn -1;\n\tif(!df.Open(pStorage, aFileName))\n\t\treturn -1;\n\n\t// add all items\n\tfor(Index = 0; Index < DataFile.NumItems(); Index++)\n\t{\n\t\tpPtr = DataFile.GetItem(Index, &Type, &ID);\n\t\tSize = DataFile.GetItemSize(Index);\n\t\tdf.AddItem(Type, ID, Size, pPtr);\n\t}\n\n\t// add all data\n\tfor(Index = 0; Index < DataFile.NumData(); Index++)\n\t{\n\t\tpPtr = DataFile.GetData(Index);\n\t\tSize = DataFile.GetDataSize(Index);\n\t\tdf.AddData(Size, pPtr);\n\t}\n\n\tDataFile.Close();\n\tdf.Finish();\n\treturn 0;\n}\n"
  },
  {
    "path": "src/tools/map_version.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/math.h>\n#include <base/system.h>\n\n#include <engine/kernel.h>\n#include <engine/map.h>\n#include <engine/storage.h>\n\n\nstatic IOHANDLE s_File = 0;\nstatic IStorage *s_pStorage = 0;\nstatic IEngineMap *s_pEngineMap = 0;\n\nint MaplistCallback(const char *pName, int IsDir, int DirType, void *pUser)\n{\n\tint l = str_length(pName);\n\tif(l < 4 || IsDir || str_comp(pName+l-4, \".map\") != 0)\n\t\treturn 0;\n\n\tchar aBuf[128];\n\tstr_format(aBuf, sizeof(aBuf), \"maps/%s\", pName);\n\tif(!s_pEngineMap->Load(aBuf))\n\t\treturn 0;\n\n\tunsigned MapCrc = s_pEngineMap->Crc();\n\ts_pEngineMap->Unload();\n\n\tIOHANDLE MapFile = s_pStorage->OpenFile(aBuf, IOFLAG_READ, DirType);\n\tunsigned MapSize = io_length(MapFile);\n\tio_close(MapFile);\n\n\tchar aMapName[8];\n\tstr_copy(aMapName, pName, min((int)sizeof(aMapName),l-3));\n\n\tstr_format(aBuf, sizeof(aBuf), \"\\t{\\\"%s\\\", {0x%02x, 0x%02x, 0x%02x, 0x%02x}, {0x%02x, 0x%02x, 0x%02x, 0x%02x}},\\n\", aMapName,\n\t\t(MapCrc>>24)&0xff, (MapCrc>>16)&0xff, (MapCrc>>8)&0xff, MapCrc&0xff,\n\t\t(MapSize>>24)&0xff, (MapSize>>16)&0xff, (MapSize>>8)&0xff, MapSize&0xff);\n\tio_write(s_File, aBuf, str_length(aBuf));\n\n\treturn 0;\n}\n\nint main(int argc, const char **argv) // ignore_convention\n{\n\tIKernel *pKernel = IKernel::Create();\n\ts_pStorage = CreateStorage(\"Teeworlds\", IStorage::STORAGETYPE_BASIC, argc, argv);\n\ts_pEngineMap = CreateEngineMap();\n\n\tbool RegisterFail = !pKernel->RegisterInterface(s_pStorage);\n\tRegisterFail |= !pKernel->RegisterInterface(s_pEngineMap);\n\n\tif(RegisterFail)\n\t\treturn -1;\n\n\ts_File = s_pStorage->OpenFile(\"map_version.txt\", IOFLAG_WRITE, 1);\n\tif(s_File)\n\t{\n\t\tio_write(s_File, \"static CMapVersion s_aMapVersionList[] = {\\n\", str_length(\"static CMapVersion s_aMapVersionList[] = {\\n\"));\n\t\ts_pStorage->ListDirectory(1, \"maps\", MaplistCallback, 0);\n\t\tio_write(s_File, \"};\\n\", str_length(\"};\\n\"));\n\t\tio_close(s_File);\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "src/tools/packetgen.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n\nenum { NUM_SOCKETS = 64 };\n\nvoid Run(NETADDR Dest)\n{\n\tNETSOCKET aSockets[NUM_SOCKETS];\n\n\tfor(int i = 0; i < NUM_SOCKETS; i++)\n\t{\n\t\tNETADDR BindAddr = {NETTYPE_IPV4, {0}, 0};\n\t \taSockets[i] = net_udp_create(BindAddr);\n\t}\n\n\twhile(1)\n\t{\n\t\tunsigned char aData[1024];\n\t\tint Size = 0;\n\t\tint SocketToUse = 0;\n\t\tio_read(io_stdin(), &Size, 2);\n\t\tio_read(io_stdin(), &SocketToUse, 1);\n\t\tSize %= 256;\n\t\tSocketToUse %= NUM_SOCKETS;\n\t\tio_read(io_stdin(), aData, Size);\n\t\tnet_udp_send(aSockets[SocketToUse], &Dest, aData, Size);\n\t}\n}\n\nint main(int argc, char **argv)\n{\n\tNETADDR Dest = {NETTYPE_IPV4, {127,0,0,1}, 8303};\n\tRun(Dest);\n\treturn 0;\n}\n"
  },
  {
    "path": "src/tools/tileset_borderop.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/math.h>\n#include <base/system.h>\n#include <engine/external/pnglite/pnglite.h>\n\n\nenum\n{\n\tOP_ADD=0,\n\tOP_FIX,\n\tOP_REM,\n\tOP_SET\n};\n\ntypedef struct\n{\n\tunsigned char r, g, b, a;\n} CPixel;\n\n\nvoid TilesetBorderAdd(int w, int h, CPixel *pSrc, CPixel *pDest)\n{\n\tint TileW = w/16;\n\tint TileH = h/16;\n\n\tfor(int tx = 0; tx < 16; tx++)\n\t{\n\t\tfor(int ty = 0; ty < 16; ty++)\n\t\t{\n\t\t\tfor(int x = 0; x < TileW + 4; x++)\n\t\t\t{\n\t\t\t\tfor(int y = 0; y < TileH + 4; y++)\n\t\t\t\t{\n\t\t\t\t\tint SourceX = tx * TileW + clamp(x - 2, 0, TileW - 1);\n\t\t\t\t\tint SourceY = ty * TileH + clamp(y - 2, 0, TileH - 1);\n\t\t\t\t\tint DestX = tx * (TileW + 4) + x;\n\t\t\t\t\tint DestY = ty * (TileH + 4) + y;\n\n\t\t\t\t\tint SourceI = SourceY * w + SourceX;\n\t\t\t\t\tint DestI = DestY * (w + 16 * 4) + DestX;\n\n\t\t\t\t\tpDest[DestI] = pSrc[SourceI];\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nCPixel Sample(int x, int y, int w, int h, CPixel *pData, int Pitch, float u, float v)\n{\n\tx = x + (int)(w*u);\n\ty = y + (int)(h*v);\n\treturn pData[y*Pitch+x];\n}\n\nvoid TilesetBorderFix(int w, int h, CPixel *pSrc, CPixel *pDest)\n{\n\tint TileW = w/16;\n\tint TileH = h/16;\n\n\tmem_zero(pDest, sizeof(CPixel)*w*h);\n\n\tfor(int ty = 0; ty < 16; ty++)\n\t{\n\t\tfor(int tx = 0; tx < 16; tx++)\n\t\t{\n\t\t\tfor(int y = 0; y < TileH-2; y++)\n\t\t\t{\n\t\t\t\tfor(int x = 0; x < TileW-2; x++)\n\t\t\t\t{\n\t\t\t\t\tfloat u = 0.5f/TileW + x/(float)(TileW-2);\n\t\t\t\t\tfloat v = 0.5f/TileH + y/(float)(TileH-2);\n\t\t\t\t\tint k = (ty*TileH+1+y)*w + tx*TileW+x+1;\n\t\t\t\t\tpDest[k] = Sample(tx*TileW, ty*TileH, TileW, TileH, pSrc, w, u, v);\n\n\t\t\t\t\tif(x == 0) pDest[k-1] = pDest[k];\n\t\t\t\t\tif(x == TileW-2-1) pDest[k+1] = pDest[k];\n\t\t\t\t\tif(y == 0) pDest[k-w] = pDest[k];\n\t\t\t\t\tif(y == TileH-2-1) pDest[k+w] = pDest[k];\n\n\t\t\t\t\tif(x == 0 && y == 0) pDest[k-w-1] = pDest[k];\n\t\t\t\t\tif(x == TileW-2-1 && y == 0) pDest[k-w+1] = pDest[k];\n\t\t\t\t\tif(x == 0 && y == TileH-2-1) pDest[k+w-1] = pDest[k];\n\t\t\t\t\tif(x == TileW-2-1 && y == TileH-2-1) pDest[k+w+1] = pDest[k];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nvoid TilesetBorderRem(int w, int h, CPixel *pSrc, CPixel *pDest)\n{\n\tint TileW = w/16;\n\tint TileH = h/16;\n\n\tfor(int tx = 0; tx < 16; tx++)\n\t{\n\t\tfor(int ty = 0; ty < 16; ty++)\n\t\t{\n\t\t\tfor(int x = 0; x < TileW - 4; x++)\n\t\t\t{\n\t\t\t\tfor(int y = 0; y < TileH - 4; y++)\n\t\t\t\t{\n\t\t\t\t\tint SourceX = tx * TileW + x + 2;\n\t\t\t\t\tint SourceY = ty * TileH + y + 2;\n\t\t\t\t\tint DestX = tx * (TileW - 4) + x;\n\t\t\t\t\tint DestY = ty * (TileH - 4) + y;\n\n\t\t\t\t\tint SourceI = SourceY * w + SourceX;\n\t\t\t\t\tint DestI = DestY * (w - 16 * 4) + DestX;\n\n\t\t\t\t\tpDest[DestI] = pSrc[SourceI];\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nvoid TilesetBorderSet(int w, int h, CPixel *pSrc, CPixel *pDest)\n{\n\tint TileW = w/16;\n\tint TileH = h/16;\n\n\tfor(int tx = 0; tx < 16; tx++)\n\t{\n\t\tfor(int ty = 0; ty < 16; ty++)\n\t\t{\n\t\t\tfor(int x = 0; x < TileW; x++)\n\t\t\t{\n\t\t\t\tfor(int y = 0; y < TileH; y++)\n\t\t\t\t{\n\t\t\t\t\t#define TILE_INDEX(tx_, ty_, x_, y_) (((ty_) * TileH + (y_)) * w + (tx_) * TileW + (x_))\n\t\t\t\t\tpDest[TILE_INDEX(tx, ty, x, y)] = pSrc[TILE_INDEX(tx, ty, clamp(x, 2, TileW - 3), clamp(y, 2, TileH - 3))];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nvoid ProcessFile(const char *pFileName, int WidthMod, int HeightMod, int Operator)\n{\n\tpng_t Png;\n\tCPixel *pBuffer[2] = {0,0};\n\n\tpng_init(0, 0);\n\tpng_open_file(&Png, pFileName);\n\n\tif(Png.color_type != PNG_TRUECOLOR_ALPHA)\n\t{\n\t\tdbg_msg(\"tileset_borderop\", \"%s: not an RGBA image\", pFileName);\n\t\treturn;\n\t}\n\n\tint w = Png.width;\n\tint h = Png.height;\n\n\tpBuffer[0] = (CPixel*)mem_alloc(w*h*sizeof(CPixel), 1);\n\tpBuffer[1] = (CPixel*)mem_alloc((w+WidthMod)*(h+HeightMod)*sizeof(CPixel), 1);\n\tpng_get_data(&Png, (unsigned char *)pBuffer[0]);\n\tpng_close_file(&Png);\n\n\tswitch(Operator)\n\t{\n\tcase OP_ADD: TilesetBorderAdd(w, h, pBuffer[0], pBuffer[1]); break;\n\tcase OP_FIX: TilesetBorderFix(w, h, pBuffer[0], pBuffer[1]); break;\n\tcase OP_REM: TilesetBorderRem(w, h, pBuffer[0], pBuffer[1]); break;\n\tcase OP_SET: TilesetBorderSet(w, h, pBuffer[0], pBuffer[1]); break;\n\t}\n\n\t// save here\n\tpng_open_file_write(&Png, pFileName);\n\tpng_set_data(&Png, w + WidthMod, h + HeightMod, 8, PNG_TRUECOLOR_ALPHA, (unsigned char *)pBuffer[1]);\n\tpng_close_file(&Png);\n}\n\nint main(int argc, const char **argv)\n{\n\tdbg_logger_stdout();\n\tif(argc < 3)\n\t{\n\t\tdbg_msg(\"Usage\", \"%s OPERATION FILE1 [ FILE2... ]\", argv[0]);\n\t\tdbg_msg(\"Usage\", \"OPERATION - ADD, FIX, REM, SET\");\n\t\treturn -1;\n\t}\n\n\tint WidthMod, HeightMod, Operator;\n\n\tif(str_comp_nocase(argv[1], \"ADD\") == 0)\n\t{\n\t\tWidthMod = 16*4;\n\t\tHeightMod = 16*4;\n\t\tOperator = OP_ADD;\n\t}\n\telse if(str_comp_nocase(argv[1], \"FIX\") == 0)\n\t{\n\t\tWidthMod = 0;\n\t\tHeightMod = 0;\n\t\tOperator = OP_FIX;\n\t}\n\telse if(str_comp_nocase(argv[1], \"REM\") == 0)\n\t{\n\t\tWidthMod = -16*4;\n\t\tHeightMod = -16*4;\n\t\tOperator = OP_REM;\n\t}\n\telse if(str_comp_nocase(argv[1], \"SET\") == 0)\n\t{\n\t\tWidthMod = 0;\n\t\tHeightMod = 0;\n\t\tOperator = OP_SET;\n\t}\n\telse\n\t{\n\t\tdbg_msg(\"Usage\", \"invalid OPERATION (ADD, FIX, REM, SET)\");\n\t\treturn -1;\n\t}\n\n\tfor(int i = 2; i < argc; i++)\n\t\tProcessFile(argv[i], WidthMod, HeightMod, Operator);\n\t\n\treturn 0;\n}\n"
  },
  {
    "path": "src/versionsrv/mapversions.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef VERSIONSRV_MAPVERSIONS_H\n#define VERSIONSRV_MAPVERSIONS_H\n\nstatic CMapVersion s_aMapVersionList[] = {\n\t{\"ctf1\", {0x06, 0xb5, 0xf1, 0x17}, {0x00, 0x00, 0x12, 0x38}},\n\t{\"ctf2\", {0x27, 0xbc, 0x5e, 0xac}, {0x00, 0x00, 0x64, 0x1a}},\n\t{\"ctf3\", {0xa3, 0x73, 0x9d, 0x41}, {0x00, 0x00, 0x17, 0x0f}},\n\t{\"ctf4\", {0xbe, 0x7c, 0x4d, 0xb9}, {0x00, 0x00, 0x2e, 0xfe}},\n\t{\"ctf5\", {0xd9, 0x21, 0x29, 0xa0}, {0x00, 0x00, 0x2f, 0x4c}},\n\t{\"ctf6\", {0x28, 0xc8, 0x43, 0x51}, {0x00, 0x00, 0x69, 0x2f}},\n\t{\"ctf7\", {0x1d, 0x35, 0x98, 0x72}, {0x00, 0x00, 0x15, 0x87}},\n\t{\"dm1\", {0xf2, 0x15, 0x9e, 0x6e}, {0x00, 0x00, 0x16, 0xad}},\n\t{\"dm2\", {0x71, 0x83, 0x98, 0x78}, {0x00, 0x00, 0x21, 0xdf}},\n\t{\"dm6\", {0x47, 0x4d, 0xa2, 0x35}, {0x00, 0x00, 0x1e, 0x95}},\n\t{\"dm7\", {0x42, 0x6d, 0xa1, 0x67}, {0x00, 0x00, 0x27, 0x2a}},\n\t{\"dm8\", {0x2f, 0x74, 0xd9, 0x18}, {0x00, 0x00, 0xa1, 0xa1}},\n\t{\"dm9\", {0x42, 0xd4, 0x77, 0x7e}, {0x00, 0x00, 0x20, 0x11}},\n};\nstatic const int s_NumMapVersionItems = sizeof(s_aMapVersionList)/sizeof(CMapVersion);\n#endif\n"
  },
  {
    "path": "src/versionsrv/versionsrv.cpp",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#include <base/system.h>\n\n#include <engine/shared/network.h>\n\n#include <game/version.h>\n\n#include \"versionsrv.h\"\n#include \"mapversions.h\"\n\nenum {\n\tMAX_MAPS_PER_PACKET=48,\n\tMAX_PACKETS=16,\n\tMAX_MAPS=MAX_MAPS_PER_PACKET*MAX_PACKETS,\n};\n\nstruct CPacketData\n{\n\tint m_Size;\n\tstruct {\n\t\tunsigned char m_aHeader[sizeof(VERSIONSRV_MAPLIST)];\n\t\tCMapVersion m_aMaplist[MAX_MAPS_PER_PACKET];\n\t} m_Data;\n};\n\nCPacketData m_aPackets[MAX_PACKETS];\nstatic int m_NumPackets = 0;\n\nstatic CNetClient g_NetOp; // main\n\nvoid BuildPackets()\n{\n\tCMapVersion *pCurrent = &s_aMapVersionList[0];\n\tint ServersLeft = s_NumMapVersionItems;\n\tm_NumPackets = 0;\n\twhile(ServersLeft && m_NumPackets < MAX_PACKETS)\n\t{\n\t\tint Chunk = ServersLeft;\n\t\tif(Chunk > MAX_MAPS_PER_PACKET)\n\t\t\tChunk = MAX_MAPS_PER_PACKET;\n\t\tServersLeft -= Chunk;\n\n\t\t// copy header\n\t\tmem_copy(m_aPackets[m_NumPackets].m_Data.m_aHeader, VERSIONSRV_MAPLIST, sizeof(VERSIONSRV_MAPLIST));\n\n\t\t// copy map versions\n\t\tfor(int i = 0; i < Chunk; i++)\n\t\t{\n\t\t\tm_aPackets[m_NumPackets].m_Data.m_aMaplist[i] = *pCurrent;\n\t\t\tpCurrent++;\n\t\t}\n\n\t\tm_aPackets[m_NumPackets].m_Size = sizeof(VERSIONSRV_MAPLIST) + sizeof(CMapVersion)*Chunk;\n\n\t\tm_NumPackets++;\n\t}\n}\n\nvoid SendVer(NETADDR *pAddr)\n{\n\tCNetChunk p;\n\tunsigned char aData[sizeof(VERSIONSRV_VERSION) + sizeof(GAME_RELEASE_VERSION)];\n\n\tmem_copy(aData, VERSIONSRV_VERSION, sizeof(VERSIONSRV_VERSION));\n\tmem_copy(aData + sizeof(VERSIONSRV_VERSION), GAME_RELEASE_VERSION, sizeof(GAME_RELEASE_VERSION));\n\n\tp.m_ClientID = -1;\n\tp.m_Address = *pAddr;\n\tp.m_Flags = NETSENDFLAG_CONNLESS;\n\tp.m_pData = aData;\n\tp.m_DataSize = sizeof(aData);\n\n\tg_NetOp.Send(&p);\n}\n\nint main(int argc, char **argv) // ignore_convention\n{\n\tNETADDR BindAddr;\n\n\tdbg_logger_stdout();\n\tnet_init();\n\n\tmem_zero(&BindAddr, sizeof(BindAddr));\n\tBindAddr.type = NETTYPE_ALL;\n\tBindAddr.port = VERSIONSRV_PORT;\n\tif(!g_NetOp.Open(BindAddr, 0))\n\t{\n\t\tdbg_msg(\"mastersrv\", \"couldn't start network\");\n\t\treturn -1;\n\t}\n\n\tBuildPackets();\n\n\tdbg_msg(\"versionsrv\", \"started\");\n\n\twhile(1)\n\t{\n\t\tg_NetOp.Update();\n\n\t\t// process packets\n\t\tCNetChunk Packet;\n\t\twhile(g_NetOp.Recv(&Packet))\n\t\t{\n\t\t\tif(Packet.m_DataSize == sizeof(VERSIONSRV_GETVERSION) &&\n\t\t\t\tmem_comp(Packet.m_pData, VERSIONSRV_GETVERSION, sizeof(VERSIONSRV_GETVERSION)) == 0)\n\t\t\t{\n\t\t\t\tSendVer(&Packet.m_Address);\n\t\t\t}\n\n\t\t\tif(Packet.m_DataSize == sizeof(VERSIONSRV_GETMAPLIST) &&\n\t\t\t\tmem_comp(Packet.m_pData, VERSIONSRV_GETMAPLIST, sizeof(VERSIONSRV_GETMAPLIST)) == 0)\n\t\t\t{\n\t\t\t\tCNetChunk p;\n\t\t\t\tp.m_ClientID = -1;\n\t\t\t\tp.m_Address = Packet.m_Address;\n\t\t\t\tp.m_Flags = NETSENDFLAG_CONNLESS;\n\n\t\t\t\tfor(int i = 0; i < m_NumPackets; i++)\n\t\t\t\t{\n\t\t\t\t\tp.m_DataSize = m_aPackets[i].m_Size;\n\t\t\t\t\tp.m_pData = &m_aPackets[i].m_Data;\n\t\t\t\t\tg_NetOp.Send(&p);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// be nice to the CPU\n\t\tthread_sleep(1);\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "src/versionsrv/versionsrv.h",
    "content": "/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n/* If you are missing that file, acquire a complete release at teeworlds.com.                */\n#ifndef VERSIONSRV_VERSIONSRV_H\n#define VERSIONSRV_VERSIONSRV_H\nstatic const int VERSIONSRV_PORT = 8302;\n\nstruct CMapVersion\n{\n\tchar m_aName[8];\n\tunsigned char m_aCrc[4];\n\tunsigned char m_aSize[4];\n};\n\nstatic const unsigned char VERSIONSRV_GETVERSION[] = {255, 255, 255, 255, 'v', 'e', 'r', 'g'};\nstatic const unsigned char VERSIONSRV_VERSION[] = {255, 255, 255, 255, 'v', 'e', 'r', 's'};\n\nstatic const unsigned char VERSIONSRV_GETMAPLIST[] = {255, 255, 255, 255, 'v', 'm', 'l', 'g'};\nstatic const unsigned char VERSIONSRV_MAPLIST[] = {255, 255, 255, 255, 'v', 'm', 'l', 's'};\n#endif\n"
  },
  {
    "path": "storage.cfg",
    "content": "####\n# This specifies where and in which order Teeworlds looks\n# for its data (sounds, skins, ...). The search goes top\n# down which means the first path has the highest priority.\n# Furthermore the top entry also defines the save path where\n# all data (settings.cfg, screenshots, ...) are stored.\n# There are 3 special paths available:\n#\t$USERDIR\n#\t- ~/.appname on UNIX based systems\n#\t- ~/Library/Applications Support/appname on Mac OS X\n#\t- %APPDATA%/Appname on Windows based systems\n#\t$DATADIR\n#\t- the 'data' directory which is part of an official\n#\trelease\n#\t$CURRENTDIR\n#\t- current working directory\n#\n#\n# The default file has the following entries:\n#\tadd_path $USERDIR\n#\tadd_path $DATADIR\n#\tadd_path $CURRENTDIR\n#\n# A customised one could look like this:\n#\tadd_path user\n#\tadd_path mods/mymod\n####\n\nadd_path $USERDIR\nadd_path $DATADIR\nadd_path $CURRENTDIR\n"
  }
]